diff --git a/.gitignore b/.gitignore index 210834c6a85..8f160116e5b 100644 --- a/.gitignore +++ b/.gitignore @@ -22,7 +22,17 @@ samples/server-generator/scalatra/output samples/server-generator/node/output/node_modules samples/server-generator/scalatra/target samples/server-generator/scalatra/output/.history - +samples/client/petstore/qt5cpp/PetStore/moc_* +samples/client/petstore/qt5cpp/PetStore/*.o +samples/client/petstore/objc/PetstoreClient.xcworkspace/xcuserdata +samples/client/petstore/qt5cpp/build-* +samples/client/petstore/qt5cpp/PetStore/PetStore +samples/client/petstore/qt5cpp/PetStore/Makefile +samples/client/petstore/java/hello.txt +samples/client/petstore/android-java/hello.txt +samples/client/petstore/objc/Build +samples/client/petstore/objc/Pods +samples/server/petstore/nodejs/node_modules target .idea .lib diff --git a/README.md b/README.md index 0687abed1ee..cb649e07da5 100644 --- a/README.md +++ b/README.md @@ -150,8 +150,11 @@ JavaClientCodegen.java JaxRSServerCodegen.java NodeJSServerCodegen.java ObjcClientCodegen.java +PerlClientCodegen.java PhpClientCodegen.java +Python3ClientCodegen.java PythonClientCodegen.java +Qt5CPPGenerator.java RubyClientCodegen.java ScalaClientCodegen.java ScalatraServerCodegen.java diff --git a/bin/jaxrs-petstore-server.sh b/bin/jaxrs-petstore-server.sh index 2dd4fc03b38..91a418d6f9a 100755 --- a/bin/jaxrs-petstore-server.sh +++ b/bin/jaxrs-petstore-server.sh @@ -26,6 +26,6 @@ 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/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l jaxrs -o samples/server/petstore/jaxrs" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l jaxrs -o samples/server/petstore/jaxrs -Dswagger.codegen.jaxrs.impl.source=src/main/java" java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/Generate.java b/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/Generate.java index 0e88a947b47..47449d84286 100644 --- a/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/Generate.java +++ b/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/Generate.java @@ -54,10 +54,16 @@ public class Generate implements Runnable { "Pass in a URL-encoded string of name:header with a comma separating multiple values") private String auth; + @Option( name= {"-D"}, title = "system properties", description = "sets specified system properties in " + + "the format of name=value,name=value") + private String systemProperties; + @Override public void run() { verbosed(verbose); + setSystemProperties(); + ClientOptInput input = new ClientOptInput(); if (isNotEmpty(auth)) { @@ -77,6 +83,17 @@ public class Generate implements Runnable { new DefaultGenerator().opts(input.opts(new ClientOpts()).swagger(swagger)).generate(); } + private void setSystemProperties() { + if( systemProperties != null && systemProperties.length() > 0 ){ + for( String property : systemProperties.split(",")) { + int ix = property.indexOf('='); + if( ix > 0 && ix < property.length()-1 ){ + System.setProperty( property.substring(0, ix), property.substring(ix+1) ); + } + } + } + } + /** * If true parameter, adds system properties which enables debug mode in generator * @param verbose - if true, enables debug mode diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index 6acdf5e29f8..2db20e67a2d 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -6,11 +6,9 @@ ../.. 4.0.0 - com.wordnik swagger-codegen jar swagger-codegen (core library) - 2.1.1-M2-SNAPSHOT src/main/java install diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java index ca73a819fb5..167610fcd70 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java @@ -56,4 +56,8 @@ public interface CodegenConfig { Map postProcessModels(Map objs); Map postProcessOperations(Map objs); Map postProcessSupportingFileData(Map objs); + + String apiFilename(String templateName, String tag); + + boolean shouldOverwrite(String filename); } diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java index 169886da22e..d1bfc90ba2a 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java @@ -11,6 +11,6 @@ public class CodegenModel { public String defaultValue; public List vars = new ArrayList(); public Set imports = new HashSet(); - public Boolean hasVars, emptyVars, hasMoreModels; + public Boolean hasVars, emptyVars, hasMoreModels, hasEnums; public ExternalDocs externalDocs; } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java index 04cecabad90..8dc9991daed 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java @@ -3,7 +3,7 @@ package com.wordnik.swagger.codegen; public class CodegenParameter { public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, isFile, notFile, hasMore, isContainer, secondaryParam; - public String baseName, paramName, dataType, collectionFormat, description, baseType; + public String baseName, paramName, dataType, collectionFormat, description, baseType, defaultValue; public String jsonSchema; /** @@ -34,7 +34,8 @@ public class CodegenParameter { output.isBodyParam = this.isBodyParam; output.required = this.required; output.jsonSchema = this.jsonSchema; + output.defaultValue = this.defaultValue; return output; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java index b00c962ba6b..921ca90f189 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java @@ -16,7 +16,10 @@ public class CodegenProperty { public String example; public String jsonSchema; - public Double minimum, maximum, exclusiveMinimum, exclusiveMaximum; + public Double minimum; + public Double maximum; + public Boolean exclusiveMinimum; + public Boolean exclusiveMaximum; public Boolean hasMore = null, required = null, secondaryParam = null; public Boolean isPrimitiveType, isContainer, isNotContainer; public boolean isEnum; diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java index 15931c9fd27..02627eec1bd 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java @@ -1,17 +1,21 @@ package com.wordnik.swagger.codegen; -import java.util.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; public class CodegenResponse { public String code, message; public Boolean hasMore; - public List> examples; + public List> examples; public final List headers = new ArrayList(); public String dataType, baseType, containerType; + public Boolean isDefault; public Boolean simpleType; public Boolean primitiveType; public Boolean isMapContainer; public Boolean isListContainer; public Object schema; public String jsonSchema; -} \ No newline at end of file + public boolean isWildcard() { return "0".equals(code) || "default".equals(code); } +} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenSecurity.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenSecurity.java index 889a9419c64..00d56ea213e 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenSecurity.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenSecurity.java @@ -1,11 +1,10 @@ package com.wordnik.swagger.codegen; public class CodegenSecurity { - String name; - String type; - Boolean hasMore, isBasic, isOAuth, isApiKey; + public String name; + public String type; + public Boolean hasMore, isBasic, isOAuth, isApiKey; // ApiKey specific - String keyParamName; - Boolean isKeyInQuery, isKeyInHeader; - + public String keyParamName; + public Boolean isKeyInQuery, isKeyInHeader; } 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 6f51374c536..a2b4258532f 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 @@ -1,26 +1,58 @@ package com.wordnik.swagger.codegen; +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.wordnik.swagger.codegen.examples.ExampleGenerator; -import com.wordnik.swagger.models.*; +import com.wordnik.swagger.models.ArrayModel; +import com.wordnik.swagger.models.Model; +import com.wordnik.swagger.models.ModelImpl; +import com.wordnik.swagger.models.Operation; +import com.wordnik.swagger.models.RefModel; +import com.wordnik.swagger.models.Response; +import com.wordnik.swagger.models.Swagger; import com.wordnik.swagger.models.auth.ApiKeyAuthDefinition; import com.wordnik.swagger.models.auth.BasicAuthDefinition; import com.wordnik.swagger.models.auth.In; import com.wordnik.swagger.models.auth.SecuritySchemeDefinition; -import com.wordnik.swagger.models.parameters.*; -import com.wordnik.swagger.models.properties.*; +import com.wordnik.swagger.models.parameters.BodyParameter; +import com.wordnik.swagger.models.parameters.CookieParameter; +import com.wordnik.swagger.models.parameters.FormParameter; +import com.wordnik.swagger.models.parameters.HeaderParameter; +import com.wordnik.swagger.models.parameters.Parameter; +import com.wordnik.swagger.models.parameters.PathParameter; +import com.wordnik.swagger.models.parameters.QueryParameter; +import com.wordnik.swagger.models.parameters.SerializableParameter; +import com.wordnik.swagger.models.properties.AbstractNumericProperty; +import com.wordnik.swagger.models.properties.ArrayProperty; +import com.wordnik.swagger.models.properties.BooleanProperty; +import com.wordnik.swagger.models.properties.DateProperty; +import com.wordnik.swagger.models.properties.DateTimeProperty; +import com.wordnik.swagger.models.properties.DecimalProperty; +import com.wordnik.swagger.models.properties.DoubleProperty; +import com.wordnik.swagger.models.properties.FloatProperty; +import com.wordnik.swagger.models.properties.IntegerProperty; +import com.wordnik.swagger.models.properties.LongProperty; +import com.wordnik.swagger.models.properties.MapProperty; +import com.wordnik.swagger.models.properties.Property; +import com.wordnik.swagger.models.properties.PropertyBuilder; +import com.wordnik.swagger.models.properties.RefProperty; +import com.wordnik.swagger.models.properties.StringProperty; import com.wordnik.swagger.util.Json; -import org.apache.commons.lang.StringUtils; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.util.*; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - public class DefaultCodegen { Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class); @@ -166,6 +198,9 @@ public class DefaultCodegen { return name; } + public String toEnumName(CodegenProperty property) { + return StringUtils.capitalize(property.name) + "Enum"; + } public String escapeReservedWord(String name) { throw new RuntimeException("reserved word " + name + " not allowed"); @@ -470,6 +505,7 @@ public class DefaultCodegen { } 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); @@ -497,6 +533,8 @@ public class DefaultCodegen { } 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) { @@ -589,7 +627,7 @@ public class DefaultCodegen { // this can cause issues for clients which don't support enums if(property.isEnum) - property.datatypeWithEnum = StringUtils.capitalize(property.name) + "Enum"; + property.datatypeWithEnum = toEnumName(property); else property.datatypeWithEnum = property.datatype; @@ -692,11 +730,11 @@ public class DefaultCodegen { for(String key: operation.getConsumes()) { Map mediaType = new HashMap(); mediaType.put("mediaType", key); + count += 1; if (count < operation.getConsumes().size()) mediaType.put("hasMore", "true"); else mediaType.put("hasMore", null); - count += 1; c.add(mediaType); } op.consumes = c; @@ -722,7 +760,6 @@ public class DefaultCodegen { if (operation.getResponses() != null && !operation.getResponses().isEmpty()) { Response methodResponse = findMethodResponse(operation.getResponses()); - CodegenResponse methodCodegenResponse = null; for (Map.Entry entry : operation.getResponses().entrySet()) { Response response = entry.getValue(); @@ -732,9 +769,7 @@ public class DefaultCodegen { !defaultIncludes.contains(r.baseType) && !languageSpecificPrimitives.contains(r.baseType)) imports.add(r.baseType); - - if (response == methodResponse) - methodCodegenResponse = r; + r.isDefault = response == methodResponse; op.responses.add(r); } op.responses.get(op.responses.size() - 1).hasMore = false; @@ -904,6 +939,15 @@ public class DefaultCodegen { p.required = param.getRequired(); p.jsonSchema = Json.pretty(param); + // move the defaultValue for headers, forms and params + if(param instanceof QueryParameter) { + p.defaultValue = ((QueryParameter)param).getDefaultValue(); + } else if(param instanceof HeaderParameter) { + p.defaultValue = ((HeaderParameter)param).getDefaultValue(); + } else if(param instanceof FormParameter) { + p.defaultValue = ((FormParameter)param).getDefaultValue(); + } + if(param instanceof SerializableParameter) { SerializableParameter qp = (SerializableParameter) param; Property property = null; @@ -918,6 +962,19 @@ public class DefaultCodegen { collectionFormat = qp.getCollectionFormat(); CodegenProperty pr = fromProperty("inner", inner); p.baseType = pr.datatype; + p.isContainer = true; + imports.add(pr.baseType); + } + else if("object".equals(qp.getType())) { + Property inner = qp.getItems(); + if(inner == null) { + LOGGER.warn("warning! No inner type supplied for map parameter \"" + qp.getName() + "\", using String"); + inner = new StringProperty().description("//TODO automatically added by swagger-codegen"); + } + property = new MapProperty(inner); + collectionFormat = qp.getCollectionFormat(); + CodegenProperty pr = fromProperty("inner", inner); + p.baseType = pr.datatype; imports.add(pr.baseType); } else @@ -926,6 +983,7 @@ public class DefaultCodegen { LOGGER.warn("warning! Property type \"" + qp.getType() + "\" not found for parameter \"" + param.getName() + "\", using String"); property = new StringProperty().description("//TODO automatically added by swagger-codegen. Type was " + qp.getType() + " but not supported"); } + property.setRequired(param.getRequired()); CodegenProperty model = fromProperty(qp.getName(), property); p.collectionFormat = collectionFormat; p.dataType = model.datatype; @@ -949,6 +1007,7 @@ public class DefaultCodegen { else { // TODO: missing format, so this will not always work Property prop = PropertyBuilder.build(impl.getType(), null, null); + prop.setRequired(bp.getRequired()); CodegenProperty cp = fromProperty("property", prop); if(cp != null) { p.dataType = cp.datatype; @@ -962,6 +1021,7 @@ public class DefaultCodegen { CodegenModel cm = fromModel(bp.getName(), impl); // get the single property ArrayProperty ap = new ArrayProperty().items(impl.getItems()); + ap.setRequired(param.getRequired()); CodegenProperty cp = fromProperty("inner", ap); if(cp.complexType != null) { imports.add(cp.complexType); @@ -996,9 +1056,9 @@ public class DefaultCodegen { if(schemes == null) return null; - List secs = new ArrayList(); - for(Iterator entries = schemes.entrySet().iterator(); entries.hasNext(); ) { - Map.Entry entry = (Map.Entry) entries.next(); + List secs = new ArrayList(schemes.size()); + for (Iterator> it = schemes.entrySet().iterator(); it.hasNext();) { + final Map.Entry entry = it.next(); final SecuritySchemeDefinition schemeDefinition = entry.getValue(); CodegenSecurity sec = CodegenModelFactory.newInstance(CodegenModelType.SECURITY); @@ -1018,23 +1078,21 @@ public class DefaultCodegen { sec.isOAuth = !sec.isBasic; } - sec.hasMore = entries.hasNext(); + sec.hasMore = it.hasNext(); secs.add(sec); } return secs; } - protected List> toExamples(Map examples) { + protected List> toExamples(Map examples) { if(examples == null) return null; - List> output = new ArrayList>(); - for(String key: examples.keySet()) { - String value = examples.get(key); - - Map kv = new HashMap(); - kv.put("contentType", key); - kv.put("example", value); + final List> output = new ArrayList>(examples.size()); + for(Map.Entry entry : examples.entrySet()) { + final Map kv = new HashMap(); + kv.put("contentType", entry.getKey()); + kv.put("example", entry.getValue()); output.add(kv); } return output; @@ -1169,4 +1227,13 @@ public class DefaultCodegen { } + public String apiFilename(String templateName, String tag) + { + String suffix = apiTemplateFiles().get(templateName); + return apiFileFolder() + File.separator + toApiFilename(tag) + suffix; + } + + public boolean shouldOverwrite( String filename ){ + return true; + } } diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index 17509973215..d57926b7e3c 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -165,6 +165,10 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { operation.putAll(config.additionalProperties()); operation.put("classname", config.toApiName(tag)); operation.put("classVarName", config.toApiVarName(tag)); + operation.put("importPath", config.toApiImport(tag)); + + processMimeTypes(swagger.getConsumes(), operation, "consumes"); + processMimeTypes(swagger.getProduces(), operation, "produces"); allOperations.add(new HashMap(operation)); for (int i = 0; i < allOperations.size(); i++) { @@ -175,11 +179,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } for (String templateName : config.apiTemplateFiles().keySet()) { - String suffix = config.apiTemplateFiles().get(templateName); - String filename = config.apiFileFolder() + - File.separator + - config.toApiFilename(tag) + - suffix; + + String filename = config.apiFilename( templateName, tag ); + if( new File( filename ).exists() && !config.shouldOverwrite( filename )){ + continue; + } String template = readTemplate(config.templateDir() + File.separator + templateName); Template tmpl = Mustache.compiler() @@ -217,6 +221,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { bundle.put("models", allModels); bundle.put("apiFolder", config.apiPackage().replace('.', File.separatorChar)); bundle.put("modelPackage", config.modelPackage()); + bundle.put("authMethods", config.fromSecurity(swagger.getSecurityDefinitions())); if (swagger.getExternalDocs() != null) { bundle.put("externalDocs", swagger.getExternalDocs()); } @@ -291,6 +296,28 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { return files; } + private void processMimeTypes(List mimeTypeList, Map operation, String source) { + if(mimeTypeList != null && mimeTypeList.size() > 0) { + List> c = new ArrayList>(); + int count = 0; + for(String key: mimeTypeList) { + Map mediaType = new HashMap(); + mediaType.put("mediaType", key); + count += 1; + if (count < mimeTypeList.size()) { + mediaType.put("hasMore", "true"); + } + else { + mediaType.put("hasMore", null); + } + c.add(mediaType); + } + operation.put(source, c); + String flagFieldName = "has" + source.substring(0, 1).toUpperCase() + source.substring(1); + operation.put(flagFieldName, true); + } + } + public Map> processPaths(Map paths) { Map> ops = new HashMap>(); @@ -427,6 +454,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { CodegenModel cm = config.fromModel(key, mm); Map mo = new HashMap(); mo.put("model", cm); + mo.put("importPath", config.toModelImport(key)); models.add(mo); allImports.addAll(cm.imports); } diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/ExampleGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/ExampleGenerator.java index 80063625440..51d10f7e8a6 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/ExampleGenerator.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/ExampleGenerator.java @@ -1,19 +1,33 @@ package com.wordnik.swagger.codegen.examples; -import com.wordnik.swagger.models.*; -import com.wordnik.swagger.models.properties.*; -import com.wordnik.swagger.util.Json; - -import java.text.SimpleDateFormat; - - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; - - import java.math.BigDecimal; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.wordnik.swagger.models.Model; +import com.wordnik.swagger.models.ModelImpl; +import com.wordnik.swagger.models.properties.ArrayProperty; +import com.wordnik.swagger.models.properties.BooleanProperty; +import com.wordnik.swagger.models.properties.DateProperty; +import com.wordnik.swagger.models.properties.DateTimeProperty; +import com.wordnik.swagger.models.properties.DecimalProperty; +import com.wordnik.swagger.models.properties.DoubleProperty; +import com.wordnik.swagger.models.properties.FileProperty; +import com.wordnik.swagger.models.properties.FloatProperty; +import com.wordnik.swagger.models.properties.IntegerProperty; +import com.wordnik.swagger.models.properties.LongProperty; +import com.wordnik.swagger.models.properties.MapProperty; +import com.wordnik.swagger.models.properties.ObjectProperty; +import com.wordnik.swagger.models.properties.Property; +import com.wordnik.swagger.models.properties.RefProperty; +import com.wordnik.swagger.models.properties.StringProperty; +import com.wordnik.swagger.models.properties.UUIDProperty; +import com.wordnik.swagger.util.Json; public class ExampleGenerator { protected Map examples; @@ -22,7 +36,7 @@ public class ExampleGenerator { this.examples = examples; } - public List> generate(Map examples, List mediaTypes, Property property) { + public List> generate(Map examples, List mediaTypes, Property property) { List> output = new ArrayList>(); Set processedModels = new HashSet(); if(examples == null ) { @@ -37,7 +51,6 @@ public class ExampleGenerator { String example = Json.pretty(resolvePropertyToExample(mediaType, property, processedModels)); if(example != null) { - example = example.replaceAll("\n", "\\\\n"); kv.put("example", example); output.add(kv); } @@ -45,7 +58,6 @@ public class ExampleGenerator { else if(property != null && mediaType.startsWith("application/xml")) { String example = new XmlExampleGenerator(this.examples).toXml(property); if(example != null) { - example = example.replaceAll("\n", "\\\\n"); kv.put("example", example); output.add(kv); } @@ -53,12 +65,10 @@ public class ExampleGenerator { } } else { - for(String key: examples.keySet()) { - String value = examples.get(key); - - Map kv = new HashMap(); - kv.put("contentType", key); - kv.put("example", value); + for(Map.Entry entry: examples.entrySet()) { + final Map kv = new HashMap(); + kv.put("contentType", entry.getKey()); + kv.put("example", Json.pretty(entry.getValue())); output.add(kv); } } diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/XmlExampleGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/XmlExampleGenerator.java index 40df89507e3..b1896605cdf 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/XmlExampleGenerator.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/XmlExampleGenerator.java @@ -8,6 +8,8 @@ import com.wordnik.swagger.models.properties.*; import java.text.SimpleDateFormat; import java.util.*; +import org.codehaus.plexus.util.StringUtils; + public class XmlExampleGenerator { public static String NEWLINE = "\n"; public static String TAG_START = "<"; @@ -16,6 +18,7 @@ public class XmlExampleGenerator { protected Map examples; protected SimpleDateFormat dtFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); protected SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + private static String EMPTY = ""; public XmlExampleGenerator(Map examples) { this.examples = examples; @@ -24,29 +27,36 @@ public class XmlExampleGenerator { } public String toXml(Property property) { - return toXml(null, property, 0); + return toXml(null, property, 0, Collections.emptySet()); } - protected String toXml(Model model, int indent) { + protected String toXml(Model model, int indent, Collection path) { if(model instanceof RefModel) { RefModel ref = (RefModel) model; Model actualModel = examples.get(ref.getSimpleRef()); if(actualModel instanceof ModelImpl) - return modelImplToXml((ModelImpl)actualModel, indent); + return modelImplToXml((ModelImpl) actualModel, indent, path); } else if(model instanceof ModelImpl) { - return modelImplToXml((ModelImpl)model, indent); + return modelImplToXml((ModelImpl) model, indent, path); } return null; } - protected String modelImplToXml(ModelImpl model, int indent) { + protected String modelImplToXml(ModelImpl model, int indent, Collection path) { + final String modelName = model.getName(); + if (path.contains(modelName)) { + return EMPTY; + } + final Set selfPath = new HashSet(path); + selfPath.add(modelName); + StringBuilder sb = new StringBuilder(); // attributes Map attributes = new LinkedHashMap(); Map elements = new LinkedHashMap(); - String name = model.getName(); + String name = modelName; String namespace; String prefix; Boolean wrapped; @@ -67,13 +77,17 @@ public class XmlExampleGenerator { sb.append(name); for(String pName : attributes.keySet()) { Property p = attributes.get(pName); - sb.append(" ").append(pName).append("=").append(quote(toXml(null, p, 0))); + sb.append(" ").append(pName).append("=").append(quote(toXml(null, p, 0, selfPath))); } sb.append(CLOSE_TAG); sb.append(NEWLINE); for(String pName : elements.keySet()) { Property p = elements.get(pName); - sb.append(toXml(pName, p, indent + 1)); + final String asXml = toXml(pName, p, indent + 1, selfPath); + if (StringUtils.isEmpty(asXml)) { + continue; + } + sb.append(asXml); sb.append(NEWLINE); } sb.append(indent(indent)).append(TAG_END).append(name).append(CLOSE_TAG); @@ -85,7 +99,7 @@ public class XmlExampleGenerator { return "\"" + string + "\""; } - protected String toXml(String name, Property property, int indent) { + protected String toXml(String name, Property property, int indent, Collection path) { if(property == null) { return ""; } @@ -98,12 +112,16 @@ public class XmlExampleGenerator { if(property.getXml() != null && property.getXml().getWrapped()) wrapped = true; if(wrapped) { + String prefix = EMPTY; if(name != null) { sb.append(indent(indent)); sb.append(openTag(name)); - sb.append(NEWLINE); + prefix = NEWLINE; + } + final String asXml = toXml(name, inner, indent + 1, path); + if (StringUtils.isNotEmpty(asXml)) { + sb.append(prefix).append(asXml); } - sb.append(toXml(name, inner, indent + 1)); if(name != null) { sb.append(NEWLINE); sb.append(indent(indent)); @@ -111,12 +129,12 @@ public class XmlExampleGenerator { } } else - sb.append(toXml(name, inner, indent)); + sb.append(toXml(name, inner, indent, path)); } else if(property instanceof RefProperty) { RefProperty ref = (RefProperty) property; Model actualModel = examples.get(ref.getSimpleRef()); - sb.append(toXml(actualModel, indent)); + sb.append(toXml(actualModel, indent, path)); } else { if(name != null) { diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AkkaScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AkkaScalaClientCodegen.java new file mode 100644 index 00000000000..fff8deb99f4 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AkkaScalaClientCodegen.java @@ -0,0 +1,365 @@ +package com.wordnik.swagger.codegen.languages; + +import com.google.common.base.CaseFormat; +import com.samskivert.mustache.Mustache; +import com.samskivert.mustache.Template; +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.models.auth.SecuritySchemeDefinition; +import com.wordnik.swagger.models.properties.*; +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.util.*; + +public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenConfig { + Logger LOGGER = LoggerFactory.getLogger(AkkaScalaClientCodegen.class); + + protected String mainPackage = "io.swagger.client"; + + protected String invokerPackage = mainPackage + ".core"; + protected String groupId = "com.wordnik"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/scala"; + protected String resourcesFolder = "src/main/resources"; + protected String configKey = "apiRequest"; + protected int defaultTimeoutInMs = 5000; + protected String configKeyPath = mainPackage; + + protected boolean registerNonStandardStatusCodes = true; + protected boolean renderJavadoc = true; + protected boolean removeOAuthSecurities = true; + /** + * If set to true, only the default response (the one with le lowest 2XX code) will be considered as a success, and all + * others as ApiErrors. + * If set to false, all responses defined in the model will be considered as a success upon reception. Only http errors, + * unmarshalling problems and any other RuntimeException will be considered as ApiErrors. + */ + protected boolean onlyOneSuccess = true; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "akka-scala"; + } + + public String getHelp() { + return "Generates a Scala client library base on Akka/Spray."; + } + + public AkkaScalaClientCodegen() { + super(); + outputFolder = "generated-code/scala"; + modelTemplateFiles.put("model.mustache", ".scala"); + apiTemplateFiles.put("api.mustache", ".scala"); + templateDir = "akka-scala"; + apiPackage = mainPackage + ".api"; + modelPackage = mainPackage + ".model"; + + reservedWords = new HashSet( + Arrays.asList( + "abstract", "case", "catch", "class", "def", "do", "else", "extends", + "false", "final", "finally", "for", "forSome", "if", "implicit", + "import", "lazy", "match", "new", "null", "object", "override", "package", + "private", "protected", "return", "sealed", "super", "this", "throw", + "trait", "try", "true", "type", "val", "var", "while", "with", "yield") + ); + + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put("configKey", configKey); + additionalProperties.put("configKeyPath", configKeyPath); + additionalProperties.put("defaultTimeout", defaultTimeoutInMs); + if (renderJavadoc) + additionalProperties.put("javadocRenderer", new JavadocLambda()); + additionalProperties.put("fnCapitalize", new CapitalizeLambda()); + additionalProperties.put("fnCamelize", new CamelizeLambda(false)); + additionalProperties.put("fnEnumEntry", new EnumEntryLambda()); + additionalProperties.put("onlyOneSuccess", onlyOneSuccess); + + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("reference.mustache", resourcesFolder, "reference.conf")); + final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator); + supportingFiles.add(new SupportingFile("apiRequest.mustache", invokerFolder, "ApiRequest.scala")); + supportingFiles.add(new SupportingFile("apiInvoker.mustache", invokerFolder, "ApiInvoker.scala")); + supportingFiles.add(new SupportingFile("requests.mustache", invokerFolder, "requests.scala")); + supportingFiles.add(new SupportingFile("apiSettings.mustache", invokerFolder, "ApiSettings.scala")); + final String apiFolder = (sourceFolder + File.separator + apiPackage).replace(".", File.separator); + supportingFiles.add(new SupportingFile("enumsSerializers.mustache", apiFolder, "EnumsSerializers.scala")); + + importMapping.remove("Seq"); + importMapping.remove("List"); + importMapping.remove("Set"); + importMapping.remove("Map"); + + importMapping.put("DateTime", "org.joda.time.DateTime"); + + typeMapping = new HashMap(); + typeMapping.put("array", "Seq"); + typeMapping.put("set", "Set"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("string", "String"); + typeMapping.put("int", "Int"); + typeMapping.put("integer", "Int"); + typeMapping.put("long", "Long"); + typeMapping.put("float", "Float"); + typeMapping.put("byte", "Byte"); + typeMapping.put("short", "Short"); + typeMapping.put("char", "Char"); + typeMapping.put("long", "Long"); + typeMapping.put("double", "Double"); + typeMapping.put("object", "Any"); + typeMapping.put("file", "File"); + typeMapping.put("number", "Double"); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Int", + "Long", + "Float", + "Object", + "List", + "Seq", + "Map") + ); + instantiationTypes.put("array", "ListBuffer"); + instantiationTypes.put("map", "Map"); + } + + @Override + public String escapeReservedWord(String name) { + return "`" + name + "`"; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public Map postProcessOperations(Map objs) { + if (registerNonStandardStatusCodes) { + try { + @SuppressWarnings("unchecked") + Map> opsMap = (Map>) objs.get("operations"); + HashSet unknownCodes = new HashSet(); + for (CodegenOperation operation : opsMap.get("operation")) { + for (CodegenResponse response : operation.responses) { + if ("default".equals(response.code)) + continue; + try { + int code = Integer.parseInt(response.code); + if (code >= 600) { + unknownCodes.add(code); + } + } catch (NumberFormatException e) { + LOGGER.error("Status code is not an integer : response.code", e); + } + } + } + if (!unknownCodes.isEmpty()) { + additionalProperties.put("unknownStatusCodes", unknownCodes); + } + } catch (Exception e) { + LOGGER.error("Unable to find operations List", e); + } + } + return super.postProcessOperations(objs); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public List fromSecurity(Map schemes) { + final List codegenSecurities = super.fromSecurity(schemes); + if (!removeOAuthSecurities) + return codegenSecurities; + + // Remove OAuth securities + Iterator it = codegenSecurities.iterator(); + while (it.hasNext()) { + final CodegenSecurity security = it.next(); + if (security.isOAuth) + it.remove(); + } + // Adapt 'hasMore' + it = codegenSecurities.iterator(); + while (it.hasNext()) { + final CodegenSecurity security = it.next(); + security.hasMore = it.hasNext(); + } + + if (codegenSecurities.isEmpty()) + return null; + return codegenSecurities; + } + + @Override + public String toOperationId(String operationId) { + return super.toOperationId(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, operationId)); + } + + private String formatIdentifier(String name, boolean capitalized) { + String identifier = camelize(name, true); + if (capitalized) + identifier = StringUtils.capitalize(identifier); + if (identifier.matches("[a-zA-Z_$][\\w_$]+") && !reservedWords.contains(identifier)) + return identifier; + return escapeReservedWord(identifier); + } + + @Override + public String toParamName(String name) { return formatIdentifier(name, false); } + + @Override + public String toVarName(String name) { + return formatIdentifier(name, false); + } + + @Override + public String toEnumName(CodegenProperty property) + { + return formatIdentifier(property.baseName, true); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) + return toModelName(type); + } else + type = swaggerType; + return toModelName(type); + } + + @Override + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return instantiationTypes.get("map") + "[String, " + inner + "]"; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return instantiationTypes.get("array") + "[" + inner + "]"; + } else + return null; + } + + public String toDefaultValue(Property p) { + if (!p.getRequired()) + return "None"; + if (p instanceof StringProperty) + return "null"; + else if (p instanceof BooleanProperty) + return "null"; + else if (p instanceof DateProperty) + return "null"; + else if (p instanceof DateTimeProperty) + return "null"; + else if (p instanceof DoubleProperty) + return "null"; + else if (p instanceof FloatProperty) + return "null"; + else if (p instanceof IntegerProperty) + return "null"; + else if (p instanceof LongProperty) + return "null"; + else if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "Map[String, " + inner + "].empty "; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "Seq[" + inner + "].empty "; + } else + return "null"; + } + + private static abstract class CustomLambda implements Mustache.Lambda { + @Override + public void execute(Template.Fragment frag, Writer out) throws IOException { + final StringWriter tempWriter = new StringWriter(); + frag.execute(tempWriter); + out.write(formatFragment(tempWriter.toString())); + } + public abstract String formatFragment(String fragment); + } + + + private static class JavadocLambda extends CustomLambda { + @Override + public String formatFragment(String fragment) { + final String[] lines = fragment.split("\\r?\\n"); + final StringBuilder sb = new StringBuilder(); + sb.append(" /**\n"); + for (String line : lines) { + sb.append(" * ").append(line).append("\n"); + } + sb.append(" */\n"); + return sb.toString(); + } + } + + private static class CapitalizeLambda extends CustomLambda { + @Override + public String formatFragment(String fragment) { + return StringUtils.capitalize(fragment); + } + } + + private static class CamelizeLambda extends CustomLambda { + private final boolean capitalizeFirst; + + public CamelizeLambda(boolean capitalizeFirst) { + this.capitalizeFirst = capitalizeFirst; + } + + @Override + public String formatFragment(String fragment) { + return camelize(fragment, !capitalizeFirst); + } + } + + private class EnumEntryLambda extends CustomLambda { + @Override + public String formatFragment(String fragment) { + return formatIdentifier(fragment, true); + } + } + +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java index 3da9c6344a4..62fc70efdea 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java @@ -13,6 +13,7 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi protected String artifactVersion = "1.0.0"; protected String projectFolder = "src/main"; protected String sourceFolder = projectFolder + "/java"; + protected Boolean useAndroidMavenGradlePlugin = true; public CodegenType getTag() { return CodegenType.CLIENT; @@ -52,6 +53,9 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi additionalProperties.put("artifactVersion", artifactVersion); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + additionalProperties.put("useAndroidMavenGradlePlugin", useAndroidMavenGradlePlugin); + + supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); supportingFiles.add(new SupportingFile("apiInvoker.mustache", 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 969b143c5a0..5060899d498 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 @@ -7,7 +7,7 @@ import java.util.*; import java.io.File; public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "io.swagger.client"; + protected String invokerPackage = "IO.Swagger.Client"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-csharp-client"; protected String artifactVersion = "1.0.0"; @@ -31,8 +31,8 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig modelTemplateFiles.put("model.mustache", ".cs"); apiTemplateFiles.put("api.mustache", ".cs"); templateDir = "csharp"; - apiPackage = "io.swagger.Api"; - modelPackage = "io.swagger.Model"; + apiPackage = "IO.Swagger.Api"; + modelPackage = "IO.Swagger.Model"; reservedWords = new HashSet ( Arrays.asList( @@ -80,7 +80,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig typeMapping.put("double", "double?"); typeMapping.put("number", "double?"); typeMapping.put("Date", "DateTime"); - typeMapping.put("file", "byte[]"); + typeMapping.put("file", "string"); // path to file typeMapping.put("array", "List"); typeMapping.put("map", "Dictionary"); diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java index 39ed9dfe540..7c0ac7422ff 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java @@ -130,7 +130,6 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { return toModelName(name); } - @Override public String getTypeDeclaration(Property p) { if(p instanceof ArrayProperty) { diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java index e6447b9484b..0bc8097d671 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java @@ -1,8 +1,6 @@ package com.wordnik.swagger.codegen.languages; import com.wordnik.swagger.models.Operation; -import com.wordnik.swagger.models.Path; -import com.wordnik.swagger.util.Json; import com.wordnik.swagger.codegen.*; import com.wordnik.swagger.models.properties.*; @@ -14,7 +12,6 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf protected String groupId = "io.swagger"; protected String artifactId = "swagger-jaxrs-server"; protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/java"; protected String title = "Swagger Server"; public CodegenType getTag() { @@ -31,12 +28,19 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf public JaxRSServerCodegen() { super(); - outputFolder = "generated-code/javaJaxRS"; + + sourceFolder = "src/gen/java"; + + outputFolder = System.getProperty( "swagger.codegen.jaxrs.genfolder", "generated-code/javaJaxRS" ); modelTemplateFiles.put("model.mustache", ".java"); apiTemplateFiles.put("api.mustache", ".java"); + apiTemplateFiles.put("apiService.mustache", ".java"); + apiTemplateFiles.put("apiServiceImpl.mustache", ".java"); + apiTemplateFiles.put("apiServiceFactory.mustache", ".java"); + templateDir = "JavaJaxRS"; - apiPackage = "io.swagger.api"; - modelPackage = "io.swagger.model"; + apiPackage = System.getProperty( "swagger.codegen.jaxrs.apipackage", "io.swagger.api") ; + modelPackage = System.getProperty( "swagger.codegen.jaxrs.modelpackage", "io.swagger.model" ); additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put("groupId", groupId); @@ -146,4 +150,44 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf } return objs; } + + @Override + public String apiFilename(String templateName, String tag) { + + String result = super.apiFilename(templateName, tag); + + if( templateName.endsWith( "Impl.mustache")){ + int ix = result.lastIndexOf( '/' ); + result = result.substring( 0, ix ) + "/impl" + result.substring( ix, result.length()-5 ) + "ServiceImpl.java"; + + String output = System.getProperty( "swagger.codegen.jaxrs.impl.source" ); + if( output != null ){ + result = result.replace( apiFileFolder(), implFileFolder(output)); + } + } + else if( templateName.endsWith( "Factory.mustache")){ + int ix = result.lastIndexOf( '/' ); + result = result.substring( 0, ix ) + "/factories" + result.substring( ix, result.length()-5 ) + "ServiceFactory.java"; + + String output = System.getProperty( "swagger.codegen.jaxrs.impl.source" ); + if( output != null ){ + result = result.replace( apiFileFolder(), implFileFolder(output)); + } + } + else if( templateName.endsWith( "Service.mustache")) { + int ix = result.lastIndexOf('.'); + result = result.substring(0, ix) + "Service.java"; + } + + return result; + } + + private String implFileFolder(String output) { + return outputFolder + "/" + output + "/" + apiPackage().replace('.', File.separatorChar); + } + + public boolean shouldOverwrite( String filename ){ + + return !filename.endsWith( "ServiceImpl.java") && !filename.endsWith( "ServiceFactory.java"); + } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/NodeJSServerCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/NodeJSServerCodegen.java index 0c6e6067607..9d516c398f6 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/NodeJSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/NodeJSServerCodegen.java @@ -1,11 +1,19 @@ package com.wordnik.swagger.codegen.languages; -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.util.Json; -import com.wordnik.swagger.models.properties.*; - -import java.util.*; import java.io.File; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import com.wordnik.swagger.codegen.CodegenConfig; +import com.wordnik.swagger.codegen.CodegenOperation; +import com.wordnik.swagger.codegen.CodegenParameter; +import com.wordnik.swagger.codegen.CodegenResponse; +import com.wordnik.swagger.codegen.CodegenType; +import com.wordnik.swagger.codegen.DefaultCodegen; +import com.wordnik.swagger.codegen.SupportingFile; public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig { protected String apiVersion = "1.0.0"; @@ -156,8 +164,10 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig @Override public Map postProcessOperations(Map objs) { - Map objectMap = (Map)objs.get("operations"); - List operations = (List)objectMap.get("operation"); + @SuppressWarnings("unchecked") + Map objectMap = (Map) objs.get("operations"); + @SuppressWarnings("unchecked") + List operations = (List) objectMap.get("operation"); for(CodegenOperation operation : operations) { operation.httpMethod = operation.httpMethod.toLowerCase(); List params = operation.allParams; @@ -170,20 +180,14 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig resp.code = "default"; } } - if(operation.examples != null && operation.examples.size() > 0) { - List> examples = operation.examples; - for(int i = examples.size() - 1; i >= 0; i--) { - Map example = examples.get(i); - String contentType = example.get("contentType"); - if(contentType != null && contentType.indexOf("application/json") == 0) { - String jsonExample = example.get("example"); - if(jsonExample != null) { - jsonExample = jsonExample.replaceAll("\\\\n", "\n"); - example.put("example", jsonExample); - } + if(operation.examples != null && !operation.examples.isEmpty()) { + // Leave application/json* items only + for (Iterator> it = operation.examples.iterator(); it.hasNext();) { + final Map example = it.next(); + final String contentType = example.get("contentType"); + if (contentType == null || !contentType.startsWith("application/json")) { + it.remove(); } - else - examples.remove(i); } } } diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java index b7c38c703ca..d1e227ce744 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java @@ -120,8 +120,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("SWGApiClient.m", sourceFolder, "SWGApiClient.m")); supportingFiles.add(new SupportingFile("SWGFile.h", sourceFolder, "SWGFile.h")); supportingFiles.add(new SupportingFile("SWGFile.m", sourceFolder, "SWGFile.m")); - supportingFiles.add(new SupportingFile("SWGDate.h", sourceFolder, "SWGDate.h")); - supportingFiles.add(new SupportingFile("SWGDate.m", sourceFolder, "SWGDate.m")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", sourceFolder, "JSONValueTransformer+ISO8601.m")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", sourceFolder, "JSONValueTransformer+ISO8601.h")); supportingFiles.add(new SupportingFile("Podfile.mustache", "", "Podfile")); } diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java index 48d4a86b09d..55d358154f8 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java @@ -84,6 +84,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("list", "array"); supportingFiles.add(new SupportingFile("composer.mustache", packagePath, "composer.json")); + supportingFiles.add(new SupportingFile("configuration.mustache", packagePath + "/lib", "Configuration.php")); supportingFiles.add(new SupportingFile("APIClient.mustache", packagePath + "/lib", "APIClient.php")); supportingFiles.add(new SupportingFile("APIClientException.mustache", packagePath + "/lib", "APIClientException.php")); supportingFiles.add(new SupportingFile("require.mustache", packagePath, invokerPackage + ".php")); diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java index bbb07b1592a..7896bf66878 100755 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java @@ -34,13 +34,12 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig apiTemplateFiles.put("api.mustache", ".py"); templateDir = "python"; - apiPackage = invokerPackage; + apiPackage = invokerPackage + ".apis"; modelPackage = invokerPackage + ".models"; languageSpecificPrimitives.clear(); languageSpecificPrimitives.add("int"); languageSpecificPrimitives.add("float"); - languageSpecificPrimitives.add("long"); languageSpecificPrimitives.add("list"); languageSpecificPrimitives.add("bool"); languageSpecificPrimitives.add("str"); @@ -49,7 +48,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig typeMapping.clear(); typeMapping.put("integer", "int"); typeMapping.put("float", "float"); - typeMapping.put("long", "long"); + typeMapping.put("long", "int"); typeMapping.put("double", "float"); typeMapping.put("array", "list"); typeMapping.put("map", "map"); @@ -70,8 +69,11 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig supportingFiles.add(new SupportingFile("README.mustache", eggPackage, "README.md")); supportingFiles.add(new SupportingFile("setup.mustache", eggPackage, "setup.py")); supportingFiles.add(new SupportingFile("swagger.mustache", invokerPackage, "swagger.py")); + supportingFiles.add(new SupportingFile("rest.mustache", invokerPackage, "rest.py")); + supportingFiles.add(new SupportingFile("util.mustache", invokerPackage, "util.py")); supportingFiles.add(new SupportingFile("__init__package.mustache", invokerPackage, "__init__.py")); supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage.replace('.', File.separatorChar), "__init__.py")); + supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage.replace('.', File.separatorChar), "__init__.py")); } @Override @@ -113,9 +115,9 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig if(languageSpecificPrimitives.contains(type)) { return type; } + } else { + type = toModelName(swaggerType); } - else - type = swaggerType; return type; } @@ -133,9 +135,9 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig if (name.matches("^[A-Z_]*$")) name = name.toLowerCase(); - // camelize (lower first character) the variable name + // underscore the variable name // petId => pet_id - name = underscore(name); + name = underscore(dropDots(name)); // for reserved word or word starting with number, append _ if(reservedWords.contains(name) || name.matches("^\\d.*")) @@ -144,6 +146,10 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig return name; } + private static String dropDots(String str) { + return str.replaceAll("\\.", "_"); + } + @Override public String toParamName(String name) { // should be the same as variable name @@ -168,8 +174,8 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); // underscore the model file name - // PhoneNumber.rb => phone_number.rb - return underscore(name); + // PhoneNumber => phone_number + return underscore(dropDots(name)); } @Override diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java index 99f56bf5d41..939c0eb0e0a 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java @@ -8,10 +8,9 @@ import java.util.*; import java.io.File; public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "com.wordnik.client"; - protected String groupId = "com.wordnik"; - protected String artifactId = "swagger-client"; - protected String artifactVersion = "1.0.0"; + protected String gemName = "swagger_client"; + protected String moduleName = null; + protected String libFolder = "lib"; public CodegenType getTag() { return CodegenType.CLIENT; @@ -25,10 +24,18 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { return "Generates a Ruby client library."; } + /** + * Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger_client". + */ + public String generateModuleName() { + return camelize(gemName.replaceAll("[^\\w]+", "_")); + } + public RubyClientCodegen() { super(); - modelPackage = "models"; - apiPackage = "lib"; + moduleName = generateModuleName(); + modelPackage = gemName + "/models"; + apiPackage = gemName + "/api"; outputFolder = "generated-code/ruby"; modelTemplateFiles.put("model.mustache", ".rb"); apiTemplateFiles.put("api.mustache", ".rb"); @@ -39,17 +46,15 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { reservedWords = new HashSet ( Arrays.asList( - "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", + "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", "begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN", - "break", "do", "false", "next", "rescue", "then", "when", "END", "case", + "break", "do", "false", "next", "rescue", "then", "when", "END", "case", "else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif", "if", "not", "return", "undef", "yield") ); - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put("gemName", gemName); + additionalProperties.put("moduleName", moduleName); languageSpecificPrimitives.add("int"); languageSpecificPrimitives.add("array"); @@ -64,15 +69,18 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("List", "array"); typeMapping.put("map", "map"); - supportingFiles.add(new SupportingFile("swagger-client.gemspec.mustache", "", "swagger-client.gemspec")); - supportingFiles.add(new SupportingFile("swagger-client.mustache", "", "lib/swagger-client.rb")); - supportingFiles.add(new SupportingFile("swagger.mustache", "", "lib/swagger.rb")); - supportingFiles.add(new SupportingFile("monkey.mustache", "", "lib/monkey.rb")); - supportingFiles.add(new SupportingFile("swagger/request.mustache", "", "lib/swagger/request.rb")); - supportingFiles.add(new SupportingFile("swagger/response.mustache", "", "lib/swagger/response.rb")); - supportingFiles.add(new SupportingFile("swagger/version.mustache", "", "lib/swagger/version.rb")); - supportingFiles.add(new SupportingFile("swagger/configuration.mustache", "", "lib/swagger/configuration.rb")); - supportingFiles.add(new SupportingFile("base_object.mustache", "", "models/base_object.rb")); + String baseFolder = "lib/" + gemName; + String swaggerFolder = baseFolder + "/swagger"; + String modelFolder = baseFolder + "/models"; + supportingFiles.add(new SupportingFile("swagger_client.gemspec.mustache", "", gemName + ".gemspec")); + supportingFiles.add(new SupportingFile("swagger_client.mustache", "lib", gemName + ".rb")); + supportingFiles.add(new SupportingFile("monkey.mustache", baseFolder, "monkey.rb")); + supportingFiles.add(new SupportingFile("swagger.mustache", baseFolder, "swagger.rb")); + supportingFiles.add(new SupportingFile("swagger/request.mustache", swaggerFolder, "request.rb")); + supportingFiles.add(new SupportingFile("swagger/response.mustache", swaggerFolder, "response.rb")); + supportingFiles.add(new SupportingFile("swagger/version.mustache", swaggerFolder, "version.rb")); + supportingFiles.add(new SupportingFile("swagger/configuration.mustache", swaggerFolder, "configuration.rb")); + supportingFiles.add(new SupportingFile("base_object.mustache", modelFolder, "base_object.rb")); } @Override @@ -82,11 +90,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String apiFileFolder() { - return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); + return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "api"; } public String modelFileFolder() { - return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); + return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "models"; } @Override @@ -150,13 +158,13 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { // should be the same as variable name return toVarName(name); } - + @Override public String toModelName(String name) { // model name cannot use reserved keyword, e.g. return if(reservedWords.contains(name)) throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); - + // camelize the model name // phone_number => PhoneNumber return camelize(name); @@ -167,11 +175,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { // model name cannot use reserved keyword, e.g. return if(reservedWords.contains(name)) throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); - + // underscore the model file name // PhoneNumber.rb => phone_number.rb return underscore(name); - } + } @Override public String toApiFilename(String name) { @@ -186,7 +194,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { public String toApiName(String name) { if(name.length() == 0) return "DefaultApi"; - // e.g. phone_number_api => PhoneNumberApi + // e.g. phone_number_api => PhoneNumberApi return camelize(name) + "Api"; } @@ -196,8 +204,17 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { if(reservedWords.contains(operationId)) throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); - return underscore(operationId); + return underscore(operationId); } + @Override + public String toModelImport(String name) { + return modelPackage() + "/" + toModelFilename(name); + } + + @Override + public String toApiImport(String name) { + return apiPackage() + "/" + toApiFilename(name); + } } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache index b5ebb30f193..a883850de19 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache @@ -1,6 +1,8 @@ package {{package}}; import {{modelPackage}}.*; +import {{package}}.{{classname}}Service; +import {{package}}.factories.{{classname}}ServiceFactory; import com.wordnik.swagger.annotations.ApiParam; @@ -21,26 +23,31 @@ import javax.ws.rs.core.Response; import javax.ws.rs.*; @Path("/{{baseName}}") +{{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} +{{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} @com.wordnik.swagger.annotations.Api(value = "/{{baseName}}", description = "the {{baseName}} API") {{#operations}} -public class {{classname}} { - {{#operation}} - @{{httpMethod}} - {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} - {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} - {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} - @com.wordnik.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}) - @com.wordnik.swagger.annotations.ApiResponses(value = { {{#responses}} - @com.wordnik.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}}, - {{/hasMore}}{{/responses}} }) +public class {{classname}} { - public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, + private final {{classname}}Service delegate = {{classname}}ServiceFactory.get{{classname}}(); + +{{#operation}} + @{{httpMethod}} + {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} + {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} + {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} + @com.wordnik.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}) + @com.wordnik.swagger.annotations.ApiResponses(value = { {{#responses}} + @com.wordnik.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}}, + {{/hasMore}}{{/responses}} }) + + public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - {{/operation}} + throws NotFoundException { + // do some magic! + return delegate.{{nickname}}({{#allParams}}{{#isFile}}fileDetail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}}{{#hasMore}},{{/hasMore}}{{/allParams}}); + } +{{/operation}} } {{/operations}} + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache new file mode 100644 index 00000000000..43e7cd8685c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache @@ -0,0 +1,28 @@ +package {{package}}; + +import {{package}}.*; +import {{modelPackage}}.*; + +import com.sun.jersey.multipart.FormDataParam; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; +import {{package}}.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; + +{{#operations}} +public abstract class {{classname}}Service { + {{#operation}} + public abstract Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) + throws NotFoundException; + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceFactory.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceFactory.mustache new file mode 100644 index 00000000000..a434311d285 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceFactory.mustache @@ -0,0 +1,14 @@ +package {{package}}.factories; + +import {{package}}.{{classname}}Service; +import {{package}}.impl.{{classname}}ServiceImpl; + +public class {{classname}}ServiceFactory { + + private final static {{classname}}Service service = new {{classname}}ServiceImpl(); + + public static {{classname}}Service get{{classname}}() + { + return service; + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache new file mode 100644 index 00000000000..d49fa4952a2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache @@ -0,0 +1,32 @@ +package {{package}}.impl; + +import {{package}}.*; +import {{modelPackage}}.*; + +import com.sun.jersey.multipart.FormDataParam; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; +import {{package}}.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; + +{{#operations}} +public class {{classname}}ServiceImpl extends {{classname}}Service { + {{#operation}} + @Override + public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache index 1bd168af747..64cfdc0af23 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache @@ -62,6 +62,25 @@ + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + @@ -129,7 +148,7 @@ - 1.5.2-M2-SNAPSHOT + 1.5.2-M2 9.2.9.v20150224 1.13 1.6.3 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceBodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceBodyParams.mustache new file mode 100644 index 00000000000..c7d1abfe527 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceBodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}{{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceFormParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceFormParams.mustache new file mode 100644 index 00000000000..e44ab167e8f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceFormParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceHeaderParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceHeaderParams.mustache new file mode 100644 index 00000000000..bd03573d196 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceHeaderParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}{{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/servicePathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/servicePathParams.mustache new file mode 100644 index 00000000000..6829cf8c7a6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/servicePathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}{{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceQueryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceQueryParams.mustache new file mode 100644 index 00000000000..ff79730471d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceQueryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}{{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/formParams.mustache index 83c928ea92e..402a684f86a 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/formParams.mustache @@ -1,2 +1,2 @@ {{#isFormParam}}{{#notFile}} -@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@RequestPart("{{paramName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file +@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestPart(value="{{paramName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/headerParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/headerParams.mustache index dd0ea1ad4ce..229717ddaa9 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/headerParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/headerParams.mustache @@ -1 +1 @@ -{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@RequestHeader("{{paramName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file +{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestHeader(value="{{paramName}}", required={{#required}}true{{/required}}{{^required}}false{{/required}}) {{{dataType}}} {{paramName}}{{/isHeaderParam}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/queryParams.mustache index 313289d9eaf..3bb2afcb6cd 100755 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value = "{{paramName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}) {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file +{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value = "{{paramName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isQueryParam}} 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 293079fbc97..c9dd5111861 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 @@ -19,3 +19,4 @@ com.wordnik.swagger.codegen.languages.StaticHtmlGenerator com.wordnik.swagger.codegen.languages.SwaggerGenerator com.wordnik.swagger.codegen.languages.SwaggerYamlGenerator com.wordnik.swagger.codegen.languages.TizenClientCodegen +com.wordnik.swagger.codegen.languages.AkkaScalaClientCodegen diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/api.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/api.mustache new file mode 100644 index 00000000000..fecf2827f04 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/api.mustache @@ -0,0 +1,43 @@ +package {{package}} + +{{#imports}} +import {{import}} +{{/imports}} +import {{invokerPackage}}._ +import {{invokerPackage}}.CollectionFormats._ +import {{invokerPackage}}.ApiKeyLocations._ + +{{#operations}} +object {{classname}} { + +{{#operation}} +{{#javadocRenderer}} +{{>javadoc}} +{{/javadocRenderer}} + def {{operationId}}({{>methodParameters}}): ApiRequest[{{>operationReturnType}}] = + ApiRequest[{{>operationReturnType}}](ApiMethods.{{httpMethod.toUpperCase}}, "{{basePath}}", "{{path}}", {{#consumes.0}}"{{mediaType}}"{{/consumes.0}}{{^consumes}}"application/json"{{/consumes}}) + {{#authMethods}}{{#isApiKey}}.withApiKey(apiKey, "{{keyParamName}}", {{#isKeyInQuery}}QUERY{{/isKeyInQuery}}{{#isKeyInHeader}}HEADER{{/isKeyInHeader}}) + {{/isApiKey}}{{#isBasic}}.withCredentials(basicAuth) + {{/isBasic}}{{/authMethods}}{{#bodyParam}}.withBody({{paramName}}) + {{/bodyParam}}{{#formParams}}.withFormParam({{>paramCreation}}) + {{/formParams}}{{#queryParams}}.withQueryParam({{>paramCreation}}) + {{/queryParams}}{{#pathParams}}.withPathParam({{>paramCreation}}) + {{/pathParams}}{{#headerParams}}.withHeaderParam({{>paramCreation}}) + {{/headerParams}}{{#responses}}{{^isWildcard}}{{#dataType}}.with{{>responseState}}Response[{{dataType}}]({{code}}) + {{/dataType}}{{^dataType}}.with{{>responseState}}Response[Unit]({{code}}) + {{/dataType}}{{/isWildcard}}{{/responses}}{{#responses}}{{#isWildcard}}{{#dataType}}.withDefault{{>responseState}}Response[{{dataType}}] + {{/dataType}}{{^dataType}}.withDefault{{>responseState}}Response[Unit] + {{/dataType}}{{/isWildcard}}{{/responses}}{{^responseHeaders.isEmpty}} + object {{#fnCapitalize}}{{operationId}}{{/fnCapitalize}}Headers { {{#responseHeaders}} + def {{name}}(r: ApiReturnWithHeaders) = r.get{{^isContainer}}{{baseType}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}Header("{{baseName}}"){{/responseHeaders}} + } + {{/responseHeaders.isEmpty}} +{{/operation}} + +{{#unknownStatusCodes}} + ApiInvoker.addCustomStatusCode({{value}}, isSuccess = false) +{{/unknownStatusCodes}} + +} + +{{/operations}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache new file mode 100644 index 00000000000..0dde3673439 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache @@ -0,0 +1,323 @@ +package {{invokerPackage}} + +import java.io.File +import java.security.cert.X509Certificate +import javax.net.ssl._ + +import akka.actor.ActorSystem +import akka.io.IO +import akka.pattern.ask +import akka.util.Timeout +import org.joda.time.DateTime +import org.joda.time.format.ISODateTimeFormat +import org.json4s.JsonAST.JString +import org.json4s._ +import org.json4s.jackson.JsonMethods._ +import org.json4s.jackson.Serialization +import spray.can.Http +import spray.can.Http.HostConnectorSetup +import spray.client.pipelining +import spray.client.pipelining._ +import spray.http.HttpEncodings._ +import spray.http.HttpHeaders.{RawHeader, `Accept-Encoding`} +import spray.http.Uri.Query +import spray.http._ +import spray.http.parser.HttpParser +import spray.httpx.encoding.{Deflate, Encoder, Gzip} +import spray.httpx.unmarshalling._ +import spray.io.ClientSSLEngineProvider + +import scala.concurrent.{ExecutionContext, Future} +import scala.reflect.ClassTag +import scala.util.control.NonFatal + +object ApiInvoker { + + def apply()(implicit system: ActorSystem): ApiInvoker = + apply(DefaultFormats + DateTimeSerializer) + def apply(serializers: Traversable[Serializer[_]])(implicit system: ActorSystem): ApiInvoker = + apply(DefaultFormats + DateTimeSerializer ++ serializers) + def apply(formats: Formats)(implicit system: ActorSystem): ApiInvoker = new ApiInvoker(formats) + + case class CustomStatusCode(value: Int, reason: String = "Application-defined status code", isSuccess: Boolean = true) + + def addCustomStatusCode(code: CustomStatusCode): Unit = addCustomStatusCode(code.value, code.reason, code.isSuccess) + + def addCustomStatusCode(code: Int, reason: String = "Application defined code", isSuccess: Boolean = true) = { + StatusCodes.getForKey(code) foreach { c => + StatusCodes.registerCustom(code, reason, reason, isSuccess, allowsEntity = true) + } + } + + /** + * Allows request execution without calling apiInvoker.execute(request) + * request.response can be used to get a future of the ApiResponse generated. + * request.result can be used to get a future of the expected ApiResponse content. If content doesn't match, a + * Future will failed with a ClassCastException + * @param request the apiRequest to be executed + */ + implicit class ApiRequestImprovements[T](request: ApiRequest[T]) { + + def response(invoker: ApiInvoker)(implicit ec: ExecutionContext, system: ActorSystem): Future[ApiResponse[T]] = + response(ec, system, invoker) + + def response(implicit ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[ApiResponse[T]] = + invoker.execute(request) + + def result[U <: T](implicit c: ClassTag[U], ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[U] = + invoker.execute(request).map(_.content).mapTo[U] + + } + + /** + * Allows transformation from ApiMethod to spray HttpMethods + * @param method the ApiMethod to be converted + */ + implicit class ApiMethodExtensions(val method: ApiMethod) { + def toSprayMethod: HttpMethod = HttpMethods.getForKey(method.value).getOrElse(HttpMethods.GET) + } + + case object DateTimeSerializer extends CustomSerializer[DateTime](format => ( { + case JString(s) => + ISODateTimeFormat.dateTimeParser().parseDateTime(s) + }, { + case d: DateTime => + JString(ISODateTimeFormat.dateTimeParser().print(d)) + })) +} + +class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends UntrustedSslContext with CustomContentTypes { + + import io.swagger.client.core.ApiInvoker._ + import io.swagger.client.core.ParametersMap._ + + implicit val ec = system.dispatcher + implicit val jsonFormats = formats + + def settings = ApiSettings(system) + + import spray.http.MessagePredicate._ + + val CompressionFilter = MessagePredicate({ _ => settings.compressionEnabled}) && + Encoder.DefaultFilter && + minEntitySize(settings.compressionSizeThreshold) + + settings.customCodes.foreach(addCustomStatusCode) + + private def addAuthentication(credentialsSeq: Seq[Credentials]): pipelining.RequestTransformer = + request => + credentialsSeq.foldLeft(request) { + case (req, BasicCredentials(login, password)) => + req ~> addCredentials(BasicHttpCredentials(login, password)) + case (req, ApiKeyCredentials(keyValue, keyName, ApiKeyLocations.HEADER)) => + req ~> addHeader(RawHeader(keyName, keyValue.value)) + case (req, _) => req + } + + private def addHeaders(headers: Map[String, Any]): pipelining.RequestTransformer = { request => + + val rawHeaders = for { + (name, value) <- headers.asFormattedParams + header = RawHeader(name, String.valueOf(value)) + } yield header + + request.withHeaders(rawHeaders.toList) + } + + private def bodyPart(name: String, value: Any): BodyPart = { + value match { + case f: File => + BodyPart(f, name) + case v: String => + BodyPart(HttpEntity(String.valueOf(v))) + case NumericValue(v) => + BodyPart(HttpEntity(String.valueOf(v))) + case m: ApiModel => + BodyPart(HttpEntity(Serialization.write(m))) + } + } + + private def formDataContent(request: ApiRequest[_]) = { + val params = request.formParams.asFormattedParams + if (params.isEmpty) + None + else + Some( + normalizedContentType(request.contentType).mediaType match { + case MediaTypes.`multipart/form-data` => + MultipartFormData(params.map { case (name, value) => (name, bodyPart(name, value))}) + case MediaTypes.`application/x-www-form-urlencoded` => + FormData(params.mapValues(String.valueOf)) + case m: MediaType => // Default : application/x-www-form-urlencoded. + FormData(params.mapValues(String.valueOf)) + } + ) + } + + private def bodyContent(request: ApiRequest[_]): Option[Any] = { + request.bodyParam.map(Extraction.decompose).map(compact) + } + + private def createRequest(uri: Uri, request: ApiRequest[_]): HttpRequest = { + + val builder = new RequestBuilder(request.method.toSprayMethod) + val httpRequest = request.method.toSprayMethod match { + case HttpMethods.GET | HttpMethods.DELETE => builder.apply(uri) + case HttpMethods.POST | HttpMethods.PUT => + formDataContent(request) orElse bodyContent(request) match { + case Some(c: FormData) => + builder.apply(uri, c) + case Some(c: MultipartFormData) => + builder.apply(uri, c) + case Some(c: String) => + builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), c)) + case _ => + builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), " ")) + } + case _ => builder.apply(uri) + } + + httpRequest ~> + addHeaders(request.headerParams) ~> + addAuthentication(request.credentials) ~> + encode(Gzip(CompressionFilter)) + } + + def makeQuery(r: ApiRequest[_]): Query = { + r.credentials.foldLeft(r.queryParams) { + case (params, ApiKeyCredentials(key, keyName, ApiKeyLocations.QUERY)) => + params + (keyName -> key.value) + case (params, _) => params + }.asFormattedParams + .mapValues(String.valueOf) + .foldRight[Query](Uri.Query.Empty) { + case ((name, value), acc) => acc.+:(name, value) + } + } + + def makeUri(r: ApiRequest[_]): Uri = { + val opPath = r.operationPath.replaceAll("\\{format\\}", "json") + val opPathWithParams = r.pathParams.asFormattedParams + .mapValues(String.valueOf) + .foldLeft(opPath) { + case (path, (name, value)) => path.replaceAll(s"\\{$name\\}", value) + } + val query = makeQuery(r) + + Uri(r.basePath + opPathWithParams).withQuery(query) + } + + def execute[T](r: ApiRequest[T]): Future[ApiResponse[T]] = { + try { + implicit val timeout: Timeout = settings.connectionTimeout + + val uri = makeUri(r) + + val connector = HostConnectorSetup( + uri.authority.host.toString, + uri.effectivePort, + sslEncryption = "https".equals(uri.scheme), + defaultHeaders = settings.defaultHeaders ++ List(`Accept-Encoding`(gzip, deflate))) + + val request = createRequest(uri, r) + + for { + Http.HostConnectorInfo(hostConnector, _) <- IO(Http) ? connector + response <- hostConnector.ask(request).mapTo[HttpResponse] + } yield { + response ~> decode(Deflate) ~> decode(Gzip) ~> unmarshallApiResponse(r) + } + } + catch { + case NonFatal(x) => Future.failed(x) + } + } + + def unmarshallApiResponse[T](request: ApiRequest[T])(response: HttpResponse): ApiResponse[T] = { + request.responseForCode(response.status.intValue) match { + case Some( (manifest: Manifest[T], state: ResponseState) ) => + entityUnmarshaller(manifest)(response.entity) match { + case Right(value) ⇒ + state match { + case ResponseState.Success => + ApiResponse(response.status.intValue, value, response.headers.map(header => (header.name, header.value)).toMap) + case ResponseState.Error => + throw new ApiError(response.status.intValue, "Error response received", + Some(value), + headers = response.headers.map(header => (header.name, header.value)).toMap) + } + + case Left(MalformedContent(error, Some(cause))) ⇒ + throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), cause) + + case Left(MalformedContent(error, None)) ⇒ + throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString)) + + case Left(ContentExpected) ⇒ + throw new ApiError(response.status.intValue, s"Unable to unmarshall empty response to [$manifest]", Some(response.entity.toString)) + } + + case _ => throw new ApiError(response.status.intValue, "Unexpected response code", Some(response.entity.toString)) + } + } + + def entityUnmarshaller[T](implicit mf: Manifest[T]): Unmarshaller[T] = + Unmarshaller[T](MediaTypes.`application/json`) { + case x: HttpEntity.NonEmpty ⇒ + parse(x.asString(defaultCharset = HttpCharsets.`UTF-8`)) + .noNulls + .camelizeKeys + .extract[T] + } + +} + +sealed trait CustomContentTypes { + + def normalizedContentType(original: String): ContentType = + MediaTypes.forExtension(original) map (ContentType(_)) getOrElse parseContentType(original) + + def parseContentType(contentType: String): ContentType = { + val contentTypeAsRawHeader = HttpHeaders.RawHeader("Content-Type", contentType) + val parsedContentTypeHeader = HttpParser.parseHeader(contentTypeAsRawHeader) + (parsedContentTypeHeader: @unchecked) match { + case Right(ct: HttpHeaders.`Content-Type`) => + ct.contentType + case Left(error: ErrorInfo) => + throw new IllegalArgumentException( + s"Error converting '$contentType' to a ContentType header: '${error.summary}'") + } + } +} + +sealed trait UntrustedSslContext { + this: ApiInvoker => + + implicit lazy val trustfulSslContext: SSLContext = { + settings.alwaysTrustCertificates match { + case false => + SSLContext.getDefault + + case true => + class IgnoreX509TrustManager extends X509TrustManager { + def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {} + + def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {} + + def getAcceptedIssuers = null + } + + val context = SSLContext.getInstance("TLS") + context.init(null, Array(new IgnoreX509TrustManager), null) + context + } + } + + implicit val clientSSLEngineProvider = + ClientSSLEngineProvider { + _ => + val engine = trustfulSslContext.createSSLEngine() + engine.setUseClientMode(true) + engine + } +} diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/apiRequest.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/apiRequest.mustache new file mode 100644 index 00000000000..3016768f7ac --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/apiRequest.mustache @@ -0,0 +1,50 @@ +package {{invokerPackage}} + +sealed trait ResponseState +object ResponseState { + case object Success extends ResponseState + case object Error extends ResponseState +} + +case class ApiRequest[U]( + // required fields + method: ApiMethod, + basePath: String, + operationPath: String, + contentType: String, + + // optional fields + responses: Map[Int, (Manifest[_], ResponseState)] = Map.empty, + bodyParam: Option[Any] = None, + formParams: Map[String, Any] = Map.empty, + pathParams: Map[String, Any] = Map.empty, + queryParams: Map[String, Any] = Map.empty, + headerParams: Map[String, Any] = Map.empty, + credentials: Seq[Credentials] = List.empty) { + + def withCredentials(cred: Credentials) = copy[U](credentials = credentials :+ cred) + + def withApiKey(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) = withCredentials(ApiKeyCredentials(key, keyName, location)) + + def withSuccessResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Success))) + + def withErrorResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Error))) + + def withDefaultSuccessResponse[T](implicit m: Manifest[T]) = withSuccessResponse[T](0) + + def withDefaultErrorResponse[T](implicit m: Manifest[T]) = withErrorResponse[T](0) + + def responseForCode(statusCode: Int): Option[(Manifest[_], ResponseState)] = responses.get(statusCode) orElse responses.get(0) + + def withoutBody() = copy[U](bodyParam = None) + + def withBody(body: Any) = copy[U](bodyParam = Some(body)) + + def withFormParam(name: String, value: Any) = copy[U](formParams = formParams + (name -> value)) + + def withPathParam(name: String, value: Any) = copy[U](pathParams = pathParams + (name -> value)) + + def withQueryParam(name: String, value: Any) = copy[U](queryParams = queryParams + (name -> value)) + + def withHeaderParam(name: String, value: Any) = copy[U](headerParams = headerParams + (name -> value)) +} diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/apiSettings.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/apiSettings.mustache new file mode 100644 index 00000000000..d3ffe3613ae --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/apiSettings.mustache @@ -0,0 +1,32 @@ +package {{invokerPackage}} + +import java.util.concurrent.TimeUnit + +import akka.actor.{ExtendedActorSystem, Extension, ExtensionKey} +import com.typesafe.config.Config +import io.swagger.client.core.ApiInvoker.CustomStatusCode +import spray.http.HttpHeaders.RawHeader + +import scala.collection.JavaConversions._ +import scala.concurrent.duration.FiniteDuration + +class ApiSettings(config: Config) extends Extension { + def this(system: ExtendedActorSystem) = this(system.settings.config) + + private def cfg = config.getConfig("io.swagger.client.apiRequest") + + val alwaysTrustCertificates = cfg.getBoolean("trust-certificates") + val defaultHeaders = cfg.getConfig("default-headers").entrySet.toList.map(c => RawHeader(c.getKey, c.getValue.render)) + val connectionTimeout = FiniteDuration(cfg.getDuration("connection-timeout", TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS) + val compressionEnabled = cfg.getBoolean("compression.enabled") + val compressionSizeThreshold = cfg.getBytes("compression.size-threshold").toInt + val customCodes = cfg.getConfigList("custom-codes").toList.map { c => CustomStatusCode( + c.getInt("code"), + c.getString("reason"), + c.getBoolean("success")) + } + + +} + +object ApiSettings extends ExtensionKey[ApiSettings] diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/enumsSerializers.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/enumsSerializers.mustache new file mode 100644 index 00000000000..52f1fd3e330 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/enumsSerializers.mustache @@ -0,0 +1,42 @@ +package {{apiPackage}} + +import {{modelPackage}}._ +import org.json4s._ +import scala.reflect.ClassTag + +object EnumsSerializers { + + def all = Seq[Serializer[_]](){{#models}}{{#model}}{{#hasEnums}}{{#vars}}{{#isEnum}} :+ + new EnumNameSerializer({{classname}}Enums.{{datatypeWithEnum}}){{/isEnum}}{{/vars}}{{/hasEnums}}{{/model}}{{/models}} + + + + private class EnumNameSerializer[E <: Enumeration: ClassTag](enum: E) + extends Serializer[E#Value] { + import JsonDSL._ + + val EnumerationClass = classOf[E#Value] + + def deserialize(implicit format: Formats): + PartialFunction[(TypeInfo, JValue), E#Value] = { + case (t @ TypeInfo(EnumerationClass, _), json) if isValid(json) => { + json match { + case JString(value) => + enum.withName(value) + case value => + throw new MappingException(s"Can't convert $value to $EnumerationClass") + } + } + } + + private[this] def isValid(json: JValue) = json match { + case JString(value) if enum.values.exists(_.toString == value) => true + case _ => false + } + + def serialize(implicit format: Formats): PartialFunction[Any, JValue] = { + case i: E#Value => i.toString + } + } + +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/javadoc.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/javadoc.mustache new file mode 100644 index 00000000000..0d22fd62374 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/javadoc.mustache @@ -0,0 +1,21 @@ +{{^notes.isEmpty}} +{{notes}} +{{/notes.isEmpty}} + +Expected answers: +{{#responses}} + code {{code}} : {{dataType}} {{^message.isEmpty}}({{message}}){{/message.isEmpty}}{{^headers.isEmpty}} + Headers :{{#headers}} + {{baseName}} - {{description}}{{/headers}}{{/headers.isEmpty}} +{{/responses}} +{{#authMethods.0}} + +Available security schemes: +{{#authMethods}} + {{name}} ({{type}}) +{{/authMethods}} +{{/authMethods.0}} + +{{#allParams}} +@param {{paramName}} {{description}} +{{/allParams}} diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/methodParameters.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/methodParameters.mustache new file mode 100644 index 00000000000..3e1ab33f665 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/methodParameters.mustache @@ -0,0 +1 @@ +{{#allParams}}{{paramName}}: {{#required}}{{dataType}}{{/required}}{{^required}}{{#isContainer}}{{dataType}}{{/isContainer}}{{^isContainer}}Option[{{dataType}}]{{/isContainer}}{{/required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}{{^required}}{{^isContainer}} = None{{/isContainer}}{{/required}}{{/defaultValue}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#authMethods.0}})(implicit {{#authMethods}}{{#isApiKey}}apiKey: ApiKeyValue{{/isApiKey}}{{#isBasic}}basicAuth: BasicCredentials{{/isBasic}}{{#hasMore}}, {{/hasMore}}{{/authMethods}}{{/authMethods.0}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/model.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/model.mustache new file mode 100644 index 00000000000..a7395b5f03a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/model.mustache @@ -0,0 +1,30 @@ +package {{package}} + +import {{invokerPackage}}.ApiModel +import org.joda.time.DateTime + +{{#models}} +{{#model}} + +case class {{classname}} ( + {{#vars}}{{#description}}/* {{{description}}} */ + {{/description}}{{name}}: {{^required}}Option[{{/required}}{{^isEnum}}{{datatype}}{{/isEnum}}{{#isEnum}}{{classname}}Enums.{{datatypeWithEnum}}{{/isEnum}}{{^required}}]{{/required}}{{#hasMore}},{{/hasMore}}{{^hasMore}}){{/hasMore}} + {{/vars}} extends ApiModel + +{{#hasEnums}} +object {{classname}}Enums { + + {{#vars}}{{#isEnum}}type {{datatypeWithEnum}} = {{datatypeWithEnum}}.Value + {{/isEnum}}{{/vars}} + {{#vars}}{{#isEnum}}object {{datatypeWithEnum}} extends Enumeration { +{{#_enum}} + val {{#fnEnumEntry}}{{.}}{{/fnEnumEntry}} = Value("{{.}}") +{{/_enum}} + } + + {{/isEnum}}{{/vars}} +} +{{/hasEnums}} +{{/model}} +{{/models}} + diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/operationReturnType.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/operationReturnType.mustache new file mode 100644 index 00000000000..ba0924313fb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/operationReturnType.mustache @@ -0,0 +1 @@ +{{#onlyOneSuccess}}{{^defaultResponse}}Unit{{/defaultResponse}}{{#defaultResponse}}{{#responses}}{{#isDefault}}{{#dataType}}{{dataType}}{{/dataType}}{{^dataType}}Unit{{/dataType}}{{/isDefault}}{{/responses}}{{/defaultResponse}}{{/onlyOneSuccess}}{{^onlyOneSuccess}}{{#responses}}{{#-first}}{{^hasMore}}{{#dataType}}{{dataType}}{{/dataType}}{{^dataType}}Unit{{/dataType}}{{/hasMore}}{{#hasMore}}Any{{/hasMore}}{{/-first}}{{/responses}}{{/onlyOneSuccess}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/paramCreation.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/paramCreation.mustache new file mode 100644 index 00000000000..f93d3765038 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/paramCreation.mustache @@ -0,0 +1 @@ +"{{baseName}}", {{#isContainer}}ArrayValues({{paramName}}{{#collectionFormat}}, {{collectionFormat.toUpperCase}}{{/collectionFormat}}){{/isContainer}}{{^isContainer}}{{paramName}}{{/isContainer}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache new file mode 100644 index 00000000000..0d65c135957 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache @@ -0,0 +1,227 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + 2.2.0 + + + + + maven-mongodb-plugin-repo + maven mongodb plugin repository + http://maven-mongodb-plugin.googlecode.com/svn/maven/repo + default + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + + 1.6 + 1.6 + + + + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin-version} + + + scala-compile-first + process-resources + + add-source + compile + + + + scala-test-compile + process-test-resources + + testCompile + + + + + + -feature + + + -Xms128m + -Xmx1500m + + + + + + + + + org.scala-tools + maven-scala-plugin + + ${scala-version} + + + + + + + org.scala-lang + scala-library + ${scala-version} + + + com.wordnik + swagger-core + ${swagger-core-version} + + + org.scalatest + scalatest_2.10 + ${scala-test-version} + test + + + junit + junit + ${junit-version} + test + + + joda-time + joda-time + ${joda-time-version} + + + org.joda + joda-convert + ${joda-version} + + + com.typesafe + config + 1.2.1 + + + com.typesafe.akka + akka-actor_2.10 + ${akka-version} + + + io.spray + spray-client + ${spray-version} + + + org.json4s + json4s-jackson_2.10 + ${json4s-jackson-version} + + + + 2.10.4 + 3.2.11 + 3.2.11 + 1.3.1 + 2.3.9 + 1.2 + 2.2 + 1.5.0-M1 + 1.0.0 + + 4.8.1 + 3.1.5 + 2.1.3 + + diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/reference.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/reference.mustache new file mode 100644 index 00000000000..1a28a8962ed --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/reference.mustache @@ -0,0 +1,24 @@ +{{configKeyPath}} { + + {{configKey}} { + + compression { + enabled: false + size-threshold: 0 + } + + trust-certificates: true + + connection-timeout: {{defaultTimeout}}ms + + default-headers { + "userAgent": "{{artifactId}}_{{artifactVersion}}" + } + + // let you define custom http status code, as in : + // { code: 601, reason: "some custom http status code", success: false } + custom-codes : [] + } +} + +spray.can.host-connector.max-redirects = 10 \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/requests.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/requests.mustache new file mode 100644 index 00000000000..145354203fb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/requests.mustache @@ -0,0 +1,166 @@ +package {{invokerPackage}} + +import java.io.File +import java.net.URLEncoder +import scala.util.Try + +sealed trait ApiReturnWithHeaders { + def headers: Map[String, String] + def header(name: String): Option[String] = headers.get(name) + def getStringHeader(name: String) = header(name) + def getIntHeader(name: String) = castedHeader(name, java.lang.Integer.parseInt) + def getLongHeader(name: String) = castedHeader(name, java.lang.Long.parseLong) + def getFloatHeader(name: String) = castedHeader(name, java.lang.Float.parseFloat) + def getDoubleHeader(name: String) = castedHeader(name, java.lang.Double.parseDouble) + def getBooleanHeader(name: String) = castedHeader(name, java.lang.Boolean.parseBoolean) + private def castedHeader[U](name: String, conversion: String => U): Option[U] = { Try { header(name).map( conversion ) }.get } +} + +sealed case class ApiResponse[T](code: Int, content: T, headers: Map[String, String] = Map.empty) + extends ApiReturnWithHeaders + +sealed case class ApiError[T](code: Int, message: String, responseContent: Option[T], cause: Throwable = null, headers: Map[String, String] = Map.empty) + extends Throwable(s"($code) $message.${responseContent.map(s => s" Content : $s").getOrElse("")}", cause) + with ApiReturnWithHeaders + +sealed case class ApiMethod(value: String) + +object ApiMethods { + val CONNECT = ApiMethod("CONNECT") + val DELETE = ApiMethod("DELETE") + val GET = ApiMethod("GET") + val HEAD = ApiMethod("HEAD") + val OPTIONS = ApiMethod("OPTIONS") + val PATCH = ApiMethod("PATCH") + val POST = ApiMethod("POST") + val PUT = ApiMethod("PUT") + val TRACE = ApiMethod("TRACE") +} + +/** + * This trait needs to be added to any model defined by the api. + */ +trait ApiModel + +/** + * Single trait defining a credential that can be transformed to a paramName / paramValue tupple + */ +sealed trait Credentials { + def asQueryParam: Option[(String, String)] = None +} + +sealed case class BasicCredentials(user: String, password: String) extends Credentials + +sealed case class ApiKeyCredentials(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) extends Credentials { + override def asQueryParam: Option[(String, String)] = location match { + case ApiKeyLocations.QUERY => Some((keyName, key.value)) + case _ => None + } +} + +sealed case class ApiKeyValue(value: String) + +sealed trait ApiKeyLocation + +object ApiKeyLocations { + + case object QUERY extends ApiKeyLocation + + case object HEADER extends ApiKeyLocation +} + + +/** + * Case class used to unapply numeric values only in pattern matching + * @param value the string representation of the numeric value + */ +sealed case class NumericValue(value: String) { + override def toString = value +} + +object NumericValue { + def unapply(n: Any): Option[NumericValue] = n match { + case (_: Int | _: Long | _: Float | _: Double | _: Boolean | _: Byte) => Some(NumericValue(String.valueOf(n))) + case _ => None + } +} + +/** + * Used for params being arrays + */ +sealed case class ArrayValues(values: Seq[Any], format: CollectionFormat = CollectionFormats.CSV) + +object ArrayValues { + def apply(values: Option[Seq[Any]], format: CollectionFormat): ArrayValues = + ArrayValues(values.getOrElse(Seq.empty), format) + + def apply(values: Option[Seq[Any]]): ArrayValues = ArrayValues(values, CollectionFormats.CSV) +} + + +/** + * Defines how arrays should be rendered in query strings. + */ +sealed trait CollectionFormat + +trait MergedArrayFormat extends CollectionFormat { + def separator: String +} + +object CollectionFormats { + + case object CSV extends MergedArrayFormat { + override val separator = "," + } + + case object TSV extends MergedArrayFormat { + override val separator = "\t" + } + + case object SSV extends MergedArrayFormat { + override val separator = " " + } + + case object PIPES extends MergedArrayFormat { + override val separator = "|" + } + + case object MULTI extends CollectionFormat + +} + +object ParametersMap { + + /** + * Pimp parameters maps (Map[String, Any]) in order to transform them in a sequence of String -> Any tupples, + * with valid url-encoding, arrays handling, files preservation, ... + */ + implicit class ParametersMapImprovements(val m: Map[String, Any]) { + + def asFormattedParamsList = m.toList.flatMap(formattedParams) + + def asFormattedParams = m.flatMap(formattedParams) + + private def urlEncode(v: Any) = URLEncoder.encode(String.valueOf(v), "utf-8").replaceAll("\\+", "%20") + + private def formattedParams(tuple: (String, Any)): Seq[(String, Any)] = formattedParams(tuple._1, tuple._2) + + private def formattedParams(name: String, value: Any): Seq[(String, Any)] = value match { + case arr: ArrayValues => + arr.format match { + case CollectionFormats.MULTI => arr.values.flatMap(formattedParams(name, _)) + case format: MergedArrayFormat => Seq((name, arr.values.mkString(format.separator))) + } + case None => Seq.empty + case Some(opt) => + formattedParams(name, opt) + case s: Seq[Any] => + formattedParams(name, ArrayValues(s)) + case v: String => Seq((name, urlEncode(v))) + case NumericValue(v) => Seq((name, urlEncode(v))) + case f: File => Seq((name, f)) + case m: ApiModel => Seq((name, m)) + } + + } +} diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/responseState.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/responseState.mustache new file mode 100644 index 00000000000..c6d44b86d87 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/responseState.mustache @@ -0,0 +1 @@ +{{#onlyOneSuccess}}{{#isDefault}}Success{{/isDefault}}{{^isDefault}}Error{{/isDefault}}{{/onlyOneSuccess}}{{^onlyOneSuccess}}Success{{/onlyOneSuccess}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/android-java/build.mustache b/modules/swagger-codegen/src/main/resources/android-java/build.mustache index 80c0d375ddb..62a56bf066e 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/build.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/build.mustache @@ -1,9 +1,17 @@ +{{#useAndroidMavenGradlePlugin}} +group = '{{groupId}}' +project.version = '{{artifactVersion}}' +{{/useAndroidMavenGradlePlugin}} + buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.2.2' + {{#useAndroidMavenGradlePlugin}} + classpath 'com.github.dcendents:android-maven-plugin:1.2' + {{/useAndroidMavenGradlePlugin}} } } @@ -13,7 +21,11 @@ allprojects { } } + apply plugin: 'com.android.library' +{{#useAndroidMavenGradlePlugin}} +apply plugin: 'com.github.dcendents.android-maven' +{{/useAndroidMavenGradlePlugin}} android { compileSdkVersion 22 @@ -22,6 +34,17 @@ android { minSdkVersion 14 targetSdkVersion 22 } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } } @@ -37,7 +60,12 @@ dependencies { compile "com.google.code.gson:gson:$gson_version" compile "org.apache.httpcomponents:httpcore:$httpclient_version" compile "org.apache.httpcomponents:httpclient:$httpclient_version" - compile "org.apache.httpcomponents:httpmime:$httpclient_version" + compile ("org.apache.httpcomponents:httpcore:$httpcore_version") { + exclude(group: 'org.apache.httpcomponents', module: 'httpclient') + } + compile ("org.apache.httpcomponents:httpmime:$httpmime_version") { + exclude(group: 'org.apache.httpcomponents', module: 'httpclient') + } testCompile "junit:junit:$junit_version" } @@ -48,7 +76,18 @@ afterEvaluate { task.dependsOn variant.javaCompile task.from variant.javaCompile.destinationDir task.destinationDir = project.file("${project.buildDir}/outputs/jar") - task.archiveName = "${project.name}-${variant.baseName}.jar" + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" artifacts.add('archives', task); } -} \ No newline at end of file +} + +{{#useAndroidMavenGradlePlugin}} +task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' +} + +artifacts { + archives sourcesJar +} +{{/useAndroidMavenGradlePlugin}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/android-java/settings.gradle.mustache b/modules/swagger-codegen/src/main/resources/android-java/settings.gradle.mustache new file mode 100644 index 00000000000..b8fd6c4c41f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android-java/settings.gradle.mustache @@ -0,0 +1 @@ +rootProject.name = "{{artifactId}}" \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 084caf97b9b..f7cc79c5255 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using RestSharp; using {{invokerPackage}}; using {{modelPackage}}; {{#imports}} @@ -9,101 +10,73 @@ namespace {{package}} { {{#operations}} public class {{classname}} { string basePath; - private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); + protected RestClient restClient; public {{classname}}(String basePath = "{{basePath}}") { this.basePath = basePath; + this.restClient = new RestClient(basePath); } - public ApiInvoker getInvoker() { - return apiInvoker; - } - - // Sets the endpoint base url for the services being accessed - public void setBasePath(string basePath) { + /// + /// Sets the endpoint base url for the services being accessed + /// + /// Base URL + /// + public void SetBasePath(string basePath) { this.basePath = basePath; } - // Gets the endpoint base url for the services being accessed - public String getBasePath() { - return basePath; + /// + /// Gets the endpoint base url for the services being accessed + /// Base URL + /// + public String GetBasePath() { + return this.basePath; } {{#operation}} - + /// /// {{summary}} {{notes}} /// - {{#allParams}}/// {{description}} - {{#hasMore}} {{/hasMore}}{{/allParams}} - /// - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - // create path and map variables - var path = "{{path}}".Replace("{format}","json"){{#pathParams}}.Replace("{" + "{{baseName}}" + "}", apiInvoker.ParameterToString({{{paramName}}})){{/pathParams}}; +{{#allParams}} /// {{description}} +{{/allParams}} + /// {{#returnType}}{{{returnType}}}{{/returnType}} + public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("{{path}}", Method.{{httpMethod}}); - {{#requiredParamCount}} - // verify required params are set - if ({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) { - throw new ApiException(400, "missing required params"); + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); + {{/required}}{{/allParams}} + + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } - {{/requiredParamCount}} - {{#queryParams}}if ({{paramName}} != null){ - queryParams.Add("{{baseName}}", apiInvoker.ParameterToString({{paramName}})); - } + _request.AddUrlSegment("format", "json"); // set format to json by default + {{#pathParams}}_request.AddUrlSegment("{{baseName}}", ApiInvoker.ParameterToString({{{paramName}}})); // path (url segment) parameter + {{/pathParams}} + {{#queryParams}} if ({{paramName}} != null) _request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // query parameter {{/queryParams}} - - {{#headerParams}}headerParams.Add("{{baseName}}", apiInvoker.ParameterToString({{paramName}})); + {{#headerParams}} if ({{paramName}} != null) _request.AddHeader("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // header parameter {{/headerParams}} - - {{#formParams}}if ({{paramName}} != null){ - if({{paramName}} is byte[]) { - formParams.Add("{{baseName}}", {{paramName}}); - } else { - formParams.Add("{{baseName}}", apiInvoker.ParameterToString({{paramName}})); - } - } + {{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // form parameter{{/isFile}} {{/formParams}} + {{#bodyParam}}_request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody); // http body (model) parameter + {{/bodyParam}} - try { - if (typeof({{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}) == typeof(byte[])) { - {{#returnType}} - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as {{{returnType}}}; - {{/returnType}} - {{^returnType}} - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - {{/returnType}} - } else { - {{#returnType}} - var response = apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, headerParams, formParams); - if (response != null){ - return ({{{returnType}}}) ApiInvoker.deserialize(response, typeof({{{returnType}}})); - } - else { - return null; - } - {{/returnType}} - {{^returnType}} - apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, headerParams, formParams); - return; - {{/returnType}} - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return {{#returnType}}null{{/returnType}}; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content); } + {{#returnType}}return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}} + return;{{/returnType}} } {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache b/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache index 3b371aea9a8..f28eb8de6f7 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache @@ -1,21 +1,17 @@ using System; namespace {{invokerPackage}} { + public class ApiException : Exception { - - private int errorCode = 0; + + public int ErrorCode { get; set; } public ApiException() {} - public int ErrorCode { - get - { - return errorCode; - } + public ApiException(int errorCode, string message) : base(message) { + this.ErrorCode = errorCode; } - public ApiException(int errorCode, string message) : base(message) { - this.errorCode = errorCode; - } } -} \ No newline at end of file + +} diff --git a/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache index 4e7f1b6997b..9beebc19231 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache @@ -1,235 +1,81 @@ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Net; - using System.Text; - using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using Newtonsoft.Json; - namespace {{invokerPackage}} { - public class ApiInvoker { - private static readonly ApiInvoker _instance = new ApiInvoker(); - private Dictionary defaultHeaderMap = new Dictionary(); +namespace {{invokerPackage}} { + public class ApiInvoker { + private static Dictionary defaultHeaderMap = new Dictionary(); - public static ApiInvoker GetInstance() { - return _instance; - } + /// + /// Add default header + /// + /// Header field name + /// Header field value + /// + public static void AddDefaultHeader(string key, string value) { + defaultHeaderMap.Add(key, value); + } - /// - /// Add default header - /// - /// Header field name - /// Header field value - /// - public void addDefaultHeader(string key, string value) { - defaultHeaderMap.Add(key, value); - } + /// + /// Get default header + /// + /// Dictionary of default header + public static Dictionary GetDefaultHeader() { + return defaultHeaderMap; + } - /// - /// escape string (url-encoded) - /// - /// String to be escaped - /// Escaped string - public string escapeString(string str) { - return str; - } + /// + /// escape string (url-encoded) + /// + /// String to be escaped + /// Escaped string + public static string EscapeString(string str) { + return str; + } - /// - /// if parameter is DateTime, output in ISO8601 format, otherwise just return the string - /// - /// The parameter (header, path, query, form) - /// Formatted string - public string ParameterToString(object obj) + /// + /// if parameter is DateTime, output in ISO8601 format, otherwise just return the string + /// + /// The parameter (header, path, query, form) + /// Formatted string + public static string ParameterToString(object obj) + { + return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : Convert.ToString (obj); + } + + /// + /// Deserialize the JSON string into a proper object + /// + /// JSON string + /// Object type + /// Object representation of the JSON string + public static object Deserialize(string json, Type type) { + try { - return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : Convert.ToString (obj); + return JsonConvert.DeserializeObject(json, type); } - - /// - /// Deserialize the JSON string into a proper object - /// - /// JSON string - /// Object type - /// Object representation of the JSON string - public static object deserialize(string json, Type type) { - try - { - return JsonConvert.DeserializeObject(json, type); - } - catch (IOException e) { - throw new ApiException(500, e.Message); - } - + catch (IOException e) { + throw new ApiException(500, e.Message); } + } - public static string serialize(object obj) { - try - { - return obj != null ? JsonConvert.SerializeObject(obj) : null; - } - catch (Exception e) { - throw new ApiException(500, e.Message); - } - } - - public string invokeAPI(string host, string path, string method, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) + /// + /// Serialize an object into JSON string + /// + /// Object + /// JSON string + public static string Serialize(object obj) { + try { - return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string; + return obj != null ? JsonConvert.SerializeObject(obj) : null; } - - public byte[] invokeBinaryAPI(string host, string path, string method, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) - { - return invokeAPIInternal(host, path, method, true, queryParams, body, headerParams, formParams) as byte[]; - } - - private object invokeAPIInternal(string host, string path, string method, bool binaryResponse, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) { - var b = new StringBuilder(); - - foreach (var queryParamItem in queryParams) - { - var value = queryParamItem.Value; - if (value == null) continue; - b.Append(b.ToString().Length == 0 ? "?" : "&"); - b.Append(escapeString(queryParamItem.Key)).Append("=").Append(escapeString(value)); - } - - var querystring = b.ToString(); - - host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host; - - var client = WebRequest.Create(host + path + querystring); - client.Method = method; - - byte[] formData = null; - if (formParams.Count > 0) - { - string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid()); - client.ContentType = "multipart/form-data; boundary=" + formDataBoundary; - formData = GetMultipartFormData(formParams, formDataBoundary); - client.ContentLength = formData.Length; - } - else - { - client.ContentType = "application/json"; - } - - foreach (var headerParamsItem in headerParams) - { - client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value); - } - foreach (var defaultHeaderMapItem in defaultHeaderMap.Where(defaultHeaderMapItem => !headerParams.ContainsKey(defaultHeaderMapItem.Key))) - { - client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value); - } - - switch (method) - { - case "GET": - break; - case "POST": - case "PATCH": - case "PUT": - case "DELETE": - using (Stream requestStream = client.GetRequestStream()) - { - if (formData != null) - { - requestStream.Write(formData, 0, formData.Length); - } - - var swRequestWriter = new StreamWriter(requestStream); - swRequestWriter.Write(serialize(body)); - swRequestWriter.Close(); - } - break; - default: - throw new ApiException(500, "unknown method type " + method); - } - - try - { - var webResponse = (HttpWebResponse)client.GetResponse(); - if (webResponse.StatusCode != HttpStatusCode.OK) - { - webResponse.Close(); - throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription); - } - - if (binaryResponse) - { - using (var memoryStream = new MemoryStream()) - { - webResponse.GetResponseStream().CopyTo(memoryStream); - return memoryStream.ToArray(); - } - } - else - { - using (var responseReader = new StreamReader(webResponse.GetResponseStream())) - { - var responseData = responseReader.ReadToEnd(); - return responseData; - } - } - } - catch(WebException ex) - { - var response = ex.Response as HttpWebResponse; - int statusCode = 0; - if (response != null) - { - statusCode = (int)response.StatusCode; - response.Close(); - } - throw new ApiException(statusCode, ex.Message); - } - } - - private static byte[] GetMultipartFormData(Dictionary postParameters, string boundary) - { - Stream formDataStream = new System.IO.MemoryStream(); - bool needsCLRF = false; - - foreach (var param in postParameters) - { - // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added. - // Skip it on the first parameter, add it to subsequent parameters. - if (needsCLRF) - formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n")); - - needsCLRF = true; - - if (param.Value is byte[]) - { - string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", - boundary, - param.Key, - "application/octet-stream"); - formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); - - // Write the file data directly to the Stream, rather than serializing it to a string. - formDataStream.Write((param.Value as byte[]), 0, (param.Value as byte[]).Length); - } - else - { - string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", - boundary, - param.Key, - param.Value); - formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); - } - } - - // Add the end of the request. Start with a newline - string footer = "\r\n--" + boundary + "--\r\n"; - formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer)); - - // Dump the Stream into a byte[] - formDataStream.Position = 0; - byte[] formData = new byte[formDataStream.Length]; - formDataStream.Read(formData, 0, formData.Length); - formDataStream.Close(); - - return formData; + catch (Exception e) { + throw new ApiException(500, e.Message); } } } +} diff --git a/modules/swagger-codegen/src/main/resources/csharp/model.mustache b/modules/swagger-codegen/src/main/resources/csharp/model.mustache index d9ef4ffbedd..a8a3aa3a7a2 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/model.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/model.mustache @@ -2,19 +2,19 @@ using System; using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; {{#models}} {{#model}} namespace {{package}} { + [DataContract] public class {{classname}} { {{#vars}} - - {{#description}}/* {{{description}}} */ - {{/description}} + {{#description}}/* {{{description}}} */{{/description}} + [DataMember(Name="{{baseName}}", EmitDefaultValue=false)] public {{{datatype}}} {{name}} { get; set; } {{/vars}} - public override string ToString() { var sb = new StringBuilder(); sb.Append("class {{classname}} {\n"); @@ -27,4 +27,4 @@ namespace {{package}} { } {{/model}} {{/models}} -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache index 99ecb80ac1a..ce881084bc2 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache @@ -35,7 +35,7 @@ {{#examples}}

Example data

Content-Type: {{{contentType}}}
-
{{{example}}}
+
{{example}}
{{/examples}}
diff --git a/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601.h b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601.h new file mode 100644 index 00000000000..832f485f4f0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601.h @@ -0,0 +1,6 @@ +#import +#import +#import + +@interface JSONValueTransformer (ISO8601) +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601.m b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601.m new file mode 100644 index 00000000000..cec8bdeea27 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601.m @@ -0,0 +1,10 @@ +#import "JSONValueTransformer+ISO8601.h" + +@implementation JSONValueTransformer (ISO8601) + +- (NSDate *) NSDateFromNSString:(NSString *)string +{ + return [NSDate dateWithISO8601String:string]; +} + +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/Podfile.mustache b/modules/swagger-codegen/src/main/resources/objc/Podfile.mustache index 1a9d463c86a..c61ab59dd8f 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Podfile.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Podfile.mustache @@ -2,3 +2,4 @@ platform :ios, '6.0' xcodeproj '{{projectName}}/{{projectName}}.xcodeproj' pod 'AFNetworking', '~> 2.1' pod 'JSONModel', '~> 1.0' +pod 'ISO8601' diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGDate.h b/modules/swagger-codegen/src/main/resources/objc/SWGDate.h deleted file mode 100644 index 2c6c7cfe01b..00000000000 --- a/modules/swagger-codegen/src/main/resources/objc/SWGDate.h +++ /dev/null @@ -1,12 +0,0 @@ -#import -#import "SWGObject.h" - -@interface SWGDate : SWGObject { -@private - NSDate *_date; -} -@property(nonatomic, readonly) NSDate* date; - -- (id) initWithValues: (NSString*)input; --(NSString*) toString; -@end \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGDate.m b/modules/swagger-codegen/src/main/resources/objc/SWGDate.m deleted file mode 100644 index 07a1405626b..00000000000 --- a/modules/swagger-codegen/src/main/resources/objc/SWGDate.m +++ /dev/null @@ -1,34 +0,0 @@ -#import "SWGDate.h" - -@implementation SWGDate - -@synthesize date = _date; - -- (id) initWithValues:(NSString*)input { - if([input isKindOfClass:[NSString class]]){ - NSDateFormatter* df = [NSDateFormatter new]; - NSLocale *locale = [[NSLocale new] - initWithLocaleIdentifier:@"en_US_POSIX"]; - [df setLocale:locale]; - [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"]; - - _date = [df dateFromString:input]; - } - else if([input isKindOfClass:[NSNumber class]]) { - NSTimeInterval interval = [input doubleValue]; - _date = [[NSDate alloc] initWithTimeIntervalSince1970:interval]; - } - return self; -} - --(NSString*) toString { - NSDateFormatter* df = [NSDateFormatter new]; - NSLocale *locale = [[NSLocale new] - initWithLocaleIdentifier:@"en_US_POSIX"]; - [df setLocale:locale]; - [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"]; - - return [df stringFromDate:_date]; -} - -@end \ No newline at end of file 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 37699206f2b..34e20e36f9a 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -69,6 +69,11 @@ static NSString * basePath = @"{{basePath}}"; {{#returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{{returnType}}} output, NSError* error))completionBlock{{/returnBaseType}} {{^returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)(NSError* error))completionBlock{{/returnBaseType}} { + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + NSAssert({{paramName}} != nil, @"Missing the required parameter `{{paramName}}` when calling {{nickname}}"); + {{/required}}{{/allParams}} + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@{{path}}", basePath]; // remove format in URL if needed diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index a750daff12d..b8b8eff4295 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -24,6 +24,8 @@ class APIClient { public static $GET = "GET"; public static $PUT = "PUT"; public static $DELETE = "DELETE"; + + private static $default_header = array(); /* * @var string timeout (second) of the HTTP request, by default set to 0, no timeout @@ -36,37 +38,110 @@ class APIClient { protected $user_agent = "PHP-Swagger"; /** - * @param string $host the address of the API server - * @param string $headerName a header to pass on requests + * @param string $host Base url of the API server (optional) */ - function __construct($host, $headerName = null, $headerValue = null) { - $this->host = $host; - $this->headerName = $headerName; - $this->headerValue = $headerValue; + function __construct($host = null) { + if ($host == null) { + $this->host = '{{basePath}}'; + } else { + $this->host = $host; + } } /** - * Set the user agent of the API client + * add default header * - * @param string $user_agent The user agent of the API client + * @param string $header_name header name (e.g. Token) + * @param string $header_value header value (e.g. 1z8wp3) + */ + public function addDefaultHeader($header_name, $header_value) { + if (!is_string($header_name)) + throw new \InvalidArgumentException('Header name must be a string.'); + + self::$default_header[$header_name] = $header_value; + } + + /** + * get the default header + * + * @return array default header + */ + public function getDefaultHeader() { + return self::$default_header; + } + + /** + * delete the default header based on header name + * + * @param string $header_name header name (e.g. Token) + */ + public function deleteDefaultHeader($header_name) { + unset(self::$default_header[$header_name]); + } + + /** + * set the user agent of the api client + * + * @param string $user_agent the user agent of the api client */ public function setUserAgent($user_agent) { - if (!is_string($user_agent)) { - throw new Exception('User-agent must be a string.'); - } + if (!is_string($user_agent)) + throw new \InvalidArgumentException('User-agent must be a string.'); + $this->user_agent= $user_agent; } /** * @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 Exception('Timeout variable must be numeric.'); - } + if (!is_numeric($seconds)) + throw new \InvalidArgumentException('Timeout variable must be numeric.'); + $this->curl_timeout = $seconds; } + /** + * 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]) { + return Configuration::$apiKeyPrefix[$apiKey]." ".Configuration::$apiKey[$apiKey]; + } else { + return Configuration::$apiKey[$apiKey]; + } + } + + /** + * update hearder and query param based on authentication setting + * + * @param array $headerParams header parameters (by ref) + * @param array $queryParams query parameters (by ref) + * @param array $authSettings array of authentication scheme (e.g ['api_key']) + */ + public function updateParamsForAuth(&$headerParams, &$queryParams, $authSettings) + { + if (count($authSettings) == 0) + return; + + // one endpoint can have more than 1 auth settings + foreach($authSettings as $auth) { + // determine which one to use + switch($auth) { + {{#authMethods}} + case '{{name}}': + {{#isApiKey}}{{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}$headerParams['Authorization'] = 'Basic '.base64_encode(Configuration::$username.":".Configuration::$password);{{/isBasic}} + {{#isOAuth}}//TODO support oauth{{/isOAuth}} + break; + {{/authMethods}} + default: + //TODO show warning about security definition not found + } + } + } + /** * @param string $resourcePath path to method endpoint * @param string $method method to call @@ -76,23 +151,22 @@ class APIClient { * @return mixed */ public function callAPI($resourcePath, $method, $queryParams, $postData, - $headerParams) { + $headerParams, $authSettings) { $headers = array(); - # Allow API key from $headerParams to override default - $added_api_key = False; + # determine authentication setting + $this->updateParamsForAuth($headerParams, $queryParams, $authSettings); + + # construct the http header if ($headerParams != null) { + # add default header + $headerParams = array_merge((array)self::$default_header, $headerParams); + foreach ($headerParams as $key => $val) { $headers[] = "$key: $val"; - if ($key == $this->headerName) { - $added_api_key = True; - } } } - if (! $added_api_key && $this->headerName != null) { - $headers[] = $this->headerName . ": " . $this->headerValue; - } // form data if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { @@ -111,6 +185,7 @@ class APIClient { } // return the result on success, rather than just TRUE curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); if (! empty($queryParams)) { @@ -130,7 +205,7 @@ class APIClient { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); } else if ($method != self::$GET) { - throw new Exception('Method ' . $method . ' is not recognized.'); + throw new APIClientException('Method ' . $method . ' is not recognized.'); } curl_setopt($curl, CURLOPT_URL, $url); @@ -261,7 +336,6 @@ class APIClient { * @param string $class class name is passed as a string * @return object an instance of $class */ - public static function deserialize($data, $class) { if (null === $data) { @@ -304,5 +378,37 @@ class APIClient { return $deserialized; } + /* + * return the header 'Accept' based on an array of Accept provided + * + * @param array[string] $accept Array of header + * @return string Accept (e.g. application/json) + */ + public static function selectHeaderAccept($accept) { + if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) { + return NULL; + } elseif (preg_grep("/application\/json/i", $accept)) { + return 'application/json'; + } else { + return implode(',', $accept); + } + } + + /* + * return the content type based on an array of content-type provided + * + * @param array[string] content_type_array Array fo content-type + * @return string Content-Type (e.g. application/json) + */ + public static function selectHeaderContentType($content_type) { + if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) { + return 'application/json'; + } elseif (preg_grep("/application\/json/i", $content_type)) { + return 'application/json'; + } else { + return implode(',', $content_type); + } + } + } diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 7759af5004d..98be8ff3a5c 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -42,7 +42,7 @@ class {{classname}} { {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set if (${{paramName}} === null) { - throw new \Exception("Missing the required parameter ${{paramName}} when calling {{nickname}}"); + throw new \InvalidArgumentException('Missing the required parameter ${{paramName}} when calling {{nickname}}'); } {{/required}}{{/allParams}} @@ -54,12 +54,11 @@ class {{classname}} { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = '{{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}})); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}}); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}})); {{#queryParams}}// query params if(${{paramName}} !== null) { @@ -92,18 +91,20 @@ class {{classname}} { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array({{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); {{#returnType}}if(! $response) { return null; } - $responseObject = $this->apiClient->deserialize($response, - '{{returnType}}'); - return $responseObject;{{/returnType}} + $responseObject = $this->apiClient->deserialize($response,'{{returnType}}'); + return $responseObject;{{/returnType}} } {{/operation}} {{newline}} diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache new file mode 100644 index 00000000000..9af553702ae --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -0,0 +1,36 @@ + 0 else 'application/json' - - {{#queryParams}} - if ('{{paramName}}' in params): - queryParams['{{baseName}}'] = self.apiClient.toPathValue(params['{{paramName}}']) - {{/queryParams}} - - {{#headerParams}} - if ('{{paramName}}' in params): - headerParams['{{baseName}}'] = params['{{paramName}}'] - {{/headerParams}} - - {{#pathParams}} - if ('{{paramName}}' in params): - replacement = str(self.apiClient.toPathValue(params['{{paramName}}'])) - replacement = urllib.quote(replacement) - resourcePath = resourcePath.replace('{' + '{{baseName}}' + '}', - replacement) - {{/pathParams}} - - {{#formParams}} - if ('{{paramName}}' in params): - {{#notFile}}formParams['{{baseName}}'] = params['{{paramName}}']{{/notFile}}{{#isFile}}files['{{baseName}}'] = params['{{paramName}}']{{/isFile}} - {{/formParams}} - - {{#bodyParam}} - if ('{{paramName}}' in params): - bodyParam = params['{{paramName}}'] - {{/bodyParam}} - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}) {{#returnType}} - if not response: - return None - - responseObject = self.apiClient.deserialize(response, '{{returnType}}') - return responseObject - {{/returnType}} - {{newline}} - {{newline}} - {{/operation}} -{{newline}} + return response + {{/returnType}}{{/operation}} {{/operations}} -{{newline}} + + + + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index e46c63df637..e9ede4cd221 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -20,33 +20,40 @@ Copyright 2015 Reverb Technologies, Inc. {{#model}} class {{classname}}(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ def __init__(self): """ - Attributes: - swaggerTypes (dict): The key is attribute name and the value is attribute type. - attributeMap (dict): The key is attribute name and the value is json key in definition. + Swagger model + + :param dict swaggerTypes: The key is attribute name and the value is attribute type. + :param dict attributeMap: The key is attribute name and the value is json key in definition. """ - self.swaggerTypes = { - {{#vars}} - '{{name}}': '{{{datatype}}}'{{#hasMore}}, - {{/hasMore}} - {{/vars}}{{newline}} + self.swagger_types = { + {{#vars}}'{{name}}': '{{{datatype}}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} } - self.attributeMap = { - {{#vars}} - '{{name}}': '{{baseName}}'{{#hasMore}},{{/hasMore}} - {{/vars}} + self.attribute_map = { + {{#vars}}'{{name}}': '{{baseName}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} } - {{#vars}} - {{#description}}#{{description}} - {{/description}} - self.{{name}} = None # {{{datatype}}} + {{#description}}# {{description}}{{/description}} + self.{{name}} = None # {{{datatype}}} {{/vars}} + + def __repr__(self): + properties = [] + for p in self.__dict__: + if p != 'swaggerTypes' and p != 'attributeMap': + properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) + + return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) {{/model}} {{/models}} + + diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache new file mode 100644 index 00000000000..06b817da757 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -0,0 +1,223 @@ +# coding: utf-8 +import sys +import io +import json + +# python 2 and python 3 compatibility library +from six import iteritems + +try: + import urllib3 +except ImportError: + raise ImportError('Swagger python client requires urllib3.') + +try: + # for python3 + from urllib.parse import urlencode +except ImportError: + # for python2 + from urllib import urlencode + + +class RESTResponse(io.IOBase): + + def __init__(self, resp): + self.urllib3_response = resp + self.status = resp.status + self.reason = resp.reason + self.data = resp.data + + def getheaders(self): + """ + Returns a dictionary of the response headers. + """ + return self.urllib3_response.getheaders() + + def getheader(self, name, default=None): + """ + Returns a given response header. + """ + return self.urllib3_response.getheader(name, default) + +class RESTClientObject(object): + + def __init__(self, pools_size=4): + self.pool_manager = urllib3.PoolManager( + num_pools=pools_size + ) + + def request(self, method, url, query_params=None, headers=None, + body=None, post_params=None): + """ + :param method: http request method + :param url: http request url + :param query_params: query parameters in the url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, `application/x-www-form-urlencode` + and `multipart/form-data` + :param raw_response: if return the raw response + """ + method = method.upper() + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH'] + + if post_params and body: + raise ValueError("body parameter cannot be used with post_params parameter.") + + post_params = post_params or {} + headers = headers or {} + + if 'Content-Type' not in headers: + headers['Content-Type'] = 'application/json' + + # For `POST`, `PUT`, `PATCH` + if method in ['POST', 'PUT', 'PATCH']: + if query_params: + url += '?' + urlencode(query_params) + if headers['Content-Type'] == 'application/json': + r = self.pool_manager.request(method, url, + body=json.dumps(body), + headers=headers) + if headers['Content-Type'] == 'application/x-www-form-urlencoded': + r = self.pool_manager.request(method, url, + fields=post_params, + encode_multipart=False, + headers=headers) + if headers['Content-Type'] == 'multipart/form-data': + # must del headers['Content-Type'], or the correct Content-Type + # which generated by urllib3 will be overwritten. + del headers['Content-Type'] + r = self.pool_manager.request(method, url, + fields=post_params, + encode_multipart=True, + headers=headers) + # For `GET`, `HEAD`, `DELETE` + else: + r = self.pool_manager.request(method, url, + fields=query_params, + headers=headers) + r = RESTResponse(r) + + if r.status not in range(200, 206): + raise ErrorResponse(r) + + return self.process_response(r) + + def process_response(self, response): + # In the python 3, the response.data is bytes. + # we need to decode it to string. + if sys.version_info > (3,): + data = response.data.decode('utf8') + else: + data = response.data + try: + resp = json.loads(data) + except ValueError: + resp = data + + return resp + + def GET(self, url, headers=None, query_params=None): + return self.request("GET", url, headers=headers, query_params=query_params) + + def HEAD(self, url, headers=None, query_params=None): + return self.request("HEAD", url, headers=headers, query_params=query_params) + + def DELETE(self, url, headers=None, query_params=None): + return self.request("DELETE", url, headers=headers, query_params=query_params) + + def POST(self, url, headers=None, post_params=None, body=None): + return self.request("POST", url, headers=headers, post_params=post_params, body=body) + + def PUT(self, url, headers=None, post_params=None, body=None): + return self.request("PUT", url, headers=headers, post_params=post_params, body=body) + + def PATCH(self, url, headers=None, post_params=None, body=None): + return self.request("PATCH", url, headers=headers, post_params=post_params, body=body) + + +class ErrorResponse(Exception): + """ + Non-2xx HTTP response + """ + + def __init__(self, http_resp): + self.status = http_resp.status + self.reason = http_resp.reason + self.body = http_resp.data + self.headers = http_resp.getheaders() + + # In the python 3, the self.body is bytes. + # we need to decode it to string. + if sys.version_info > (3,): + data = self.body.decode('utf8') + else: + data = self.body + + try: + self.body = json.loads(data) + except ValueError: + self.body = data + + def __str__(self): + """ + Custom error response messages + """ + return "({0})\nReason: {1}\nHeader: {2}\nBody: {3}\n".\ + format(self.status, self.reason, self.headers, self.body) + +class RESTClient(object): + """ + A class with all class methods to perform JSON requests. + """ + + IMPL = RESTClientObject() + + @classmethod + def request(cls, *n, **kw): + """ + Perform a REST request and parse the response. + """ + return cls.IMPL.request(*n, **kw) + + @classmethod + def GET(cls, *n, **kw): + """ + Perform a GET request using `RESTClient.request()`. + """ + return cls.IMPL.GET(*n, **kw) + + @classmethod + def HEAD(cls, *n, **kw): + """ + Perform a HEAD request using `RESTClient.request()`. + """ + return cls.IMPL.GET(*n, **kw) + + @classmethod + def POST(cls, *n, **kw): + """ + Perform a POST request using `RESTClient.request()` + """ + return cls.IMPL.POST(*n, **kw) + + @classmethod + def PUT(cls, *n, **kw): + """ + Perform a PUT request using `RESTClient.request()` + """ + return cls.IMPL.PUT(*n, **kw) + + @classmethod + def PATCH(cls, *n, **kw): + """ + Perform a PATCH request using `RESTClient.request()` + """ + return cls.IMPL.PATCH(*n, **kw) + + @classmethod + def DELETE(cls, *n, **kw): + """ + Perform a DELETE request using `RESTClient.request()` + """ + return cls.IMPL.DELETE(*n, **kw) diff --git a/modules/swagger-codegen/src/main/resources/python/setup.mustache b/modules/swagger-codegen/src/main/resources/python/setup.mustache index d10da4c68d0..a049057c920 100644 --- a/modules/swagger-codegen/src/main/resources/python/setup.mustache +++ b/modules/swagger-codegen/src/main/resources/python/setup.mustache @@ -12,7 +12,7 @@ from setuptools import setup, find_packages # Try reading the setuptools documentation: # http://pypi.python.org/pypi/setuptools -REQUIRES = [] +REQUIRES = ["urllib3 >= 1.10", "six >= 1.9"] setup( name="{{module}}", @@ -30,3 +30,11 @@ setup( ) {{/hasMore}}{{/apis}}{{/apiInfo}} + + + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/python/swagger.mustache b/modules/swagger-codegen/src/main/resources/python/swagger.mustache index 10ac54d527d..549106014e3 100644 --- a/modules/swagger-codegen/src/main/resources/python/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/python/swagger.mustache @@ -6,118 +6,109 @@ server communication, and is invariant across implementations. Specifics of the methods and models for each application are generated from the Swagger templates.""" -import sys +from __future__ import absolute_import +from . import models +from .rest import RESTClient + import os import re import urllib -import urllib2 -import httplib import json import datetime import mimetypes import random -import string -import models + +# python 2 and python 3 compatibility library +from six import iteritems + +try: + # for python3 + from urllib.parse import quote +except ImportError: + # for python2 + from urllib import quote class ApiClient(object): - """Generic API client for Swagger client library builds - - Attributes: - host: The base path for the server to call - headerName: a header to pass when making calls to the API - headerValue: a header value to pass when making calls to the API """ - def __init__(self, host=None, headerName=None, headerValue=None): - self.defaultHeaders = {} - if (headerName is not None): - self.defaultHeaders[headerName] = headerValue + Generic API client for Swagger client library builds + + :param host: The base path for the server to call + :param header_name: a header to pass when making calls to the API + :param header_value: a header value to pass when making calls to the API + """ + def __init__(self, host=None, header_name=None, header_value=None): + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value self.host = host self.cookie = None - self.boundary = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(30)) # Set default User-Agent. self.user_agent = 'Python-Swagger' @property def user_agent(self): - return self.defaultHeaders['User-Agent'] + return self.default_headers['User-Agent'] @user_agent.setter def user_agent(self, value): - self.defaultHeaders['User-Agent'] = value + self.default_headers['User-Agent'] = value - def setDefaultHeader(self, headerName, headerValue): - self.defaultHeaders[headerName] = headerValue + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value - def callAPI(self, resourcePath, method, queryParams, postData, - headerParams=None, files=None): - - url = self.host + resourcePath - - mergedHeaderParams = self.defaultHeaders.copy() - mergedHeaderParams.update(headerParams) - headers = {} - if mergedHeaderParams: - for param, value in mergedHeaderParams.iteritems(): - headers[param] = ApiClient.sanitizeForSerialization(value) + def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, + body=None, post_params=None, files=None, response=None): + # headers parameters + headers = self.default_headers.copy() + headers.update(header_params) if self.cookie: - headers['Cookie'] = ApiClient.sanitizeForSerialization(self.cookie) + headers['Cookie'] = self.cookie + if headers: + headers = ApiClient.sanitize_for_serialization(headers) - data = None + # path parameters + if path_params: + path_params = ApiClient.sanitize_for_serialization(path_params) + for k, v in iteritems(path_params): + replacement = quote(str(self.to_path_value(v))) + resource_path = resource_path.replace('{' + k + '}', replacement) - if queryParams: - # Need to remove None values, these should not be sent - sentQueryParams = {} - for param, value in queryParams.items(): - if value is not None: - sentQueryParams[param] = ApiClient.sanitizeForSerialization(value) - url = url + '?' + urllib.urlencode(sentQueryParams) + # query parameters + if query_params: + query_params = ApiClient.sanitize_for_serialization(query_params) + query_params = {k: self.to_path_value(v) for k, v in iteritems(query_params)} - if method in ['GET']: - #Options to add statements later on and for compatibility - pass + # post parameters + if post_params: + post_params = self.prepare_post_parameters(post_params, files) + post_params = ApiClient.sanitize_for_serialization(post_params) - elif method in ['POST', 'PUT', 'DELETE']: - if postData: - postData = ApiClient.sanitizeForSerialization(postData) - if 'Content-Type' not in headers: - headers['Content-Type'] = 'application/json' - data = json.dumps(postData) - elif headers['Content-Type'] == 'application/json': - data = json.dumps(postData) - elif headers['Content-Type'] == 'multipart/form-data': - data = self.buildMultipartFormData(postData, files) - headers['Content-Type'] = 'multipart/form-data; boundary={0}'.format(self.boundary) - headers['Content-length'] = str(len(data)) - else: - data = urllib.urlencode(postData) + # body + if body: + body = ApiClient.sanitize_for_serialization(body) + # request url + url = self.host + resource_path + + # perform request and return response + response_data = self.request(method, url, query_params=query_params, headers=headers, + post_params=post_params, body=body) + + # deserialize response data + if response: + return self.deserialize(response_data, response) else: - raise Exception('Method ' + method + ' is not recognized.') + return None - request = MethodRequest(method=method, url=url, headers=headers, - data=data) + def to_path_value(self, obj): + """ + Convert a string or object to a path-friendly value + + :param obj: object or string value - # Make the request - response = urllib2.urlopen(request) - if 'Set-Cookie' in response.headers: - self.cookie = response.headers['Set-Cookie'] - string = response.read() - - try: - data = json.loads(string) - except ValueError: # PUT requests don't return anything - data = None - - return data - - def toPathValue(self, obj): - """Convert a string or object to a path-friendly value - Args: - obj -- object or string value - Returns: - string -- quoted value + :return string: quoted value """ if type(obj) == list: return ','.join(obj) @@ -125,12 +116,12 @@ class ApiClient(object): return str(obj) @staticmethod - def sanitizeForSerialization(obj): + def sanitize_for_serialization(obj): """ Sanitize an object for Request. If obj is None, return None. - If obj is str, int, long, float, bool, return directly. + If obj is str, int, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. If obj is list, santize each element in the list. If obj is dict, return the dict. @@ -138,113 +129,80 @@ class ApiClient(object): """ if isinstance(obj, type(None)): return None - elif isinstance(obj, (str, int, long, float, bool, file)): + elif isinstance(obj, (str, int, float, bool, tuple)): return obj elif isinstance(obj, list): - return [ApiClient.sanitizeForSerialization(subObj) for subObj in obj] + return [ApiClient.sanitize_for_serialization(sub_obj) for sub_obj in obj] elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() else: if isinstance(obj, dict): - objDict = obj + obj_dict = obj else: - # Convert model obj to dict except attributes `swaggerTypes`, `attributeMap` + # Convert model obj to dict except attributes `swagger_types`, `attribute_map` # and attributes which value is not None. # Convert attribute name to json key in model definition for request. - objDict = {obj.attributeMap[key]: val - for key, val in obj.__dict__.iteritems() - if key != 'swaggerTypes' and key != 'attributeMap' and val is not None} - return {key: ApiClient.sanitizeForSerialization(val) - for (key, val) in objDict.iteritems()} + obj_dict = {obj.attribute_map[key]: val + for key, val in iteritems(obj.__dict__) + if key != 'swagger_types' and key != 'attribute_map' and val is not None} + return {key: ApiClient.sanitize_for_serialization(val) + for key, val in iteritems(obj_dict)} - def buildMultipartFormData(self, postData, files): - def escape_quotes(s): - return s.replace('"', '\\"') + def deserialize(self, obj, obj_class): + """ + Derialize a JSON string into an object. - lines = [] + :param obj: string or object to be deserialized + :param obj_class: class literal for deserialzied object, or string of class name - for name, value in postData.items(): - lines.extend(( - '--{0}'.format(self.boundary), - 'Content-Disposition: form-data; name="{0}"'.format(escape_quotes(name)), - '', - str(value), - )) - - for name, filepath in files.items(): - f = open(filepath, 'r') - filename = filepath.split('/')[-1] - mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' - lines.extend(( - '--{0}'.format(self.boundary), - 'Content-Disposition: form-data; name="{0}"; filename="{1}"'.format(escape_quotes(name), escape_quotes(filename)), - 'Content-Type: {0}'.format(mimetype), - '', - f.read() - )) - - lines.extend(( - '--{0}--'.format(self.boundary), - '' - )) - return '\r\n'.join(lines) - - def deserialize(self, obj, objClass): - """Derialize a JSON string into an object. - - Args: - obj -- string or object to be deserialized - objClass -- class literal for deserialzied object, or string - of class name - Returns: - object -- deserialized object""" - - # Have to accept objClass as string or actual type. Type could be a + :return object: deserialized object + """ + # Have to accept obj_class as string or actual type. Type could be a # native Python type, or one of the model classes. - if type(objClass) == str: - if 'list[' in objClass: - match = re.match('list\[(.*)\]', objClass) - subClass = match.group(1) - return [self.deserialize(subObj, subClass) for subObj in obj] + if type(obj_class) == str: + if 'list[' in obj_class: + match = re.match('list\[(.*)\]', obj_class) + sub_class = match.group(1) + return [self.deserialize(sub_obj, sub_class) for sub_obj in obj] - if (objClass in ['int', 'float', 'long', 'dict', 'list', 'str', 'bool', 'datetime']): - objClass = eval(objClass) + if obj_class in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime']: + obj_class = eval(obj_class) else: # not a native type, must be model class - objClass = eval('models.' + objClass) + obj_class = eval('models.' + obj_class) - if objClass in [int, long, float, dict, list, str, bool]: - return objClass(obj) - elif objClass == datetime: + if obj_class in [int, float, dict, list, str, bool]: + return obj_class(obj) + elif obj_class == datetime: return self.__parse_string_to_datetime(obj) - instance = objClass() + instance = obj_class() - for attr, attrType in instance.swaggerTypes.iteritems(): - if obj is not None and instance.attributeMap[attr] in obj and type(obj) in [list, dict]: - value = obj[instance.attributeMap[attr]] - if attrType in ['str', 'int', 'long', 'float', 'bool']: - attrType = eval(attrType) + for attr, attr_type in iteritems(instance.swagger_types): + if obj is not None and instance.attribute_map[attr] in obj and type(obj) in [list, dict]: + value = obj[instance.attribute_map[attr]] + if attr_type in ['str', 'int', 'float', 'bool']: + attr_type = eval(attr_type) try: - value = attrType(value) + value = attr_type(value) except UnicodeEncodeError: value = unicode(value) except TypeError: value = value setattr(instance, attr, value) - elif (attrType == 'datetime'): + elif attr_type == 'datetime': setattr(instance, attr, self.__parse_string_to_datetime(value)) - elif 'list[' in attrType: - match = re.match('list\[(.*)\]', attrType) - subClass = match.group(1) - subValues = [] + elif 'list[' in attr_type: + match = re.match('list\[(.*)\]', attr_type) + sub_class = match.group(1) + sub_values = [] if not value: setattr(instance, attr, None) else: - for subValue in value: - subValues.append(self.deserialize(subValue, subClass)) - setattr(instance, attr, subValues) + for sub_value in value: + sub_values.append(self.deserialize(sub_value, sub_class)) + setattr(instance, attr, sub_values) else: - setattr(instance, attr, self.deserialize(value, attrType)) + setattr(instance, attr, self.deserialize(value, attr_type)) return instance @@ -260,16 +218,42 @@ class ApiClient(object): except ImportError: return string -class MethodRequest(urllib2.Request): - def __init__(self, *args, **kwargs): - """Construct a MethodRequest. Usage is the same as for - `urllib2.Request` except it also takes an optional `method` - keyword argument. If supplied, `method` will be used instead of - the default.""" + def request(self, method, url, query_params=None, headers=None, post_params=None, body=None): + """ + Perform http request using RESTClient. + """ + if method == "GET": + return RESTClient.GET(url, query_params=query_params, headers=headers) + elif method == "HEAD": + return RESTClient.HEAD(url, query_params=query_params, headers=headers) + elif method == "POST": + return RESTClient.POST(url, headers=headers, post_params=post_params, body=body) + elif method == "PUT": + return RESTClient.PUT(url, headers=headers, post_params=post_params, body=body) + elif method == "PATCH": + return RESTClient.PATCH(url, headers=headers, post_params=post_params, body=body) + elif method == "DELETE": + return RESTClient.DELETE(url, query_params=query_params, headers=headers) + else: + raise ValueError("http method must be `GET`, `HEAD`, `POST`, `PATCH`, `PUT` or `DELETE`") + + def prepare_post_parameters(self, post_params=None, files=None): + params = {} + + if post_params: + params.update(post_params) + + if files: + for k, v in iteritems(files): + with open(v, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' + params[k] = tuple([filename, filedata, mimetype]) + + return params + + + - if 'method' in kwargs: - self.method = kwargs.pop('method') - return urllib2.Request.__init__(self, *args, **kwargs) - def get_method(self): - return getattr(self, 'method', urllib2.Request.get_method(self)) diff --git a/modules/swagger-codegen/src/main/resources/python/util.mustache b/modules/swagger-codegen/src/main/resources/python/util.mustache new file mode 100644 index 00000000000..1137a5d2d23 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/python/util.mustache @@ -0,0 +1,17 @@ +from six import iteritems + +def remove_none(obj): + if isinstance(obj, (list, tuple, set)): + return type(obj)(remove_none(x) for x in obj if x is not None) + elif isinstance(obj, dict): + return type(obj)((remove_none(k), remove_none(v)) + for k, v in iteritems(obj) if k is not None and v is not None) + else: + return obj + + +def inspect_vars(obj): + if not hasattr(obj, '__dict__'): + return obj + else: + return {k: inspect_vars(getattr(obj, k)) for k in dir(obj)} diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 038a40f66ea..ba38a8157b5 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -1,57 +1,59 @@ require "uri" +module {{moduleName}} {{#operations}} -class {{classname}} - basePath = "{{basePath}}" - # apiInvoker = APIInvoker + class {{classname}} + basePath = "{{basePath}}" + # apiInvoker = APIInvoker {{#operation}} {{newline}} - # {{summary}} - # {{notes}} -{{#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}} - def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) - {{#allParams}}{{#required}} - # verify the required parameter '{{paramName}}' is set - raise "Missing the required parameter '{{paramName}}' when calling {{nickname}}" if {{{paramName}}}.nil? - {{/required}}{{/allParams}} + # {{summary}} + # {{notes}} +{{#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}} + def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) + {{#allParams}}{{#required}} + # verify the required parameter '{{paramName}}' is set + raise "Missing the required parameter '{{paramName}}' when calling {{nickname}}" if {{{paramName}}}.nil? + {{/required}}{{/allParams}} - # resource path - path = "{{path}}".sub('{format}','json'){{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}} + # resource path + path = "{{path}}".sub('{format}','json'){{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}} - # query parameters - query_params = {}{{#queryParams}}{{#required}} - query_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/queryParams}}{{#queryParams}}{{^required}} - query_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/queryParams}} + # query parameters + query_params = {}{{#queryParams}}{{#required}} + query_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/queryParams}}{{#queryParams}}{{^required}} + query_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/queryParams}} - # header parameters - header_params = {} + # header parameters + header_params = {} - # HTTP header 'Accept' (if needed) - _header_accept = [{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Accept' (if needed) + _header_accept = [{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - # HTTP header 'Content-Type' - _header_content_type = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type){{#headerParams}}{{#required}} - header_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}} - header_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}} + # HTTP header 'Content-Type' + _header_content_type = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type){{#headerParams}}{{#required}} + header_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}} + header_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}} - # form parameters - form_params = {}{{#formParams}}{{#required}} - form_params["{{baseName}}"] = {{paramName}}{{/required}}{{/formParams}}{{#formParams}}{{^required}} - form_params["{{baseName}}"] = opts[:'{{paramName}}'] if opts[:'{{paramName}}']{{/required}}{{/formParams}} + # form parameters + form_params = {}{{#formParams}}{{#required}} + form_params["{{baseName}}"] = {{paramName}}{{/required}}{{/formParams}}{{#formParams}}{{^required}} + form_params["{{baseName}}"] = opts[:'{{paramName}}'] if opts[:'{{paramName}}']{{/required}}{{/formParams}} - # http body (model) - {{^bodyParam}}post_body = nil - {{/bodyParam}}{{#bodyParam}}post_body = Swagger::Request.object_to_http_body({{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}) - {{/bodyParam}} + # http body (model) + {{^bodyParam}}post_body = nil + {{/bodyParam}}{{#bodyParam}}post_body = Swagger::Request.object_to_http_body({{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}) + {{/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}} + {{#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 {{/operation}} -end + end {{/operations}} +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache index ecad551c77b..c0e563a0bb7 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache @@ -1,83 +1,83 @@ -# base class containing fundamental method such as to_hash, build_from_hash and more -class BaseObject +module {{moduleName}} + # base class containing fundamental method such as to_hash, build_from_hash and more + class BaseObject - # return the object in the form of hash - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? + # return the object in the form of hash + def to_body + body = {} + self.class.attribute_map.each_pair do |key, value| + body[value] = self.send(key) unless self.send(key).nil? + end + body end - body - end - # build the object from hash - def build_from_hash(attributes) - return nil unless attributes.is_a?(Hash) - self.class.swagger_types.each_pair do |key, type| - if type =~ /^array\[(.*)\]/i - if attributes[self.class.attribute_map[key]].is_a?(Array) - self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + # build the object from hash + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /^array\[(.*)\]/i + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + else + #TODO show warning in debug mode + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) else - #TODO show warning in debug mode - end - elsif !attributes[self.class.attribute_map[key]].nil? - self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) - else - # data not found in attributes(hash), not an issue as the data can be optional - end - end - - self - end - - def _deserialize(type, value) - case type.to_sym - when :DateTime - DateTime.parse(value) - when :string - value.to_s - when :int - value.to_i - when :double - value.to_f - when :boolean - if value =~ /^(true|t|yes|y|1)$/i - true - else - false - end - else # model - _model = Object.const_get(type).new - _model.build_from_hash(value) - end - end - - - - # to_body is an alias to to_body (backward compatibility) - def to_hash - hash = {} - self.class.attribute_map.each_pair do |key, value| - if self.send(key).is_a?(Array) - next if self.send(key).empty? - hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil? - else - unless (_tmp_value = _to_hash self.send(key)).nil? - hash[value] = _tmp_value + # data not found in attributes(hash), not an issue as the data can be optional end end - end - hash - end - # Method to output non-array value in the form of hash - # For object, use to_hash. Otherwise, just return the value - def _to_hash(value) - if value.respond_to? :to_hash - value.to_hash - else - value + self end - end + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :string + value.to_s + when :int + value.to_i + when :double + value.to_f + when :boolean + if value =~ /^(true|t|yes|y|1)$/i + true + else + false + end + else # model + _model = {{moduleName}}.const_get(type).new + _model.build_from_hash(value) + end + end + + # to_body is an alias to to_body (backward compatibility) + def to_hash + hash = {} + self.class.attribute_map.each_pair do |key, value| + if self.send(key).is_a?(Array) + next if self.send(key).empty? + hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil? + else + unless (_tmp_value = _to_hash self.send(key)).nil? + hash[value] = _tmp_value + end + end + end + hash + end + + # Method to output non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + def _to_hash(value) + if value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/model.mustache b/modules/swagger-codegen/src/main/resources/ruby/model.mustache index 362664aa2b7..d0d4e787756 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/model.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/model.mustache @@ -1,41 +1,40 @@ -require_relative 'base_object' - -{{#models}}#{{description}} -{{#model}}class {{classname}} < BaseObject - attr_accessor {{#vars}}:{{{name}}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{newline}} - # attribute mapping from ruby-style variable name to JSON key - def self.attribute_map - { - {{#vars}} - # {{description}} - :'{{{name}}}' => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}} - {{/vars}} - } - end - - # attribute type - def self.swagger_types - { - {{#vars}}:'{{{name}}}' => :'{{{datatype}}}'{{#hasMore}},{{/hasMore}} - {{/vars}} - } - end - - def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? - - # convert string to symbol for hash key - attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} - - {{#vars}} - if attributes[:'{{{baseName}}}'] - {{#isContainer}}if (value = attributes[:'{{{baseName}}}']).is_a?(Array) - @{{{name}}} = value - end{{/isContainer}}{{^isContainer}}@{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}} +module {{moduleName}} +{{#models}} # {{description}} +{{#model}} class {{classname}} < BaseObject + attr_accessor {{#vars}}:{{{name}}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{newline}} + # attribute mapping from ruby-style variable name to JSON key + def self.attribute_map + { + {{#vars}} + # {{description}} + :'{{{name}}}' => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}} + {{/vars}} + } end - {{/vars}} - end -end + # attribute type + def self.swagger_types + { + {{#vars}}:'{{{name}}}' => :'{{{datatype}}}'{{#hasMore}},{{/hasMore}} + {{/vars}} + } + end + + def initialize(attributes = {}) + return if !attributes.is_a?(Hash) || attributes.empty? + + # convert string to symbol for hash key + attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + + {{#vars}} + if attributes[:'{{{baseName}}}'] + {{#isContainer}}if (value = attributes[:'{{{baseName}}}']).is_a?(Array) + @{{{name}}} = value + end{{/isContainer}}{{^isContainer}}@{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}} + end + {{/vars}} + end + end {{/model}} {{/models}} +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.gemspec.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger-client.gemspec.mustache deleted file mode 100644 index c002e581b8b..00000000000 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.gemspec.mustache +++ /dev/null @@ -1,33 +0,0 @@ -# -*- encoding: utf-8 -*- -$:.push File.expand_path("../lib", __FILE__) -require "swagger/version" - -Gem::Specification.new do |s| - s.name = "{{artifactId}}" - s.version = Swagger::VERSION - s.platform = Gem::Platform::RUBY - s.authors = ["Zeke Sikelianos", "Tony Tam"] - s.email = ["zeke@wordnik.com", "tony@wordnik.com"] - s.homepage = "http://developer.wordnik.com" - s.summary = %q{A ruby wrapper for the swagger APIs} - s.description = %q{This gem maps to a swagger API} - - s.rubyforge_project = "{{artifactId}}" - - s.add_dependency 'typhoeus', '>=0.2.1' - s.add_dependency 'addressable', '>=2.2.4' - s.add_dependency 'json', '>=1.4.6' - - s.add_development_dependency 'rspec', '>=2.5.0' - s.add_development_dependency 'vcr', '>=1.5.1' - s.add_development_dependency 'webmock', '>=1.6.2' - s.add_development_dependency 'autotest' - s.add_development_dependency 'autotest-rails-pure' - s.add_development_dependency 'autotest-growl' - s.add_development_dependency 'autotest-fsevent' - - s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? } - s.test_files = `find spec/*`.split("\n") - s.executables = [] - s.require_paths = ["lib"] -end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache deleted file mode 100644 index b13f83b1dbc..00000000000 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache +++ /dev/null @@ -1,5 +0,0 @@ -require 'monkey' -require 'swagger' - -Dir[File.join(File.dirname(__FILE__), "../lib/*.rb")].each {|file| require file if file !~ /swagger-client\.rb\z/ } -Dir[File.join(File.dirname(__FILE__), "../models/*.rb")].each {|file| require file } diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache index f393330b148..750e6ac5155 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache @@ -1,86 +1,78 @@ -require 'monkey' -require 'swagger/configuration' -require 'swagger/request' -require 'swagger/response' -require 'swagger/version' require 'logger' require 'json' -module Swagger - - @configuration = Configuration.new +module {{moduleName}} + module Swagger + class << self + attr_accessor :logger - class << self - attr_accessor :logger - - # A Swagger configuration object. Must act like a hash and return sensible - # values for all Swagger configuration options. See Swagger::Configuration. - attr_accessor :configuration + # A Swagger configuration object. Must act like a hash and return sensible + # values for all Swagger configuration options. See Swagger::Configuration. + attr_accessor :configuration - attr_accessor :resources - - # Call this method to modify defaults in your initializers. - # - # @example - # Swagger.configure do |config| - # config.api_key = '1234567890abcdef' # required - # config.username = 'wordlover' # optional, but needed for user-related functions - # config.password = 'i<3words' # optional, but needed for user-related functions - # config.format = 'json' # optional, defaults to 'json' - # end - # - def configure - yield(configuration) if block_given? + attr_accessor :resources - # Configure logger. Default to use Rails - self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT)) + # Call this method to modify defaults in your initializers. + # + # @example + # Swagger.configure do |config| + # config.api_key = '1234567890abcdef' # required + # config.username = 'wordlover' # optional, but needed for user-related functions + # config.password = 'i<3words' # optional, but needed for user-related functions + # config.format = 'json' # optional, defaults to 'json' + # end + # + def configure + yield(configuration) if block_given? - # remove :// from scheme - configuration.scheme.sub!(/:\/\//, '') + # Configure logger. Default to use Rails + self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT)) - # remove http(s):// and anything after a slash - configuration.host.sub!(/https?:\/\//, '') - configuration.host = configuration.host.split('/').first + # remove :// from scheme + configuration.scheme.sub!(/:\/\//, '') - # Add leading and trailing slashes to base_path - configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') - configuration.base_path = "" if configuration.base_path == "/" - end - - def authenticated? - Swagger.configuration.auth_token.present? - end - - def de_authenticate - Swagger.configuration.auth_token = nil - end - - def authenticate - return if Swagger.authenticated? - - if Swagger.configuration.username.blank? || Swagger.configuration.password.blank? - raise ClientError, "Username and password are required to authenticate." + # remove http(s):// and anything after a slash + configuration.host.sub!(/https?:\/\//, '') + configuration.host = configuration.host.split('/').first + + # Add leading and trailing slashes to base_path + configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') + configuration.base_path = "" if configuration.base_path == "/" + end + + def authenticated? + Swagger.configuration.auth_token.present? + end + + def de_authenticate + Swagger.configuration.auth_token = nil + end + + def authenticate + return if Swagger.authenticated? + + if Swagger.configuration.username.blank? || Swagger.configuration.password.blank? + raise ClientError, "Username and password are required to authenticate." + end + + request = Swagger::Request.new( + :get, + "account/authenticate/{username}", + :params => { + :username => Swagger.configuration.username, + :password => Swagger.configuration.password + } + ) + + response_body = request.response.body + Swagger.configuration.auth_token = response_body['token'] end - - request = Swagger::Request.new( - :get, - "account/authenticate/{username}", - :params => { - :username => Swagger.configuration.username, - :password => Swagger.configuration.password - } - ) - - response_body = request.response.body - Swagger.configuration.auth_token = response_body['token'] end - end - -end -class ServerError < StandardError -end + class ServerError < StandardError + end -class ClientError < StandardError + class ClientError < StandardError + end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache index d27109aa445..e780a9c8e7d 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache @@ -1,22 +1,19 @@ -module Swagger - - class Configuration - require 'swagger/version' +module {{moduleName}} + module Swagger + class Configuration + attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent - attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent - - # Defaults go in here.. - def initialize - @format = 'json' - @scheme = '{{scheme}}' - @host = '{{host}}' - @base_path = '{{contextPath}}' - @user_agent = "ruby-swagger-#{Swagger::VERSION}" - @inject_format = false - @force_ending_format = false - @camelize_params = true + # Defaults go in here.. + def initialize + @format = 'json' + @scheme = '{{scheme}}' + @host = '{{host}}' + @base_path = '{{contextPath}}' + @user_agent = "ruby-swagger-#{Swagger::VERSION}" + @inject_format = false + @force_ending_format = false + @camelize_params = true + end end - end - end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache index 4ec071b93d5..14718bb6b3c 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache @@ -1,263 +1,257 @@ -module Swagger +module {{moduleName}} + module Swagger + class Request + require 'uri' + require 'addressable/uri' + require 'typhoeus' - class Request - require 'uri' - require 'addressable/uri' - require 'typhoeus' - require "swagger/version" + attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params - attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params + # All requests must have an HTTP method and a path + # Optionals parameters are :params, :headers, :body, :format, :host + def initialize(http_method, path, attributes={}) + attributes[:format] ||= Swagger.configuration.format + attributes[:params] ||= {} + # Set default headers + default_headers = { + 'Content-Type' => "application/#{attributes[:format].downcase}", + :api_key => Swagger.configuration.api_key, + 'User-Agent' => Swagger.configuration.user_agent + } - # All requests must have an HTTP method and a path - # Optionals parameters are :params, :headers, :body, :format, :host - # - def initialize(http_method, path, attributes={}) - attributes[:format] ||= Swagger.configuration.format - attributes[:params] ||= {} + # api_key from headers hash trumps the default, even if its value is blank + if attributes[:headers].present? && attributes[:headers].has_key?(:api_key) + default_headers.delete(:api_key) + end - # Set default headers - default_headers = { - 'Content-Type' => "application/#{attributes[:format].downcase}", - :api_key => Swagger.configuration.api_key, - 'User-Agent' => Swagger.configuration.user_agent - } + # api_key from params hash trumps all others (headers and default_headers) + if attributes[:params].present? && attributes[:params].has_key?(:api_key) + default_headers.delete(:api_key) + attributes[:headers].delete(:api_key) if attributes[:headers].present? + end - # api_key from headers hash trumps the default, even if its value is blank - if attributes[:headers].present? && attributes[:headers].has_key?(:api_key) - default_headers.delete(:api_key) - end - - # api_key from params hash trumps all others (headers and default_headers) - if attributes[:params].present? && attributes[:params].has_key?(:api_key) - default_headers.delete(:api_key) - attributes[:headers].delete(:api_key) if attributes[:headers].present? - end - - # Merge argument headers into defaults - attributes[:headers] = default_headers.merge(attributes[:headers] || {}) - - # Stick in the auth token if there is one - if Swagger.authenticated? - attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) - end - - self.http_method = http_method.to_sym - self.path = path - attributes.each do |name, value| - send("#{name.to_s.underscore.to_sym}=", value) - end - end + # Merge argument headers into defaults + attributes[:headers] = default_headers.merge(attributes[:headers] || {}) - # Construct a base URL - # - def url(options = {}) - u = Addressable::URI.new( - :scheme => Swagger.configuration.scheme, - :host => Swagger.configuration.host, - :path => self.interpreted_path, - :query => self.query_string.sub(/\?/, '') - ).to_s - - # Drop trailing question mark, if present - u.sub! /\?$/, '' - - # Obfuscate API key? - u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated] - - u - end + # Stick in the auth token if there is one + if Swagger.authenticated? + attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) + end - # Iterate over the params hash, injecting any path values into the path string - # - # e.g. /word.{format}/{word}/entries => /word.json/cat/entries - def interpreted_path - p = self.path.dup - - # Stick a .{format} placeholder into the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words.{format}/blah - if Swagger.configuration.inject_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = p.sub(/^(\/?\w+)/, "\\1.#{format}") + self.http_method = http_method.to_sym + self.path = path + attributes.each do |name, value| + send("#{name.to_s.underscore.to_sym}=", value) end end - # Stick a .{format} placeholder on the end of the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words/blah.{format} - if Swagger.configuration.force_ending_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = "#{p}.#{format}" + # Construct a base URL + def url(options = {}) + u = Addressable::URI.new( + :scheme => Swagger.configuration.scheme, + :host => Swagger.configuration.host, + :path => self.interpreted_path, + :query => self.query_string.sub(/\?/, '') + ).to_s + + # Drop trailing question mark, if present + u.sub! /\?$/, '' + + # Obfuscate API key? + u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated] + + u + end + + # Iterate over the params hash, injecting any path values into the path string + # e.g. /word.{format}/{word}/entries => /word.json/cat/entries + def interpreted_path + p = self.path.dup + + # Stick a .{format} placeholder into the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words.{format}/blah + if Swagger.configuration.inject_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = p.sub(/^(\/?\w+)/, "\\1.#{format}") + end + end + + # Stick a .{format} placeholder on the end of the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words/blah.{format} + if Swagger.configuration.force_ending_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = "#{p}.#{format}" + end + end + + p = p.sub("{format}", self.format.to_s) + + URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') + end + + # Massage the request body into a state of readiness + # If body is a hash, camelize all keys then convert to a json string + def body=(value) + if value.is_a?(Hash) + value = value.inject({}) do |memo, (k,v)| + memo[k.to_s.camelize(:lower).to_sym] = v + memo + end + end + @body = value + end + + # If body is an object, JSONify it before making the actual request. + # For form parameters, remove empty value + def outgoing_body + # http form + if @body.nil? && @form_params && !@form_params.empty? + data = form_params.dup + data.each do |key, value| + data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter + end + data + else # http body is JSON + @body.is_a?(String) ? @body : @body.to_json end end - p = p.sub("{format}", self.format.to_s) - - URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') - end - - # Massage the request body into a state of readiness - # If body is a hash, camelize all keys then convert to a json string - # - def body=(value) - if value.is_a?(Hash) - value = value.inject({}) do |memo, (k,v)| - memo[k.to_s.camelize(:lower).to_sym] = v - memo + # Construct a query string from the query-string-type params + def query_string + # Iterate over all params, + # .. removing the ones that are part of the path itself. + # .. stringifying values so Addressable doesn't blow up. + query_values = {} + self.params.each_pair do |key, value| + next if self.path.include? "{#{key}}" # skip path params + next if value.blank? && value.class != FalseClass # skip empties + if Swagger.configuration.camelize_params + key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param + end + query_values[key] = value.to_s + end + + # We don't want to end up with '?' as our query string + # if there aren't really any params + return "" if query_values.blank? + + # Addressable requires query_values to be set after initialization.. + qs = Addressable::URI.new + qs.query_values = query_values + qs.to_s + end + + def make + #TODO use configuration setting to determine if debugging + #logger = Logger.new STDOUT + #logger.debug self.url + response = case self.http_method.to_sym + when :get,:GET + Typhoeus::Request.get( + self.url, + :headers => self.headers.stringify_keys, + ) + + when :post,:POST + Typhoeus::Request.post( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :patch,:PATCH + Typhoeus::Request.patch( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :put,:PUT + Typhoeus::Request.put( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :delete,:DELETE + Typhoeus::Request.delete( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + end + Response.new(response) + end + + def response + self.make + end + + def response_code_pretty + return unless @response.present? + @response.code.to_s + end + + def response_headers_pretty + return unless @response.present? + # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient + @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus + end + + # return 'Accept' based on an array of accept provided + # @param [Array] header_accept_array Array fo 'Accept' + # @return String Accept (e.g. application/json) + def self.select_header_accept header_accept_array + if header_accept_array.empty? + return + elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # look for json data by default + else + header_accept_array.join(',') end end - @body = value - end - - # If body is an object, JSONify it before making the actual request. - # For form parameters, remove empty value - def outgoing_body - # http form - if @body.nil? && @form_params && !@form_params.empty? - data = form_params.dup - data.each do |key, value| - data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter + + # return the content type based on an array of content-type provided + # @param [Array] content_type_array Array fo content-type + # @return String Content-Type (e.g. application/json) + def self.select_header_content_type content_type_array + if content_type_array.empty? + 'application/json' # use application/json by default + elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # use application/json if it's included + else + content_type_array[0]; # otherwise, use the first one end - data - else # http body is JSON - @body.is_a?(String) ? @body : @body.to_json end - end - - # Construct a query string from the query-string-type params - def query_string - # Iterate over all params, - # .. removing the ones that are part of the path itself. - # .. stringifying values so Addressable doesn't blow up. - query_values = {} - self.params.each_pair do |key, value| - next if self.path.include? "{#{key}}" # skip path params - next if value.blank? && value.class != FalseClass # skip empties - if Swagger.configuration.camelize_params - key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param + # static method to convert object (array, hash, object, etc) to JSON string + # @param model object to be converted into JSON string + # @return string JSON string representation of the object + def self.object_to_http_body model + return if model.nil? + _body = nil + if model.is_a?(Array) + _body = model.map{|m| object_to_hash(m) } + else + _body = object_to_hash(model) end - query_values[key] = value.to_s + _body.to_json end - - # We don't want to end up with '?' as our query string - # if there aren't really any params - return "" if query_values.blank? - - # Addressable requires query_values to be set after initialization.. - qs = Addressable::URI.new - qs.query_values = query_values - qs.to_s - end - - def make - #TODO use configuration setting to determine if debugging - #logger = Logger.new STDOUT - #logger.debug self.url - response = case self.http_method.to_sym - when :get,:GET - Typhoeus::Request.get( - self.url, - :headers => self.headers.stringify_keys, - ) - when :post,:POST - Typhoeus::Request.post( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :patch,:PATCH - Typhoeus::Request.patch( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :put,:PUT - Typhoeus::Request.put( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :delete,:DELETE - Typhoeus::Request.delete( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) + # static method to convert object(non-array) to hash + # @param obj object to be converted into JSON string + # @return string JSON string representation of the object + def self.object_to_hash obj + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end end - Response.new(response) - end - - def response - self.make - end - - def response_code_pretty - return unless @response.present? - @response.code.to_s - end - - def response_headers_pretty - return unless @response.present? - # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient - @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus - end - # return 'Accept' based on an array of accept provided - # @param [Array] header_accept_array Array fo 'Accept' - # @return String Accept (e.g. application/json) - def self.select_header_accept header_accept_array - if header_accept_array.empty? - return - elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # look for json data by default - else - header_accept_array.join(',') - end end - - # return the content type based on an array of content-type provided - # @param [Array] content_type_array Array fo content-type - # @return String Content-Type (e.g. application/json) - def self.select_header_content_type content_type_array - if content_type_array.empty? - 'application/json' # use application/json by default - elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # use application/json if it's included - else - content_type_array[0]; # otherwise, use the first one - end - end - - # static method to convert object (array, hash, object, etc) to JSON string - # @param model object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_http_body model - return if model.nil? - _body = nil - if model.is_a?(Array) - _body = model.map{|m| object_to_hash(m) } - else - _body = object_to_hash(model) - end - _body.to_json - end - - # static method to convert object(non-array) to hash - # @param obj object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_hash obj - if obj.respond_to?(:to_hash) - obj.to_hash - else - obj - end - end - end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache index 641b7ccc756..e7bb482fb66 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache @@ -1,70 +1,70 @@ -module Swagger +module {{moduleName}} + module Swagger + class Response + require 'json' - class Response - require 'json' + attr_accessor :raw - attr_accessor :raw + def initialize(raw) + self.raw = raw - def initialize(raw) - self.raw = raw + case self.code + when 500..510 then raise(ServerError, self.error_message) + when 299..426 then raise(ClientError, self.error_message) + end + end - case self.code - when 500..510 then raise(ServerError, self.error_message) - when 299..426 then raise(ClientError, self.error_message) + def code + raw.code + end + + # Account for error messages that take different forms... + def error_message + body['message'] + rescue + body + end + + # If body is JSON, parse it + # Otherwise return raw string + def body + JSON.parse(raw.body, :symbolize_names => true) + rescue + raw.body + end + + # `headers_hash` is a Typhoeus-specific extension of Hash, + # so simplify it back into a regular old Hash. + def headers + h = {} + raw.headers_hash.each {|k,v| h[k] = v } + h + end + + # Extract the response format from the header hash + # e.g. {'Content-Type' => 'application/json'} + def format + headers['Content-Type'].split("/").last.downcase + end + + def json? + format == 'json' + end + + def xml? + format == 'xml' + end + + def pretty_body + return unless body.present? + case format + when 'json' then JSON.pretty_generate(body).gsub(/\n/, '
') + end + end + + def pretty_headers + JSON.pretty_generate(headers).gsub(/\n/, '
') end end - - def code - raw.code - end - - # Account for error messages that take different forms... - def error_message - body['message'] - rescue - body - end - - # If body is JSON, parse it - # Otherwise return raw string - def body - JSON.parse(raw.body, :symbolize_names => true) - rescue - raw.body - end - - # `headers_hash` is a Typhoeus-specific extension of Hash, - # so simplify it back into a regular old Hash. - def headers - h = {} - raw.headers_hash.each {|k,v| h[k] = v } - h - end - - # Extract the response format from the header hash - # e.g. {'Content-Type' => 'application/json'} - def format - headers['Content-Type'].split("/").last.downcase - end - - def json? - format == 'json' - end - - def xml? - format == 'xml' - end - - def pretty_body - return unless body.present? - case format - when 'json' then JSON.pretty_generate(body).gsub(/\n/, '
') - end - end - - def pretty_headers - JSON.pretty_generate(headers).gsub(/\n/, '
') - end - end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache index 39357c0ed6d..332a5e66f45 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache @@ -1,4 +1,5 @@ -module Swagger - VERSION = "4.06.08" +module {{moduleName}} + module Swagger + VERSION = "{{appVersion}}" + end end - diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache new file mode 100644 index 00000000000..9f84d88d4e1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache @@ -0,0 +1,32 @@ +# -*- encoding: utf-8 -*- +$:.push File.expand_path("../lib", __FILE__) +require "{{gemName}}/swagger/version" + +Gem::Specification.new do |s| + s.name = "{{gemName}}" + s.version = {{moduleName}}::Swagger::VERSION + s.platform = Gem::Platform::RUBY + s.authors = ["Zeke Sikelianos", "Tony Tam"] + s.email = ["zeke@wordnik.com", "tony@wordnik.com"] + s.homepage = "http://developer.wordnik.com" + s.summary = %q{A ruby wrapper for the swagger APIs} + s.description = %q{This gem maps to a swagger API} + s.license = "Apache-2.0" + + s.add_runtime_dependency 'typhoeus', '~> 0.2', '>= 0.2.1' + s.add_runtime_dependency 'addressable', '~> 2.2', '>= 2.2.4' + s.add_runtime_dependency 'json', '~> 1.4', '>= 1.4.6' + + s.add_development_dependency 'rspec', '~> 3.2', '>= 3.2.0' + s.add_development_dependency 'vcr', '~> 2.9', '>= 2.9.3' + s.add_development_dependency 'webmock', '~> 1.6', '>= 1.6.2' + s.add_development_dependency 'autotest', '~> 4.4', '>= 4.4.6' + s.add_development_dependency 'autotest-rails-pure', '~> 4.1', '>= 4.1.2' + s.add_development_dependency 'autotest-growl', '~> 0.2', '>= 0.2.16' + s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.10' + + s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? } + s.test_files = `find spec/*`.split("\n") + s.executables = [] + s.require_paths = ["lib"] +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache new file mode 100644 index 00000000000..df675ddf26e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache @@ -0,0 +1,25 @@ +# Swagger common files +require '{{gemName}}/monkey' +require '{{gemName}}/swagger' +require '{{gemName}}/swagger/configuration' +require '{{gemName}}/swagger/request' +require '{{gemName}}/swagger/response' +require '{{gemName}}/swagger/version' + +# Models +require '{{modelPackage}}/base_object' +{{#models}} +require '{{importPath}}' +{{/models}} + +# APIs +{{#apiInfo}} +{{#apis}} +require '{{importPath}}' +{{/apis}} +{{/apiInfo}} + +module {{moduleName}} + # Initialize the default configuration + Swagger.configuration ||= Swagger::Configuration.new +end diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.json b/modules/swagger-codegen/src/test/resources/2_0/petstore.json index b4678fc3ab9..30c53134633 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore.json +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.json @@ -720,6 +720,18 @@ "description": "successful operation", "schema": { "$ref": "#/definitions/User" + }, + "examples": { + "application/json": { + "id": 1, + "username": "johnp", + "firstName": "John", + "lastName": "Public", + "email": "johnp@swagger.io", + "password": "-secret-", + "phone": "0123456789", + "userStatus": 0 + } } }, "400": { diff --git a/modules/swagger-codegen/src/test/resources/2_0/requiredTest.json b/modules/swagger-codegen/src/test/resources/2_0/requiredTest.json new file mode 100644 index 00000000000..88106746d29 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/requiredTest.json @@ -0,0 +1,93 @@ +{ + "swagger": "2.0", + "info": { + "description": "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", + "version": "1.0.0", + "title": "Swagger Petstore", + "termsOfService": "http://helloreverb.com/terms/", + "contact": { + "email": "apiteam@wordnik.com" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "host": "petstore.swagger.io", + "basePath": "/v2", + "schemes": [ + "http" + ], + "paths": { + "/tests/requiredParams": { + "get": { + "tags": [ + "tests" + ], + "summary": "Operation with required parameters", + "description": "", + "operationId": "requiredParams", + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "param1", + "in": "formData", + "description": "Some required parameter", + "required": true, + "type": "integer", + "format": "int64" + }, + { + "name": "param2", + "in": "formData", + "description": "Some optional parameter", + "required": false, + "type": "string" + } + ], + "responses": { + "200": { + "description": "successful operation. Retuning a simple int.", + "schema": { + "type": "integer", + "format": "int64" + } + } + } + } + } + }, + "securityDefinitions": { + "api_key": { + "type": "apiKey", + "name": "api_key", + "in": "header" + }, + "petstore_auth": { + "type": "oauth2", + "authorizationUrl": "http://petstore.swagger.io/api/oauth/dialog", + "flow": "implicit", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + }, + "definitions": { + "CustomModel": { + "required": ["id"], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string", + "example": "doggie" + } + } + } + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/resources/2_0/v1beta3.json b/modules/swagger-codegen/src/test/resources/2_0/v1beta3.json new file mode 100644 index 00000000000..c5e7d8d5986 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/v1beta3.json @@ -0,0 +1,316 @@ +{ + "swaggerVersion": "1.2", + "apiVersion": "v1beta3", + "basePath": "https://127.0.0.1:6443", + "resourcePath": "/api/v1beta3", + "apis": [ + { + "path": "/api/v1beta3/namespaces/{namespaces}/bindings", + "description": "API at /api/v1beta3 version v1beta3", + "operations": [ + { + "type": "v1beta3.Binding", + "method": "POST", + "summary": "create a Binding", + "nickname": "createBinding", + "parameters": [ + { + "type": "string", + "paramType": "path", + "name": "namespaces", + "description": "object name and auth scope, such as for teams and projects", + "required": true, + "allowMultiple": false + }, + { + "type": "v1beta3.Binding", + "paramType": "body", + "name": "body", + "description": "", + "required": true, + "allowMultiple": false + } + ], + "responseMessages": [ + { + "code": 200, + "message": "OK", + "responseModel": "v1beta3.Binding" + } + ], + "produces": [ + "application/json" + ], + "consumes": [ + "*/*" + ] + } + ] + }, + { + "path": "/api/v1beta3/namespaces/{namespaces}/componentstatuses", + "description": "API at /api/v1beta3 version v1beta3", + "operations": [ + { + "type": "v1beta3.ComponentStatusList", + "method": "GET", + "summary": "list objects of kind ComponentStatus", + "nickname": "listComponentStatus", + "parameters": [ + { + "type": "string", + "paramType": "path", + "name": "namespaces", + "description": "object name and auth scope, such as for teams and projects", + "required": true, + "allowMultiple": false + }, + { + "type": "string", + "paramType": "query", + "name": "fieldSelector", + "description": "a selector to restrict the list of returned objects by their fields; defaults to everything", + "required": false, + "allowMultiple": false + }, + { + "type": "string", + "paramType": "query", + "name": "labelSelector", + "description": "a selector to restrict the list of returned objects by their labels; defaults to everything", + "required": false, + "allowMultiple": false + }, + { + "type": "string", + "paramType": "query", + "name": "resourceVersion", + "description": "when specified with a watch call, shows changes that occur after that particular version of a resource; defaults to changes from the beginning of history", + "required": false, + "allowMultiple": false + }, + { + "type": "boolean", + "paramType": "query", + "name": "watch", + "description": "watch for changes to the described resources and return them as a stream of add, update, and remove notifications; specify resourceVersion", + "required": false, + "allowMultiple": false + } + ], + "responseMessages": [ + { + "code": 200, + "message": "OK", + "responseModel": "v1beta3.ComponentStatusList" + } + ], + "produces": [ + "application/json" + ], + "consumes": [ + "*/*" + ] + } + ] + }, + { + "path": "/api/v1beta3/namespaces/{namespaces}/componentstatuses/{name}", + "description": "API at /api/v1beta3 version v1beta3", + "operations": [ + { + "type": "v1beta3.ComponentStatus", + "method": "GET", + "summary": "read the specified ComponentStatus", + "nickname": "readComponentStatus", + "parameters": [ + { + "type": "string", + "paramType": "path", + "name": "name", + "description": "name of the ComponentStatus", + "required": true, + "allowMultiple": false + }, + { + "type": "string", + "paramType": "path", + "name": "namespaces", + "description": "object name and auth scope, such as for teams and projects", + "required": true, + "allowMultiple": false + } + ], + "responseMessages": [ + { + "code": 200, + "message": "OK", + "responseModel": "v1beta3.ComponentStatus" + } + ], + "produces": [ + "application/json" + ], + "consumes": [ + "*/*" + ] + } + ] + } + ], + "models": { + "v1beta3.ComponentStatus": { + "id": "v1beta3.ComponentStatus", + "properties": { + "apiVersion": { + "type": "string", + "description": "version of the schema the object should have" + }, + "conditions": { + "type": "array", + "items": { + "$ref": "v1beta3.ObjectReference" + }, + "description": "list of component conditions observed" + }, + "kind": { + "type": "string", + "description": "kind of object, in CamelCase; cannot be updated" + }, + "metadata": { + "$ref": "v1beta3.ObjectMeta", + "description": "standard object metadata; see http://docs.k8s.io/api-conventions.md#metadata" + } + } + }, + "v1beta3.ComponentStatusList": { + "id": "v1beta3.ComponentStatusList", + "required": [ + "items" + ], + "properties": { + "apiVersion": { + "type": "string", + "description": "version of the schema the object should have" + }, + "items": { + "type": "array", + "items": { + "$ref": "v1beta3.ComponentStatus" + }, + "description": "list of component status objects" + }, + "kind": { + "type": "string", + "description": "kind of object, in CamelCase; cannot be updated" + }, + "metadata": { + "$ref": "v1beta3.ObjectMeta", + "description": "standard list metadata; see http://docs.k8s.io/api-conventions.md#metadata" + } + } + }, + "v1beta3.Binding": { + "id": "v1beta3.Binding", + "required": [ + "target" + ], + "properties": { + "apiVersion": { + "type": "string", + "description": "version of the schema the object should have" + }, + "kind": { + "type": "string", + "description": "kind of object, in CamelCase; cannot be updated" + }, + "metadata": { + "$ref": "v1beta3.ObjectMeta", + "description": "standard object metadata; see http://docs.k8s.io/api-conventions.md#metadata" + }, + "target": { + "$ref": "v1beta3.ObjectReference", + "description": "an object to bind to" + } + } + }, + "v1beta3.ObjectReference": { + "id": "v1beta3.ObjectReference", + "properties": { + "apiVersion": { + "type": "string", + "description": "API version of the referent" + }, + "fieldPath": { + "type": "string", + "description": "if referring to a piece of an object instead of an entire object, this string should contain a valid JSON/Go field access statement, such as desiredState.manifest.containers[2]" + }, + "kind": { + "type": "string", + "description": "kind of the referent" + }, + "name": { + "type": "string", + "description": "name of the referent" + }, + "namespace": { + "type": "string", + "description": "namespace of the referent" + }, + "resourceVersion": { + "type": "string", + "description": "specific resourceVersion to which this reference is made, if any: http://docs.k8s.io/api-conventions.md#concurrency-control-and-consistency" + }, + "uid": { + "type": "string", + "description": "uid of the referent" + } + } + }, + "v1beta3.ObjectMeta": { + "id": "v1beta3.ObjectMeta", + "properties": { + "annotations": { + "type": "any", + "description": "map of string keys and values that can be used by external tooling to store and retrieve arbitrary metadata about objects" + }, + "creationTimestamp": { + "type": "string", + "description": "RFC 3339 date and time at which the object was created; populated by the system, read-only; null for lists" + }, + "deletionTimestamp": { + "type": "string", + "description": "RFC 3339 date and time at which the object will be deleted; populated by the system when a graceful deletion is requested, read-only; if not set, graceful deletion of the object has not been requested" + }, + "generateName": { + "type": "string", + "description": "an optional prefix to use to generate a unique name; has the same validation rules as name; optional, and is applied only name if is not specified" + }, + "labels": { + "type": "any", + "description": "map of string keys and values that can be used to organize and categorize objects; may match selectors of replication controllers and services" + }, + "name": { + "type": "string", + "description": "string that identifies an object. Must be unique within a namespace; cannot be updated" + }, + "namespace": { + "type": "string", + "description": "namespace of the object; cannot be updated" + }, + "resourceVersion": { + "type": "string", + "description": "string that identifies the internal version of this object that can be used by clients to determine when objects have changed; populated by the system, read-only; value must be treated as opaque by clients and passed unmodified back to the server: http://docs.k8s.io/api-conventions.md#concurrency-control-and-consistency" + }, + "selfLink": { + "type": "string", + "description": "URL for the object; populated by the system, read-only" + }, + "uid": { + "type": "string", + "description": "unique UUID across space and time; populated by the system; read-only" + } + } + } + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/CodegenTest.scala b/modules/swagger-codegen/src/test/scala/CodegenTest.scala index 9e2a1d9fa9e..5ce35825159 100644 --- a/modules/swagger-codegen/src/test/scala/CodegenTest.scala +++ b/modules/swagger-codegen/src/test/scala/CodegenTest.scala @@ -1,15 +1,9 @@ -import com.wordnik.swagger.models._ -import com.wordnik.swagger.util.Json -import io.swagger.parser._ - import com.wordnik.swagger.codegen.DefaultCodegen - +import com.wordnik.swagger.models.properties.Property +import io.swagger.parser._ import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner -import org.scalatest.FlatSpec -import org.scalatest.Matchers - -import scala.collection.JavaConverters._ +import org.scalatest.{FlatSpec, Matchers} @RunWith(classOf[JUnitRunner]) class CodegenTest extends FlatSpec with Matchers { @@ -95,6 +89,32 @@ class CodegenTest extends FlatSpec with Matchers { statusParam.hasMore should be (null) } + it should "handle required parameters from a 2.0 spec as required when figuring out Swagger types" in { + val model = new SwaggerParser() + .read("src/test/resources/2_0/requiredTest.json") + + val codegen = new DefaultCodegen() { + override def getSwaggerType(p: Property) = Option(p) match { + case Some(property) if !property.getRequired => + "Optional<" + super.getSwaggerType(p) + ">" + case other => super.getSwaggerType(p) + } + } + val path = "/tests/requiredParams" + val p = model.getPaths().get(path).getGet() + val op = codegen.fromOperation(path, "get", p, model.getDefinitions) + + val formParams = op.formParams + formParams.size should be(2) + val requiredParam = formParams.get(0) + requiredParam.dataType should be("Long") + + val optionalParam = formParams.get(1) + optionalParam.dataType should be("Optional") + + op.returnType should be("Long") + } + it should "select main response from a 2.0 spec using the lowest 2XX code" in { val model = new SwaggerParser() .read("src/test/resources/2_0/responseSelectionTest.json") diff --git a/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala b/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala new file mode 100644 index 00000000000..09ffbf0e16c --- /dev/null +++ b/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala @@ -0,0 +1,67 @@ +import scala.collection.JavaConverters.asScalaBufferConverter +import scala.collection.JavaConverters.mapAsJavaMapConverter +import scala.collection.JavaConverters.seqAsJavaListConverter + +import org.junit.runner.RunWith +import org.scalatest.FlatSpec +import org.scalatest.Matchers +import org.scalatest.junit.JUnitRunner + +import com.wordnik.swagger.codegen.examples.ExampleGenerator +import com.wordnik.swagger.models.Model +import com.wordnik.swagger.models.ModelImpl +import com.wordnik.swagger.models.Xml +import com.wordnik.swagger.models.properties.ArrayProperty +import com.wordnik.swagger.models.properties.RefProperty +import com.wordnik.swagger.models.properties.StringProperty + +@RunWith(classOf[JUnitRunner]) +class ExampleGeneratorTest extends FlatSpec with Matchers { + val json = "application/json" + val xml = "application/xml" + + it should "check handling of recursive models" in { + val nodeType = "Node" + val ref = new RefProperty(nodeType) + val node = new ModelImpl().name(nodeType).property("name", new StringProperty()) + node.property("parent", ref) + node.property("children", new ArrayProperty(ref)) + node.property("wrappedChildren", new ArrayProperty(ref).xml(new Xml().wrapped(true))) + val pairType = "Pair" + val pair = new ModelImpl().name(pairType) + for (item <- Map("first" -> "First", "second" -> "Second")) { + val property = new RefProperty(nodeType) + property.setXml(new Xml().name(item._2)) + pair.property(item._1, property); + } + val types = scala.collection.mutable.Buffer[String]() + val expectedTypes = List(json, xml) + val eg = new ExampleGenerator(Map[String, Model](nodeType -> node, pairType -> pair).asJava) + for (item <- eg.generate(null, expectedTypes.asJava, new RefProperty(pairType)).asScala) { + val example = item.get("example") + item.get("contentType") match { + case `xml` => { + types += xml + example should be ("\n" + + " \n" + + " string\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " string\n" + + " \n" + + " \n" + + " \n" + + "") + } + case `json` => { + types += json + // TODO - add JSON validation + example should not be (null) + } + } + } + types should be (expectedTypes) + } +} diff --git a/modules/swagger-codegen/src/test/scala/python/PythonTest.scala b/modules/swagger-codegen/src/test/scala/python/PythonTest.scala new file mode 100644 index 00000000000..ec42985586c --- /dev/null +++ b/modules/swagger-codegen/src/test/scala/python/PythonTest.scala @@ -0,0 +1,34 @@ +package python + +import com.wordnik.swagger.codegen.languages.{PythonClientCodegen} +import io.swagger.parser.SwaggerParser +import org.junit.runner.RunWith + +import org.scalatest.junit.JUnitRunner +import org.scalatest.FlatSpec +import org.scalatest.Matchers + +@RunWith(classOf[JUnitRunner]) +class PythonTest extends FlatSpec with Matchers { + it should "convert a python model with dots" in { + val swagger = new SwaggerParser() + .read("src/test/resources/2_0/v1beta3.json") + + val codegen = new PythonClientCodegen() + val simpleName = codegen.fromModel("v1beta3.Binding", swagger.getDefinitions().get("v1beta3.Binding")) + simpleName.name should be("v1beta3.Binding") + simpleName.classname should be("V1beta3Binding") + simpleName.classVarName should be("v1beta3_binding") + + val compoundName = codegen.fromModel("v1beta3.ComponentStatus", swagger.getDefinitions().get("v1beta3.ComponentStatus")) + compoundName.name should be("v1beta3.ComponentStatus") + compoundName.classname should be("V1beta3ComponentStatus") + compoundName.classVarName should be("v1beta3_component_status") + + val path = "/api/v1beta3/namespaces/{namespaces}/bindings" + val operation = swagger.getPaths().get(path).getPost() + val codegenOperation = codegen.fromOperation(path, "get", operation, swagger.getDefinitions()) + codegenOperation.returnType should be("V1beta3Binding") + codegenOperation.returnBaseType should be("V1beta3Binding") + } +} diff --git a/modules/swagger-generator/pom.xml b/modules/swagger-generator/pom.xml index 23187d581dd..e5b7b2c341f 100644 --- a/modules/swagger-generator/pom.xml +++ b/modules/swagger-generator/pom.xml @@ -6,11 +6,9 @@ 2.1.1-M2-SNAPSHOT ../.. - com.wordnik swagger-generator war swagger-generator - 2.1.1-M2-SNAPSHOT src/main/java diff --git a/pom.xml b/pom.xml index e28a46bb442..6fbb36464f8 100644 --- a/pom.xml +++ b/pom.xml @@ -450,10 +450,10 @@ - 1.0.6-SNAPSHOT + 1.0.7 2.10.4 2.3.4 - 1.5.1-M2 + 1.5.2-M2 2.1.4 2.3 1.2 diff --git a/samples/client/petstore/akka-scala/pom.xml b/samples/client/petstore/akka-scala/pom.xml new file mode 100644 index 00000000000..f865a97c38b --- /dev/null +++ b/samples/client/petstore/akka-scala/pom.xml @@ -0,0 +1,227 @@ + + 4.0.0 + com.wordnik + swagger-client + jar + swagger-client + 1.0.0 + + 2.2.0 + + + + + maven-mongodb-plugin-repo + maven mongodb plugin repository + http://maven-mongodb-plugin.googlecode.com/svn/maven/repo + default + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + + 1.6 + 1.6 + + + + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin-version} + + + scala-compile-first + process-resources + + add-source + compile + + + + scala-test-compile + process-test-resources + + testCompile + + + + + + -feature + + + -Xms128m + -Xmx1500m + + + + + + + + + org.scala-tools + maven-scala-plugin + + ${scala-version} + + + + + + + org.scala-lang + scala-library + ${scala-version} + + + com.wordnik + swagger-core + ${swagger-core-version} + + + org.scalatest + scalatest_2.10 + ${scala-test-version} + test + + + junit + junit + ${junit-version} + test + + + joda-time + joda-time + ${joda-time-version} + + + org.joda + joda-convert + ${joda-version} + + + com.typesafe + config + 1.2.1 + + + com.typesafe.akka + akka-actor_2.10 + ${akka-version} + + + io.spray + spray-client + ${spray-version} + + + org.json4s + json4s-jackson_2.10 + ${json4s-jackson-version} + + + + 2.10.4 + 3.2.11 + 3.2.11 + 1.3.1 + 2.3.9 + 1.2 + 2.2 + 1.5.0-M1 + 1.0.0 + + 4.8.1 + 3.1.5 + 2.1.3 + + diff --git a/samples/client/petstore/akka-scala/src/main/resources/reference.conf b/samples/client/petstore/akka-scala/src/main/resources/reference.conf new file mode 100644 index 00000000000..f993f765edd --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/resources/reference.conf @@ -0,0 +1,24 @@ +io.swagger.client { + + apiRequest { + + compression { + enabled: false + size-threshold: 0 + } + + trust-certificates: true + + connection-timeout: 5000ms + + default-headers { + "userAgent": "swagger-client_1.0.0" + } + + // let you define custom http status code, as in : + // { code: 601, reason: "some custom http status code", success: false } + custom-codes : [] + } +} + +spray.can.host-connector.max-redirects = 10 \ No newline at end of file diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/EnumsSerializers.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/EnumsSerializers.scala new file mode 100644 index 00000000000..c8c0d2454e4 --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/EnumsSerializers.scala @@ -0,0 +1,43 @@ +package io.swagger.client.api + +import io.swagger.client.model._ +import org.json4s._ +import scala.reflect.ClassTag + +object EnumsSerializers { + + def all = Seq[Serializer[_]]() :+ + new EnumNameSerializer(PetEnums.Status) :+ + new EnumNameSerializer(OrderEnums.Status) + + + + private class EnumNameSerializer[E <: Enumeration: ClassTag](enum: E) + extends Serializer[E#Value] { + import JsonDSL._ + + val EnumerationClass = classOf[E#Value] + + def deserialize(implicit format: Formats): + PartialFunction[(TypeInfo, JValue), E#Value] = { + case (t @ TypeInfo(EnumerationClass, _), json) if isValid(json) => { + json match { + case JString(value) => + enum.withName(value) + case value => + throw new MappingException(s"Can't convert $value to $EnumerationClass") + } + } + } + + private[this] def isValid(json: JValue) = json match { + case JString(value) if enum.values.exists(_.toString == value) => true + case _ => false + } + + def serialize(implicit format: Formats): PartialFunction[Any, JValue] = { + case i: E#Value => i.toString + } + } + +} \ No newline at end of file diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala new file mode 100644 index 00000000000..d5ae6fd65f0 --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -0,0 +1,139 @@ +package io.swagger.client.api + +import io.swagger.client.model.Pet +import java.io.File +import io.swagger.client.core._ +import io.swagger.client.core.CollectionFormats._ +import io.swagger.client.core.ApiKeyLocations._ + +object PetApi { + + /** + * + * Expected answers: + * code 405 : (Validation exception) + * code 404 : (Pet not found) + * code 400 : (Invalid ID supplied) + * + * @param body Pet object that needs to be added to the store + */ + def updatePet(body: Option[Pet] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.PUT, "http://petstore.swagger.io/v2", "/pet", "application/json") + .withBody(body) + .withErrorResponse[Unit](405) + .withErrorResponse[Unit](404) + .withErrorResponse[Unit](400) + + /** + * + * Expected answers: + * code 405 : (Invalid input) + * + * @param body Pet object that needs to be added to the store + */ + def addPet(body: Option[Pet] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/pet", "application/json") + .withBody(body) + .withErrorResponse[Unit](405) + + /** + * Multiple status values can be provided with comma seperated strings + * + * Expected answers: + * code 200 : Seq[Pet] (successful operation) + * code 400 : (Invalid status value) + * + * @param status Status values that need to be considered for filter + */ + def findPetsByStatus(status: Seq[String]): ApiRequest[Seq[Pet]] = + ApiRequest[Seq[Pet]](ApiMethods.GET, "http://petstore.swagger.io/v2", "/pet/findByStatus", "application/json") + .withQueryParam("status", ArrayValues(status, MULTI)) + .withSuccessResponse[Seq[Pet]](200) + .withErrorResponse[Unit](400) + + /** + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * + * Expected answers: + * code 200 : Seq[Pet] (successful operation) + * code 400 : (Invalid tag value) + * + * @param tags Tags to filter by + */ + def findPetsByTags(tags: Seq[String]): ApiRequest[Seq[Pet]] = + ApiRequest[Seq[Pet]](ApiMethods.GET, "http://petstore.swagger.io/v2", "/pet/findByTags", "application/json") + .withQueryParam("tags", ArrayValues(tags, MULTI)) + .withSuccessResponse[Seq[Pet]](200) + .withErrorResponse[Unit](400) + + /** + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * + * Expected answers: + * code 404 : (Pet not found) + * code 200 : Pet (successful operation) + * code 400 : (Invalid ID supplied) + * + * Available security schemes: + * api_key (apiKey) + * + * @param petId ID of pet that needs to be fetched + */ + def getPetById(petId: Long)(implicit apiKey: ApiKeyValue): ApiRequest[Pet] = + ApiRequest[Pet](ApiMethods.GET, "http://petstore.swagger.io/v2", "/pet/{petId}", "application/json") + .withApiKey(apiKey, "api_key", HEADER) + .withPathParam("petId", petId) + .withErrorResponse[Unit](404) + .withSuccessResponse[Pet](200) + .withErrorResponse[Unit](400) + + /** + * + * Expected answers: + * code 405 : (Invalid input) + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + def updatePetWithForm(petId: String, name: Option[String] = None, status: Option[String] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/pet/{petId}", "application/x-www-form-urlencoded") + .withFormParam("name", name) + .withFormParam("status", status) + .withPathParam("petId", petId) + .withErrorResponse[Unit](405) + + /** + * + * Expected answers: + * code 400 : (Invalid pet value) + * + * @param apiKey + * @param petId Pet id to delete + */ + def deletePet(apiKey: Option[String] = None, petId: Long): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.DELETE, "http://petstore.swagger.io/v2", "/pet/{petId}", "application/json") + .withPathParam("petId", petId) + .withHeaderParam("api_key", apiKey) + .withErrorResponse[Unit](400) + + /** + * + * Expected answers: + * code 0 : (successful operation) + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + def uploadFile(petId: Long, additionalMetadata: Option[String] = None, file: Option[File] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/pet/{petId}/uploadImage", "multipart/form-data") + .withFormParam("additionalMetadata", additionalMetadata) + .withFormParam("file", file) + .withPathParam("petId", petId) + .withDefaultSuccessResponse[Unit] + + + +} + diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/StoreApi.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/StoreApi.scala new file mode 100644 index 00000000000..686e85e105d --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/StoreApi.scala @@ -0,0 +1,73 @@ +package io.swagger.client.api + +import io.swagger.client.model.Order +import io.swagger.client.core._ +import io.swagger.client.core.CollectionFormats._ +import io.swagger.client.core.ApiKeyLocations._ + +object StoreApi { + + /** + * Returns a map of status codes to quantities + * + * Expected answers: + * code 200 : Map[String, Int] (successful operation) + * + * Available security schemes: + * api_key (apiKey) + */ + def getInventory()(implicit apiKey: ApiKeyValue): ApiRequest[Map[String, Int]] = + ApiRequest[Map[String, Int]](ApiMethods.GET, "http://petstore.swagger.io/v2", "/store/inventory", "application/json") + .withApiKey(apiKey, "api_key", HEADER) + .withSuccessResponse[Map[String, Int]](200) + + /** + * + * Expected answers: + * code 200 : Order (successful operation) + * code 400 : (Invalid Order) + * + * @param body order placed for purchasing the pet + */ + def placeOrder(body: Option[Order] = None): ApiRequest[Order] = + ApiRequest[Order](ApiMethods.POST, "http://petstore.swagger.io/v2", "/store/order", "application/json") + .withBody(body) + .withSuccessResponse[Order](200) + .withErrorResponse[Unit](400) + + /** + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * Expected answers: + * code 404 : (Order not found) + * code 200 : Order (successful operation) + * code 400 : (Invalid ID supplied) + * + * @param orderId ID of pet that needs to be fetched + */ + def getOrderById(orderId: String): ApiRequest[Order] = + ApiRequest[Order](ApiMethods.GET, "http://petstore.swagger.io/v2", "/store/order/{orderId}", "application/json") + .withPathParam("orderId", orderId) + .withErrorResponse[Unit](404) + .withSuccessResponse[Order](200) + .withErrorResponse[Unit](400) + + /** + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * Expected answers: + * code 404 : (Order not found) + * code 400 : (Invalid ID supplied) + * + * @param orderId ID of the order that needs to be deleted + */ + def deleteOrder(orderId: String): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.DELETE, "http://petstore.swagger.io/v2", "/store/order/{orderId}", "application/json") + .withPathParam("orderId", orderId) + .withErrorResponse[Unit](404) + .withErrorResponse[Unit](400) + + + +} + diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/UserApi.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/UserApi.scala new file mode 100644 index 00000000000..4c2ab10e9e7 --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/UserApi.scala @@ -0,0 +1,123 @@ +package io.swagger.client.api + +import io.swagger.client.model.User +import io.swagger.client.core._ +import io.swagger.client.core.CollectionFormats._ +import io.swagger.client.core.ApiKeyLocations._ + +object UserApi { + + /** + * This can only be done by the logged in user. + * + * Expected answers: + * code 0 : (successful operation) + * + * @param body Created user object + */ + def createUser(body: Option[User] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/user", "application/json") + .withBody(body) + .withDefaultSuccessResponse[Unit] + + /** + * + * Expected answers: + * code 0 : (successful operation) + * + * @param body List of user object + */ + def createUsersWithArrayInput(body: Seq[User]): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/user/createWithArray", "application/json") + .withBody(body) + .withDefaultSuccessResponse[Unit] + + /** + * + * Expected answers: + * code 0 : (successful operation) + * + * @param body List of user object + */ + def createUsersWithListInput(body: Seq[User]): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/user/createWithList", "application/json") + .withBody(body) + .withDefaultSuccessResponse[Unit] + + /** + * + * Expected answers: + * code 200 : String (successful operation) + * code 400 : (Invalid username/password supplied) + * + * @param username The user name for login + * @param password The password for login in clear text + */ + def loginUser(username: Option[String] = None, password: Option[String] = None): ApiRequest[String] = + ApiRequest[String](ApiMethods.GET, "http://petstore.swagger.io/v2", "/user/login", "application/json") + .withQueryParam("username", username) + .withQueryParam("password", password) + .withSuccessResponse[String](200) + .withErrorResponse[Unit](400) + + /** + * + * Expected answers: + * code 0 : (successful operation) + */ + def logoutUser(): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.GET, "http://petstore.swagger.io/v2", "/user/logout", "application/json") + .withDefaultSuccessResponse[Unit] + + /** + * + * Expected answers: + * code 404 : (User not found) + * code 200 : User (successful operation) + * code 400 : (Invalid username supplied) + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + def getUserByName(username: String): ApiRequest[User] = + ApiRequest[User](ApiMethods.GET, "http://petstore.swagger.io/v2", "/user/{username}", "application/json") + .withPathParam("username", username) + .withErrorResponse[Unit](404) + .withSuccessResponse[User](200) + .withErrorResponse[Unit](400) + + /** + * This can only be done by the logged in user. + * + * Expected answers: + * code 404 : (User not found) + * code 400 : (Invalid user supplied) + * + * @param username name that need to be deleted + * @param body Updated user object + */ + def updateUser(username: String, body: Option[User] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.PUT, "http://petstore.swagger.io/v2", "/user/{username}", "application/json") + .withBody(body) + .withPathParam("username", username) + .withErrorResponse[Unit](404) + .withErrorResponse[Unit](400) + + /** + * This can only be done by the logged in user. + * + * Expected answers: + * code 404 : (User not found) + * code 400 : (Invalid username supplied) + * + * @param username The name that needs to be deleted + */ + def deleteUser(username: String): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.DELETE, "http://petstore.swagger.io/v2", "/user/{username}", "application/json") + .withPathParam("username", username) + .withErrorResponse[Unit](404) + .withErrorResponse[Unit](400) + + + +} + diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala new file mode 100644 index 00000000000..3b11d866017 --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala @@ -0,0 +1,323 @@ +package io.swagger.client.core + +import java.io.File +import java.security.cert.X509Certificate +import javax.net.ssl._ + +import akka.actor.ActorSystem +import akka.io.IO +import akka.pattern.ask +import akka.util.Timeout +import org.joda.time.DateTime +import org.joda.time.format.ISODateTimeFormat +import org.json4s.JsonAST.JString +import org.json4s._ +import org.json4s.jackson.JsonMethods._ +import org.json4s.jackson.Serialization +import spray.can.Http +import spray.can.Http.HostConnectorSetup +import spray.client.pipelining +import spray.client.pipelining._ +import spray.http.HttpEncodings._ +import spray.http.HttpHeaders.{RawHeader, `Accept-Encoding`} +import spray.http.Uri.Query +import spray.http._ +import spray.http.parser.HttpParser +import spray.httpx.encoding.{Deflate, Encoder, Gzip} +import spray.httpx.unmarshalling._ +import spray.io.ClientSSLEngineProvider + +import scala.concurrent.{ExecutionContext, Future} +import scala.reflect.ClassTag +import scala.util.control.NonFatal + +object ApiInvoker { + + def apply()(implicit system: ActorSystem): ApiInvoker = + apply(DefaultFormats + DateTimeSerializer) + def apply(serializers: Traversable[Serializer[_]])(implicit system: ActorSystem): ApiInvoker = + apply(DefaultFormats + DateTimeSerializer ++ serializers) + def apply(formats: Formats)(implicit system: ActorSystem): ApiInvoker = new ApiInvoker(formats) + + case class CustomStatusCode(value: Int, reason: String = "Application-defined status code", isSuccess: Boolean = true) + + def addCustomStatusCode(code: CustomStatusCode): Unit = addCustomStatusCode(code.value, code.reason, code.isSuccess) + + def addCustomStatusCode(code: Int, reason: String = "Application defined code", isSuccess: Boolean = true) = { + StatusCodes.getForKey(code) foreach { c => + StatusCodes.registerCustom(code, reason, reason, isSuccess, allowsEntity = true) + } + } + + /** + * Allows request execution without calling apiInvoker.execute(request) + * request.response can be used to get a future of the ApiResponse generated. + * request.result can be used to get a future of the expected ApiResponse content. If content doesn't match, a + * Future will failed with a ClassCastException + * @param request the apiRequest to be executed + */ + implicit class ApiRequestImprovements[T](request: ApiRequest[T]) { + + def response(invoker: ApiInvoker)(implicit ec: ExecutionContext, system: ActorSystem): Future[ApiResponse[T]] = + response(ec, system, invoker) + + def response(implicit ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[ApiResponse[T]] = + invoker.execute(request) + + def result[U <: T](implicit c: ClassTag[U], ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[U] = + invoker.execute(request).map(_.content).mapTo[U] + + } + + /** + * Allows transformation from ApiMethod to spray HttpMethods + * @param method the ApiMethod to be converted + */ + implicit class ApiMethodExtensions(val method: ApiMethod) { + def toSprayMethod: HttpMethod = HttpMethods.getForKey(method.value).getOrElse(HttpMethods.GET) + } + + case object DateTimeSerializer extends CustomSerializer[DateTime](format => ( { + case JString(s) => + ISODateTimeFormat.dateTimeParser().parseDateTime(s) + }, { + case d: DateTime => + JString(ISODateTimeFormat.dateTimeParser().print(d)) + })) +} + +class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends UntrustedSslContext with CustomContentTypes { + + import io.swagger.client.core.ApiInvoker._ + import io.swagger.client.core.ParametersMap._ + + implicit val ec = system.dispatcher + implicit val jsonFormats = formats + + def settings = ApiSettings(system) + + import spray.http.MessagePredicate._ + + val CompressionFilter = MessagePredicate({ _ => settings.compressionEnabled}) && + Encoder.DefaultFilter && + minEntitySize(settings.compressionSizeThreshold) + + settings.customCodes.foreach(addCustomStatusCode) + + private def addAuthentication(credentialsSeq: Seq[Credentials]): pipelining.RequestTransformer = + request => + credentialsSeq.foldLeft(request) { + case (req, BasicCredentials(login, password)) => + req ~> addCredentials(BasicHttpCredentials(login, password)) + case (req, ApiKeyCredentials(keyValue, keyName, ApiKeyLocations.HEADER)) => + req ~> addHeader(RawHeader(keyName, keyValue.value)) + case (req, _) => req + } + + private def addHeaders(headers: Map[String, Any]): pipelining.RequestTransformer = { request => + + val rawHeaders = for { + (name, value) <- headers.asFormattedParams + header = RawHeader(name, String.valueOf(value)) + } yield header + + request.withHeaders(rawHeaders.toList) + } + + private def bodyPart(name: String, value: Any): BodyPart = { + value match { + case f: File => + BodyPart(f, name) + case v: String => + BodyPart(HttpEntity(String.valueOf(v))) + case NumericValue(v) => + BodyPart(HttpEntity(String.valueOf(v))) + case m: ApiModel => + BodyPart(HttpEntity(Serialization.write(m))) + } + } + + private def formDataContent(request: ApiRequest[_]) = { + val params = request.formParams.asFormattedParams + if (params.isEmpty) + None + else + Some( + normalizedContentType(request.contentType).mediaType match { + case MediaTypes.`multipart/form-data` => + MultipartFormData(params.map { case (name, value) => (name, bodyPart(name, value))}) + case MediaTypes.`application/x-www-form-urlencoded` => + FormData(params.mapValues(String.valueOf)) + case m: MediaType => // Default : application/x-www-form-urlencoded. + FormData(params.mapValues(String.valueOf)) + } + ) + } + + private def bodyContent(request: ApiRequest[_]): Option[Any] = { + request.bodyParam.map(Extraction.decompose).map(compact) + } + + private def createRequest(uri: Uri, request: ApiRequest[_]): HttpRequest = { + + val builder = new RequestBuilder(request.method.toSprayMethod) + val httpRequest = request.method.toSprayMethod match { + case HttpMethods.GET | HttpMethods.DELETE => builder.apply(uri) + case HttpMethods.POST | HttpMethods.PUT => + formDataContent(request) orElse bodyContent(request) match { + case Some(c: FormData) => + builder.apply(uri, c) + case Some(c: MultipartFormData) => + builder.apply(uri, c) + case Some(c: String) => + builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), c)) + case _ => + builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), " ")) + } + case _ => builder.apply(uri) + } + + httpRequest ~> + addHeaders(request.headerParams) ~> + addAuthentication(request.credentials) ~> + encode(Gzip(CompressionFilter)) + } + + def makeQuery(r: ApiRequest[_]): Query = { + r.credentials.foldLeft(r.queryParams) { + case (params, ApiKeyCredentials(key, keyName, ApiKeyLocations.QUERY)) => + params + (keyName -> key.value) + case (params, _) => params + }.asFormattedParams + .mapValues(String.valueOf) + .foldRight[Query](Uri.Query.Empty) { + case ((name, value), acc) => acc.+:(name, value) + } + } + + def makeUri(r: ApiRequest[_]): Uri = { + val opPath = r.operationPath.replaceAll("\\{format\\}", "json") + val opPathWithParams = r.pathParams.asFormattedParams + .mapValues(String.valueOf) + .foldLeft(opPath) { + case (path, (name, value)) => path.replaceAll(s"\\{$name\\}", value) + } + val query = makeQuery(r) + + Uri(r.basePath + opPathWithParams).withQuery(query) + } + + def execute[T](r: ApiRequest[T]): Future[ApiResponse[T]] = { + try { + implicit val timeout: Timeout = settings.connectionTimeout + + val uri = makeUri(r) + + val connector = HostConnectorSetup( + uri.authority.host.toString, + uri.effectivePort, + sslEncryption = "https".equals(uri.scheme), + defaultHeaders = settings.defaultHeaders ++ List(`Accept-Encoding`(gzip, deflate))) + + val request = createRequest(uri, r) + + for { + Http.HostConnectorInfo(hostConnector, _) <- IO(Http) ? connector + response <- hostConnector.ask(request).mapTo[HttpResponse] + } yield { + response ~> decode(Deflate) ~> decode(Gzip) ~> unmarshallApiResponse(r) + } + } + catch { + case NonFatal(x) => Future.failed(x) + } + } + + def unmarshallApiResponse[T](request: ApiRequest[T])(response: HttpResponse): ApiResponse[T] = { + request.responseForCode(response.status.intValue) match { + case Some( (manifest: Manifest[T], state: ResponseState) ) => + entityUnmarshaller(manifest)(response.entity) match { + case Right(value) ⇒ + state match { + case ResponseState.Success => + ApiResponse(response.status.intValue, value, response.headers.map(header => (header.name, header.value)).toMap) + case ResponseState.Error => + throw new ApiError(response.status.intValue, "Error response received", + Some(value), + headers = response.headers.map(header => (header.name, header.value)).toMap) + } + + case Left(MalformedContent(error, Some(cause))) ⇒ + throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), cause) + + case Left(MalformedContent(error, None)) ⇒ + throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString)) + + case Left(ContentExpected) ⇒ + throw new ApiError(response.status.intValue, s"Unable to unmarshall empty response to [$manifest]", Some(response.entity.toString)) + } + + case _ => throw new ApiError(response.status.intValue, "Unexpected response code", Some(response.entity.toString)) + } + } + + def entityUnmarshaller[T](implicit mf: Manifest[T]): Unmarshaller[T] = + Unmarshaller[T](MediaTypes.`application/json`) { + case x: HttpEntity.NonEmpty ⇒ + parse(x.asString(defaultCharset = HttpCharsets.`UTF-8`)) + .noNulls + .camelizeKeys + .extract[T] + } + +} + +sealed trait CustomContentTypes { + + def normalizedContentType(original: String): ContentType = + MediaTypes.forExtension(original) map (ContentType(_)) getOrElse parseContentType(original) + + def parseContentType(contentType: String): ContentType = { + val contentTypeAsRawHeader = HttpHeaders.RawHeader("Content-Type", contentType) + val parsedContentTypeHeader = HttpParser.parseHeader(contentTypeAsRawHeader) + (parsedContentTypeHeader: @unchecked) match { + case Right(ct: HttpHeaders.`Content-Type`) => + ct.contentType + case Left(error: ErrorInfo) => + throw new IllegalArgumentException( + s"Error converting '$contentType' to a ContentType header: '${error.summary}'") + } + } +} + +sealed trait UntrustedSslContext { + this: ApiInvoker => + + implicit lazy val trustfulSslContext: SSLContext = { + settings.alwaysTrustCertificates match { + case false => + SSLContext.getDefault + + case true => + class IgnoreX509TrustManager extends X509TrustManager { + def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {} + + def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {} + + def getAcceptedIssuers = null + } + + val context = SSLContext.getInstance("TLS") + context.init(null, Array(new IgnoreX509TrustManager), null) + context + } + } + + implicit val clientSSLEngineProvider = + ClientSSLEngineProvider { + _ => + val engine = trustfulSslContext.createSSLEngine() + engine.setUseClientMode(true) + engine + } +} diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiRequest.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiRequest.scala new file mode 100644 index 00000000000..0588193cfbe --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiRequest.scala @@ -0,0 +1,50 @@ +package io.swagger.client.core + +sealed trait ResponseState +object ResponseState { + case object Success extends ResponseState + case object Error extends ResponseState +} + +case class ApiRequest[U]( + // required fields + method: ApiMethod, + basePath: String, + operationPath: String, + contentType: String, + + // optional fields + responses: Map[Int, (Manifest[_], ResponseState)] = Map.empty, + bodyParam: Option[Any] = None, + formParams: Map[String, Any] = Map.empty, + pathParams: Map[String, Any] = Map.empty, + queryParams: Map[String, Any] = Map.empty, + headerParams: Map[String, Any] = Map.empty, + credentials: Seq[Credentials] = List.empty) { + + def withCredentials(cred: Credentials) = copy[U](credentials = credentials :+ cred) + + def withApiKey(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) = withCredentials(ApiKeyCredentials(key, keyName, location)) + + def withSuccessResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Success))) + + def withErrorResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Error))) + + def withDefaultSuccessResponse[T](implicit m: Manifest[T]) = withSuccessResponse[T](0) + + def withDefaultErrorResponse[T](implicit m: Manifest[T]) = withErrorResponse[T](0) + + def responseForCode(statusCode: Int): Option[(Manifest[_], ResponseState)] = responses.get(statusCode) orElse responses.get(0) + + def withoutBody() = copy[U](bodyParam = None) + + def withBody(body: Any) = copy[U](bodyParam = Some(body)) + + def withFormParam(name: String, value: Any) = copy[U](formParams = formParams + (name -> value)) + + def withPathParam(name: String, value: Any) = copy[U](pathParams = pathParams + (name -> value)) + + def withQueryParam(name: String, value: Any) = copy[U](queryParams = queryParams + (name -> value)) + + def withHeaderParam(name: String, value: Any) = copy[U](headerParams = headerParams + (name -> value)) +} diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiSettings.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiSettings.scala new file mode 100644 index 00000000000..3162fb9f6be --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiSettings.scala @@ -0,0 +1,32 @@ +package io.swagger.client.core + +import java.util.concurrent.TimeUnit + +import akka.actor.{ExtendedActorSystem, Extension, ExtensionKey} +import com.typesafe.config.Config +import io.swagger.client.core.ApiInvoker.CustomStatusCode +import spray.http.HttpHeaders.RawHeader + +import scala.collection.JavaConversions._ +import scala.concurrent.duration.FiniteDuration + +class ApiSettings(config: Config) extends Extension { + def this(system: ExtendedActorSystem) = this(system.settings.config) + + private def cfg = config.getConfig("io.swagger.client.apiRequest") + + val alwaysTrustCertificates = cfg.getBoolean("trust-certificates") + val defaultHeaders = cfg.getConfig("default-headers").entrySet.toList.map(c => RawHeader(c.getKey, c.getValue.render)) + val connectionTimeout = FiniteDuration(cfg.getDuration("connection-timeout", TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS) + val compressionEnabled = cfg.getBoolean("compression.enabled") + val compressionSizeThreshold = cfg.getBytes("compression.size-threshold").toInt + val customCodes = cfg.getConfigList("custom-codes").toList.map { c => CustomStatusCode( + c.getInt("code"), + c.getString("reason"), + c.getBoolean("success")) + } + + +} + +object ApiSettings extends ExtensionKey[ApiSettings] diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/requests.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/requests.scala new file mode 100644 index 00000000000..a096a994ea3 --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/requests.scala @@ -0,0 +1,166 @@ +package io.swagger.client.core + +import java.io.File +import java.net.URLEncoder +import scala.util.Try + +sealed trait ApiReturnWithHeaders { + def headers: Map[String, String] + def header(name: String): Option[String] = headers.get(name) + def getStringHeader(name: String) = header(name) + def getIntHeader(name: String) = castedHeader(name, java.lang.Integer.parseInt) + def getLongHeader(name: String) = castedHeader(name, java.lang.Long.parseLong) + def getFloatHeader(name: String) = castedHeader(name, java.lang.Float.parseFloat) + def getDoubleHeader(name: String) = castedHeader(name, java.lang.Double.parseDouble) + def getBooleanHeader(name: String) = castedHeader(name, java.lang.Boolean.parseBoolean) + private def castedHeader[U](name: String, conversion: String => U): Option[U] = { Try { header(name).map( conversion ) }.get } +} + +sealed case class ApiResponse[T](code: Int, content: T, headers: Map[String, String] = Map.empty) + extends ApiReturnWithHeaders + +sealed case class ApiError[T](code: Int, message: String, responseContent: Option[T], cause: Throwable = null, headers: Map[String, String] = Map.empty) + extends Throwable(s"($code) $message.${responseContent.map(s => s" Content : $s").getOrElse("")}", cause) + with ApiReturnWithHeaders + +sealed case class ApiMethod(value: String) + +object ApiMethods { + val CONNECT = ApiMethod("CONNECT") + val DELETE = ApiMethod("DELETE") + val GET = ApiMethod("GET") + val HEAD = ApiMethod("HEAD") + val OPTIONS = ApiMethod("OPTIONS") + val PATCH = ApiMethod("PATCH") + val POST = ApiMethod("POST") + val PUT = ApiMethod("PUT") + val TRACE = ApiMethod("TRACE") +} + +/** + * This trait needs to be added to any model defined by the api. + */ +trait ApiModel + +/** + * Single trait defining a credential that can be transformed to a paramName / paramValue tupple + */ +sealed trait Credentials { + def asQueryParam: Option[(String, String)] = None +} + +sealed case class BasicCredentials(user: String, password: String) extends Credentials + +sealed case class ApiKeyCredentials(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) extends Credentials { + override def asQueryParam: Option[(String, String)] = location match { + case ApiKeyLocations.QUERY => Some((keyName, key.value)) + case _ => None + } +} + +sealed case class ApiKeyValue(value: String) + +sealed trait ApiKeyLocation + +object ApiKeyLocations { + + case object QUERY extends ApiKeyLocation + + case object HEADER extends ApiKeyLocation +} + + +/** + * Case class used to unapply numeric values only in pattern matching + * @param value the string representation of the numeric value + */ +sealed case class NumericValue(value: String) { + override def toString = value +} + +object NumericValue { + def unapply(n: Any): Option[NumericValue] = n match { + case (_: Int | _: Long | _: Float | _: Double | _: Boolean | _: Byte) => Some(NumericValue(String.valueOf(n))) + case _ => None + } +} + +/** + * Used for params being arrays + */ +sealed case class ArrayValues(values: Seq[Any], format: CollectionFormat = CollectionFormats.CSV) + +object ArrayValues { + def apply(values: Option[Seq[Any]], format: CollectionFormat): ArrayValues = + ArrayValues(values.getOrElse(Seq.empty), format) + + def apply(values: Option[Seq[Any]]): ArrayValues = ArrayValues(values, CollectionFormats.CSV) +} + + +/** + * Defines how arrays should be rendered in query strings. + */ +sealed trait CollectionFormat + +trait MergedArrayFormat extends CollectionFormat { + def separator: String +} + +object CollectionFormats { + + case object CSV extends MergedArrayFormat { + override val separator = "," + } + + case object TSV extends MergedArrayFormat { + override val separator = "\t" + } + + case object SSV extends MergedArrayFormat { + override val separator = " " + } + + case object PIPES extends MergedArrayFormat { + override val separator = "|" + } + + case object MULTI extends CollectionFormat + +} + +object ParametersMap { + + /** + * Pimp parameters maps (Map[String, Any]) in order to transform them in a sequence of String -> Any tupples, + * with valid url-encoding, arrays handling, files preservation, ... + */ + implicit class ParametersMapImprovements(val m: Map[String, Any]) { + + def asFormattedParamsList = m.toList.flatMap(formattedParams) + + def asFormattedParams = m.flatMap(formattedParams) + + private def urlEncode(v: Any) = URLEncoder.encode(String.valueOf(v), "utf-8").replaceAll("\\+", "%20") + + private def formattedParams(tuple: (String, Any)): Seq[(String, Any)] = formattedParams(tuple._1, tuple._2) + + private def formattedParams(name: String, value: Any): Seq[(String, Any)] = value match { + case arr: ArrayValues => + arr.format match { + case CollectionFormats.MULTI => arr.values.flatMap(formattedParams(name, _)) + case format: MergedArrayFormat => Seq((name, arr.values.mkString(format.separator))) + } + case None => Seq.empty + case Some(opt) => + formattedParams(name, opt) + case s: Seq[Any] => + formattedParams(name, ArrayValues(s)) + case v: String => Seq((name, urlEncode(v))) + case NumericValue(v) => Seq((name, urlEncode(v))) + case f: File => Seq((name, f)) + case m: ApiModel => Seq((name, m)) + } + + } +} diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Category.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Category.scala new file mode 100644 index 00000000000..af66bc14753 --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Category.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Category ( + id: Option[Long], + name: Option[String]) + extends ApiModel + + diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Order.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Order.scala new file mode 100644 index 00000000000..83a40fb55d3 --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Order.scala @@ -0,0 +1,29 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Order ( + id: Option[Long], + petId: Option[Long], + quantity: Option[Int], + shipDate: Option[DateTime], + /* Order Status */ + status: Option[OrderEnums.Status], + complete: Option[Boolean]) + extends ApiModel + +object OrderEnums { + + type Status = Status.Value + + object Status extends Enumeration { + val Placed = Value("placed") + val Approved = Value("approved") + val Delivered = Value("delivered") + } + + +} + diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Pet.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Pet.scala new file mode 100644 index 00000000000..8cd3c61cb60 --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Pet.scala @@ -0,0 +1,29 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Pet ( + id: Option[Long], + category: Option[Category], + name: String, + photoUrls: Seq[String], + tags: Option[Seq[Tag]], + /* pet status in the store */ + status: Option[PetEnums.Status]) + extends ApiModel + +object PetEnums { + + type Status = Status.Value + + object Status extends Enumeration { + val Available = Value("available") + val Pending = Value("pending") + val Sold = Value("sold") + } + + +} + diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Tag.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Tag.scala new file mode 100644 index 00000000000..58aabadabe0 --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Tag.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Tag ( + id: Option[Long], + name: Option[String]) + extends ApiModel + + diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/User.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/User.scala new file mode 100644 index 00000000000..dd0bce1d8a7 --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/User.scala @@ -0,0 +1,19 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class User ( + id: Option[Long], + username: Option[String], + firstName: Option[String], + lastName: Option[String], + email: Option[String], + password: Option[String], + phone: Option[String], + /* User Status */ + userStatus: Option[Int]) + extends ApiModel + + diff --git a/samples/client/petstore/android-java/build.gradle b/samples/client/petstore/android-java/build.gradle index 80c0d375ddb..26a00d90da8 100644 --- a/samples/client/petstore/android-java/build.gradle +++ b/samples/client/petstore/android-java/build.gradle @@ -1,9 +1,15 @@ +group = 'io.swagger' +project.version = '1.0.0' + buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.2.2' + + classpath 'com.github.dcendents:android-maven-plugin:1.2' + } } @@ -13,7 +19,9 @@ allprojects { } } + apply plugin: 'com.android.library' +apply plugin: 'com.github.dcendents.android-maven' android { compileSdkVersion 22 @@ -22,6 +30,17 @@ android { minSdkVersion 14 targetSdkVersion 22 } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } } @@ -37,7 +56,12 @@ dependencies { compile "com.google.code.gson:gson:$gson_version" compile "org.apache.httpcomponents:httpcore:$httpclient_version" compile "org.apache.httpcomponents:httpclient:$httpclient_version" - compile "org.apache.httpcomponents:httpmime:$httpclient_version" + compile ("org.apache.httpcomponents:httpcore:$httpcore_version") { + exclude(group: 'org.apache.httpcomponents', module: 'httpclient') + } + compile ("org.apache.httpcomponents:httpmime:$httpmime_version") { + exclude(group: 'org.apache.httpcomponents', module: 'httpclient') + } testCompile "junit:junit:$junit_version" } @@ -48,7 +72,16 @@ afterEvaluate { task.dependsOn variant.javaCompile task.from variant.javaCompile.destinationDir task.destinationDir = project.file("${project.buildDir}/outputs/jar") - task.archiveName = "${project.name}-${variant.baseName}.jar" + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" artifacts.add('archives', task); } -} \ No newline at end of file +} + +task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' +} + +artifacts { + archives sourcesJar +} diff --git a/samples/client/petstore/android-java/settings.gradle b/samples/client/petstore/android-java/settings.gradle new file mode 100644 index 00000000000..6a6796bf9fe --- /dev/null +++ b/samples/client/petstore/android-java/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-android-client" \ No newline at end of file diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java index 88fdfdb6980..ebf600d787e 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java @@ -63,7 +63,7 @@ public class PetApi { String[] contentTypes = { - "application/json","application/xml", + "application/json","application/xml" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -117,7 +117,7 @@ public class PetApi { String[] contentTypes = { - "application/json","application/xml", + "application/json","application/xml" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -349,7 +349,7 @@ public class PetApi { String[] contentTypes = { - "application/x-www-form-urlencoded", + "application/x-www-form-urlencoded" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -481,7 +481,7 @@ public class PetApi { String[] contentTypes = { - "multipart/form-data", + "multipart/form-data" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; diff --git a/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/PetApiTest.java index 97f3b5f8006..e7fd31f2996 100644 --- a/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -100,11 +100,11 @@ public class PetApiTest { api.addPet(pet); Pet fetched = api.getPetById(pet.getId()); - + assertEquals("frank", fetched.getName()); + api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null); Pet updated = api.getPetById(fetched.getId()); - - assertEquals(updated.getName(), fetched.getName()); + assertEquals("furt", updated.getName()); } @Test @@ -152,4 +152,4 @@ public class PetApiTest { return pet; } -} \ No newline at end of file +} diff --git a/samples/client/petstore/csharp/compile.bat b/samples/client/petstore/csharp/compile.bat index 18a85febb70..1ced2568767 100644 --- a/samples/client/petstore/csharp/compile.bat +++ b/samples/client/petstore/csharp/compile.bat @@ -1,2 +1,2 @@ SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319 -%CSCPATH%\csc /reference:bin/Newtonsoft.Json.dll /target:library /out:bin/io.swagger.client.dll /recurse:src\*.cs /doc:bin/io.swagger.client.xml \ No newline at end of file +%CSCPATH%\csc /reference:bin/Newtonsoft.Json.dll /target:library /out:bin/IO.Swagger.Client.dll /recurse:src\*.cs /doc:bin/IO.Swagger.Client.xml \ No newline at end of file diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs index 4f20c0cba45..6a39ce7ba75 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs @@ -1,471 +1,336 @@ using System; using System.Collections.Generic; -using io.swagger.client; -using io.swagger.Model; +using RestSharp; +using IO.Swagger.Client; +using IO.Swagger.Model; -namespace io.swagger.Api { +namespace IO.Swagger.Api { public class PetApi { string basePath; - private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); + protected RestClient restClient; public PetApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; + this.restClient = new RestClient(basePath); } - public ApiInvoker getInvoker() { - return apiInvoker; - } - - // Sets the endpoint base url for the services being accessed - public void setBasePath(string basePath) { + /// + /// Sets the endpoint base url for the services being accessed + /// + /// Base URL + /// + public void SetBasePath(string basePath) { this.basePath = basePath; } - // Gets the endpoint base url for the services being accessed - public String getBasePath() { - return basePath; + /// + /// Gets the endpoint base url for the services being accessed + /// Base URL + /// + public String GetBasePath() { + return this.basePath; } - + /// /// Update an existing pet /// /// Pet object that needs to be added to the store - /// - public void UpdatePet (Pet Body) { - // create path and map variables - var path = "/pet".Replace("{format}","json"); + public void UpdatePet (Pet Body) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet", Method.PUT); - - - - - - - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, Body, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } + + _request.AddUrlSegment("format", "json"); // set format to json by default + + + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter + + + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.Content); + } + + return; } - + /// /// Add a new pet to the store /// /// Pet object that needs to be added to the store - /// - public void AddPet (Pet Body) { - // create path and map variables - var path = "/pet".Replace("{format}","json"); + public void AddPet (Pet Body) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet", Method.POST); - - - - - - - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "POST", queryParams, Body, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } + + _request.AddUrlSegment("format", "json"); // set format to json by default + + + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter + + + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.Content); + } + + return; } - + /// /// Finds Pets by status Multiple status values can be provided with comma seperated strings /// /// Status values that need to be considered for filter - - /// - public List FindPetsByStatus (List Status) { - // create path and map variables - var path = "/pet/findByStatus".Replace("{format}","json"); + /// List + public List FindPetsByStatus (List Status) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet/findByStatus", Method.GET); - if (Status != null){ - queryParams.Add("status", apiInvoker.ParameterToString(Status)); + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } + + _request.AddUrlSegment("format", "json"); // set format to json by default + + if (Status != null) _request.AddParameter("status", ApiInvoker.ParameterToString(Status)); // query parameter + + + - - - - - try { - if (typeof(List) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as List; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (List) ApiInvoker.deserialize(response, typeof(List)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.Content); } + return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); } - + /// /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// Tags to filter by - - /// - public List FindPetsByTags (List Tags) { - // create path and map variables - var path = "/pet/findByTags".Replace("{format}","json"); + /// List + public List FindPetsByTags (List Tags) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet/findByTags", Method.GET); - if (Tags != null){ - queryParams.Add("tags", apiInvoker.ParameterToString(Tags)); + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } + + _request.AddUrlSegment("format", "json"); // set format to json by default + + if (Tags != null) _request.AddParameter("tags", ApiInvoker.ParameterToString(Tags)); // query parameter + + + - - - - - try { - if (typeof(List) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as List; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (List) ApiInvoker.deserialize(response, typeof(List)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.Content); } + return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); } - + /// /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// /// ID of pet that needs to be fetched - - /// - public Pet GetPetById (long? PetId) { - // create path and map variables - var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.ParameterToString(PetId)); + /// Pet + public Pet GetPetById (long? PetId) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet/{petId}", Method.GET); - + // verify the required parameter 'PetId' is set + if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling GetPetById"); - - - - - try { - if (typeof(Pet) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as Pet; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (Pet) ApiInvoker.deserialize(response, typeof(Pet)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } + + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter + + + + + + + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.Content); + } + return (Pet) ApiInvoker.Deserialize(response.Content, typeof(Pet)); } - + /// /// Updates a pet in the store with form data /// /// ID of pet that needs to be updated - /// Updated name of the pet - /// Updated status of the pet - + /// Updated name of the pet + /// Updated status of the pet /// - public void UpdatePetWithForm (string PetId, string Name, string Status) { - // create path and map variables - var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.ParameterToString(PetId)); + public void UpdatePetWithForm (string PetId, string Name, string Status) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet/{petId}", Method.POST); - + // verify the required parameter 'PetId' is set + if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling UpdatePetWithForm"); - - - if (Name != null){ - if(Name is byte[]) { - formParams.Add("name", Name); - } else { - formParams.Add("name", apiInvoker.ParameterToString(Name)); - } + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } - if (Status != null){ - if(Status is byte[]) { - formParams.Add("status", Status); - } else { - formParams.Add("status", apiInvoker.ParameterToString(Status)); - } + + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter + + + + if (Name != null) _request.AddParameter("name", ApiInvoker.ParameterToString(Name)); // form parameter + if (Status != null) _request.AddParameter("status", ApiInvoker.ParameterToString(Status)); // form parameter + + + + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.Content); } - - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "POST", queryParams, null, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } - } + return; } - + /// /// Deletes a pet /// /// - /// Pet id to delete - + /// Pet id to delete /// - public void DeletePet (string ApiKey, long? PetId) { - // create path and map variables - var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.ParameterToString(PetId)); + public void DeletePet (string ApiKey, long? PetId) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet/{petId}", Method.DELETE); - + // verify the required parameter 'PetId' is set + if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling DeletePet"); - headerParams.Add("api_key", apiInvoker.ParameterToString(ApiKey)); - - - - - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } + + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter + + + if (ApiKey != null) _request.AddHeader("api_key", ApiInvoker.ParameterToString(ApiKey)); // header parameter + + + + + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.Content); + } + + return; } - + /// /// uploads an image /// /// ID of pet to update - /// Additional data to pass to server - /// file to upload - + /// Additional data to pass to server + /// file to upload /// - public void UploadFile (long? PetId, string AdditionalMetadata, byte[] File) { - // create path and map variables - var path = "/pet/{petId}/uploadImage".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.ParameterToString(PetId)); + public void UploadFile (long? PetId, string AdditionalMetadata, string File) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet/{petId}/uploadImage", Method.POST); - + // verify the required parameter 'PetId' is set + if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling UploadFile"); - - - if (AdditionalMetadata != null){ - if(AdditionalMetadata is byte[]) { - formParams.Add("additionalMetadata", AdditionalMetadata); - } else { - formParams.Add("additionalMetadata", apiInvoker.ParameterToString(AdditionalMetadata)); - } + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } - if (File != null){ - if(File is byte[]) { - formParams.Add("file", File); - } else { - formParams.Add("file", apiInvoker.ParameterToString(File)); - } + + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter + + + + if (AdditionalMetadata != null) _request.AddParameter("additionalMetadata", ApiInvoker.ParameterToString(AdditionalMetadata)); // form parameter + if (File != null) _request.AddFile("file", File); + + + + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.Content); } - - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "POST", queryParams, null, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } - } + return; } } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs index 2514539e298..5b4236c7a77 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs @@ -1,238 +1,178 @@ using System; using System.Collections.Generic; -using io.swagger.client; -using io.swagger.Model; +using RestSharp; +using IO.Swagger.Client; +using IO.Swagger.Model; -namespace io.swagger.Api { +namespace IO.Swagger.Api { public class StoreApi { string basePath; - private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); + protected RestClient restClient; public StoreApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; + this.restClient = new RestClient(basePath); } - public ApiInvoker getInvoker() { - return apiInvoker; - } - - // Sets the endpoint base url for the services being accessed - public void setBasePath(string basePath) { + /// + /// Sets the endpoint base url for the services being accessed + /// + /// Base URL + /// + public void SetBasePath(string basePath) { this.basePath = basePath; } - // Gets the endpoint base url for the services being accessed - public String getBasePath() { - return basePath; + /// + /// Gets the endpoint base url for the services being accessed + /// Base URL + /// + public String GetBasePath() { + return this.basePath; } - + /// /// Returns pet inventories by status Returns a map of status codes to quantities /// - - /// - public Dictionary GetInventory () { - // create path and map variables - var path = "/store/inventory".Replace("{format}","json"); + /// Dictionary + public Dictionary GetInventory () { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/store/inventory", Method.GET); - - - - - - - try { - if (typeof(Dictionary) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as Dictionary; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (Dictionary) ApiInvoker.deserialize(response, typeof(Dictionary)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } + + _request.AddUrlSegment("format", "json"); // set format to json by default + + + + + + + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content); + } + return (Dictionary) ApiInvoker.Deserialize(response.Content, typeof(Dictionary)); } - + /// /// Place an order for a pet /// /// order placed for purchasing the pet - - /// - public Order PlaceOrder (Order Body) { - // create path and map variables - var path = "/store/order".Replace("{format}","json"); + /// Order + public Order PlaceOrder (Order Body) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/store/order", Method.POST); - - - - - - - try { - if (typeof(Order) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as Order; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, Body, headerParams, formParams); - if (response != null){ - return (Order) ApiInvoker.deserialize(response, typeof(Order)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } + + _request.AddUrlSegment("format", "json"); // set format to json by default + + + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter + + + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content); + } + return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); } - + /// /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions /// /// ID of pet that needs to be fetched - - /// - public Order GetOrderById (string OrderId) { - // create path and map variables - var path = "/store/order/{orderId}".Replace("{format}","json").Replace("{" + "orderId" + "}", apiInvoker.ParameterToString(OrderId)); + /// Order + public Order GetOrderById (string OrderId) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/store/order/{orderId}", Method.GET); - + // verify the required parameter 'OrderId' is set + if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling GetOrderById"); - - - - - try { - if (typeof(Order) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as Order; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (Order) ApiInvoker.deserialize(response, typeof(Order)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } + + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // path (url segment) parameter + + + + + + + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content); + } + return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); } - + /// /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors /// /// ID of the order that needs to be deleted - /// - public void DeleteOrder (string OrderId) { - // create path and map variables - var path = "/store/order/{orderId}".Replace("{format}","json").Replace("{" + "orderId" + "}", apiInvoker.ParameterToString(OrderId)); + public void DeleteOrder (string OrderId) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/store/order/{orderId}", Method.DELETE); - + // verify the required parameter 'OrderId' is set + if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling DeleteOrder"); - - - - - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } + + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // path (url segment) parameter + + + + + + + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content); + } + + return; } } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs index 4f1f4a1bf19..ff8f23a18b2 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs @@ -1,433 +1,326 @@ using System; using System.Collections.Generic; -using io.swagger.client; -using io.swagger.Model; +using RestSharp; +using IO.Swagger.Client; +using IO.Swagger.Model; -namespace io.swagger.Api { +namespace IO.Swagger.Api { public class UserApi { string basePath; - private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); + protected RestClient restClient; public UserApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; + this.restClient = new RestClient(basePath); } - public ApiInvoker getInvoker() { - return apiInvoker; - } - - // Sets the endpoint base url for the services being accessed - public void setBasePath(string basePath) { + /// + /// Sets the endpoint base url for the services being accessed + /// + /// Base URL + /// + public void SetBasePath(string basePath) { this.basePath = basePath; } - // Gets the endpoint base url for the services being accessed - public String getBasePath() { - return basePath; + /// + /// Gets the endpoint base url for the services being accessed + /// Base URL + /// + public String GetBasePath() { + return this.basePath; } - + /// /// Create user This can only be done by the logged in user. /// /// Created user object - /// - public void CreateUser (User Body) { - // create path and map variables - var path = "/user".Replace("{format}","json"); + public void CreateUser (User Body) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user", Method.POST); - - - - - - - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "POST", queryParams, Body, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } + + _request.AddUrlSegment("format", "json"); // set format to json by default + + + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter + + + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.Content); + } + + return; } - + /// /// Creates list of users with given input array /// /// List of user object - /// - public void CreateUsersWithArrayInput (List Body) { - // create path and map variables - var path = "/user/createWithArray".Replace("{format}","json"); + public void CreateUsersWithArrayInput (List Body) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/createWithArray", Method.POST); - - - - - - - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "POST", queryParams, Body, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } + + _request.AddUrlSegment("format", "json"); // set format to json by default + + + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter + + + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.Content); + } + + return; } - + /// /// Creates list of users with given input array /// /// List of user object - /// - public void CreateUsersWithListInput (List Body) { - // create path and map variables - var path = "/user/createWithList".Replace("{format}","json"); + public void CreateUsersWithListInput (List Body) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/createWithList", Method.POST); - - - - - - - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "POST", queryParams, Body, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } + + _request.AddUrlSegment("format", "json"); // set format to json by default + + + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter + + + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.Content); + } + + return; } - + /// /// Logs user into the system /// /// The user name for login - /// The password for login in clear text - - /// - public string LoginUser (string Username, string Password) { - // create path and map variables - var path = "/user/login".Replace("{format}","json"); + /// The password for login in clear text + /// string + public string LoginUser (string Username, string Password) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/login", Method.GET); - if (Username != null){ - queryParams.Add("username", apiInvoker.ParameterToString(Username)); + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } - if (Password != null){ - queryParams.Add("password", apiInvoker.ParameterToString(Password)); - } - - - - - - - try { - if (typeof(string) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as string; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (string) ApiInvoker.deserialize(response, typeof(string)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } + + _request.AddUrlSegment("format", "json"); // set format to json by default + + if (Username != null) _request.AddParameter("username", ApiInvoker.ParameterToString(Username)); // query parameter + if (Password != null) _request.AddParameter("password", ApiInvoker.ParameterToString(Password)); // query parameter + + + + + + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.Content); } + return (string) ApiInvoker.Deserialize(response.Content, typeof(string)); } - + /// /// Logs out current logged in user session /// - /// - public void LogoutUser () { - // create path and map variables - var path = "/user/logout".Replace("{format}","json"); + public void LogoutUser () { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/logout", Method.GET); - - - - - - - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } + + _request.AddUrlSegment("format", "json"); // set format to json by default + + + + + + + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.Content); + } + + return; } - + /// /// Get user by user name /// /// The name that needs to be fetched. Use user1 for testing. - - /// - public User GetUserByName (string Username) { - // create path and map variables - var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.ParameterToString(Username)); + /// User + public User GetUserByName (string Username) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/{username}", Method.GET); - + // verify the required parameter 'Username' is set + if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling GetUserByName"); - - - - - try { - if (typeof(User) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as User; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (User) ApiInvoker.deserialize(response, typeof(User)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } + + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter + + + + + + + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.Content); + } + return (User) ApiInvoker.Deserialize(response.Content, typeof(User)); } - + /// /// Updated user This can only be done by the logged in user. /// /// name that need to be deleted - /// Updated user object - + /// Updated user object /// - public void UpdateUser (string Username, User Body) { - // create path and map variables - var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.ParameterToString(Username)); + public void UpdateUser (string Username, User Body) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/{username}", Method.PUT); - + // verify the required parameter 'Username' is set + if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling UpdateUser"); - - - - - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, Body, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } + + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter + + + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter + + + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.Content); + } + + return; } - + /// /// Delete user This can only be done by the logged in user. /// /// The name that needs to be deleted - /// - public void DeleteUser (string Username) { - // create path and map variables - var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.ParameterToString(Username)); + public void DeleteUser (string Username) { - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/{username}", Method.DELETE); - + // verify the required parameter 'Username' is set + if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling DeleteUser"); - - - - - try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); } + + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter + + + + + + + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.Content); + } + + return; } } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs index bfe1c0c4be8..04867ca365f 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs @@ -2,21 +2,22 @@ using System; using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; -namespace io.swagger.Model { +namespace IO.Swagger.Model { + [DataContract] public class Category { - + [DataMember(Name="id", EmitDefaultValue=false)] public long? Id { get; set; } - + [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } - public override string ToString() { var sb = new StringBuilder(); sb.Append("class Category {\n"); @@ -31,4 +32,4 @@ namespace io.swagger.Model { } -} \ No newline at end of file +} diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs index 20a6d7367dd..cf773a7a150 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs @@ -2,42 +2,42 @@ using System; using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; -namespace io.swagger.Model { +namespace IO.Swagger.Model { + [DataContract] public class Order { - + [DataMember(Name="id", EmitDefaultValue=false)] public long? Id { get; set; } - + [DataMember(Name="petId", EmitDefaultValue=false)] public long? PetId { get; set; } - + [DataMember(Name="quantity", EmitDefaultValue=false)] public int? Quantity { get; set; } - + [DataMember(Name="shipDate", EmitDefaultValue=false)] public DateTime ShipDate { get; set; } - /* Order Status */ - + [DataMember(Name="status", EmitDefaultValue=false)] public string Status { get; set; } - + [DataMember(Name="complete", EmitDefaultValue=false)] public bool? Complete { get; set; } - public override string ToString() { var sb = new StringBuilder(); sb.Append("class Order {\n"); @@ -60,4 +60,4 @@ namespace io.swagger.Model { } -} \ No newline at end of file +} diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs index b0f3573b78c..41f4081d371 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs @@ -2,42 +2,42 @@ using System; using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; -namespace io.swagger.Model { +namespace IO.Swagger.Model { + [DataContract] public class Pet { - + [DataMember(Name="id", EmitDefaultValue=false)] public long? Id { get; set; } - + [DataMember(Name="category", EmitDefaultValue=false)] public Category Category { get; set; } - + [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } - + [DataMember(Name="photoUrls", EmitDefaultValue=false)] public List PhotoUrls { get; set; } - + [DataMember(Name="tags", EmitDefaultValue=false)] public List Tags { get; set; } - /* pet status in the store */ - + [DataMember(Name="status", EmitDefaultValue=false)] public string Status { get; set; } - public override string ToString() { var sb = new StringBuilder(); sb.Append("class Pet {\n"); @@ -60,4 +60,4 @@ namespace io.swagger.Model { } -} \ No newline at end of file +} diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs index 2fbf7070050..44b6ae29297 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs @@ -2,21 +2,22 @@ using System; using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; -namespace io.swagger.Model { +namespace IO.Swagger.Model { + [DataContract] public class Tag { - + [DataMember(Name="id", EmitDefaultValue=false)] public long? Id { get; set; } - + [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } - public override string ToString() { var sb = new StringBuilder(); sb.Append("class Tag {\n"); @@ -31,4 +32,4 @@ namespace io.swagger.Model { } -} \ No newline at end of file +} diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs index 146ba13c768..0fb3bfc86ce 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs @@ -2,52 +2,52 @@ using System; using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; -namespace io.swagger.Model { +namespace IO.Swagger.Model { + [DataContract] public class User { - + [DataMember(Name="id", EmitDefaultValue=false)] public long? Id { get; set; } - + [DataMember(Name="username", EmitDefaultValue=false)] public string Username { get; set; } - + [DataMember(Name="firstName", EmitDefaultValue=false)] public string FirstName { get; set; } - + [DataMember(Name="lastName", EmitDefaultValue=false)] public string LastName { get; set; } - + [DataMember(Name="email", EmitDefaultValue=false)] public string Email { get; set; } - + [DataMember(Name="password", EmitDefaultValue=false)] public string Password { get; set; } - + [DataMember(Name="phone", EmitDefaultValue=false)] public string Phone { get; set; } - /* User Status */ - + [DataMember(Name="userStatus", EmitDefaultValue=false)] public int? UserStatus { get; set; } - public override string ToString() { var sb = new StringBuilder(); sb.Append("class User {\n"); @@ -74,4 +74,4 @@ namespace io.swagger.Model { } -} \ No newline at end of file +} diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs index 01648d1607c..7c4a7934681 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs @@ -1,21 +1,17 @@ using System; -namespace io.swagger.client { +namespace IO.Swagger.Client { + public class ApiException : Exception { - - private int errorCode = 0; + + public int ErrorCode { get; set; } public ApiException() {} - public int ErrorCode { - get - { - return errorCode; - } + public ApiException(int errorCode, string message) : base(message) { + this.ErrorCode = errorCode; } - public ApiException(int errorCode, string message) : base(message) { - this.errorCode = errorCode; - } } -} \ No newline at end of file + +} 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 ee2c5b1d889..144027b2314 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 @@ -1,235 +1,81 @@ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Net; - using System.Text; - using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using Newtonsoft.Json; - namespace io.swagger.client { - public class ApiInvoker { - private static readonly ApiInvoker _instance = new ApiInvoker(); - private Dictionary defaultHeaderMap = new Dictionary(); +namespace IO.Swagger.Client { + public class ApiInvoker { + private static Dictionary defaultHeaderMap = new Dictionary(); - public static ApiInvoker GetInstance() { - return _instance; - } + /// + /// Add default header + /// + /// Header field name + /// Header field value + /// + public static void AddDefaultHeader(string key, string value) { + defaultHeaderMap.Add(key, value); + } - /// - /// Add default header - /// - /// Header field name - /// Header field value - /// - public void addDefaultHeader(string key, string value) { - defaultHeaderMap.Add(key, value); - } + /// + /// Get default header + /// + /// Dictionary of default header + public static Dictionary GetDefaultHeader() { + return defaultHeaderMap; + } - /// - /// escape string (url-encoded) - /// - /// String to be escaped - /// Escaped string - public string escapeString(string str) { - return str; - } + /// + /// escape string (url-encoded) + /// + /// String to be escaped + /// Escaped string + public static string EscapeString(string str) { + return str; + } - /// - /// if parameter is DateTime, output in ISO8601 format, otherwise just return the string - /// - /// The parameter (header, path, query, form) - /// Formatted string - public string ParameterToString(object obj) + /// + /// if parameter is DateTime, output in ISO8601 format, otherwise just return the string + /// + /// The parameter (header, path, query, form) + /// Formatted string + public static string ParameterToString(object obj) + { + return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : Convert.ToString (obj); + } + + /// + /// Deserialize the JSON string into a proper object + /// + /// JSON string + /// Object type + /// Object representation of the JSON string + public static object Deserialize(string json, Type type) { + try { - return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : Convert.ToString (obj); + return JsonConvert.DeserializeObject(json, type); } - - /// - /// Deserialize the JSON string into a proper object - /// - /// JSON string - /// Object type - /// Object representation of the JSON string - public static object deserialize(string json, Type type) { - try - { - return JsonConvert.DeserializeObject(json, type); - } - catch (IOException e) { - throw new ApiException(500, e.Message); - } - + catch (IOException e) { + throw new ApiException(500, e.Message); } + } - public static string serialize(object obj) { - try - { - return obj != null ? JsonConvert.SerializeObject(obj) : null; - } - catch (Exception e) { - throw new ApiException(500, e.Message); - } - } - - public string invokeAPI(string host, string path, string method, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) + /// + /// Serialize an object into JSON string + /// + /// Object + /// JSON string + public static string Serialize(object obj) { + try { - return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string; + return obj != null ? JsonConvert.SerializeObject(obj) : null; } - - public byte[] invokeBinaryAPI(string host, string path, string method, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) - { - return invokeAPIInternal(host, path, method, true, queryParams, body, headerParams, formParams) as byte[]; - } - - private object invokeAPIInternal(string host, string path, string method, bool binaryResponse, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) { - var b = new StringBuilder(); - - foreach (var queryParamItem in queryParams) - { - var value = queryParamItem.Value; - if (value == null) continue; - b.Append(b.ToString().Length == 0 ? "?" : "&"); - b.Append(escapeString(queryParamItem.Key)).Append("=").Append(escapeString(value)); - } - - var querystring = b.ToString(); - - host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host; - - var client = WebRequest.Create(host + path + querystring); - client.Method = method; - - byte[] formData = null; - if (formParams.Count > 0) - { - string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid()); - client.ContentType = "multipart/form-data; boundary=" + formDataBoundary; - formData = GetMultipartFormData(formParams, formDataBoundary); - client.ContentLength = formData.Length; - } - else - { - client.ContentType = "application/json"; - } - - foreach (var headerParamsItem in headerParams) - { - client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value); - } - foreach (var defaultHeaderMapItem in defaultHeaderMap.Where(defaultHeaderMapItem => !headerParams.ContainsKey(defaultHeaderMapItem.Key))) - { - client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value); - } - - switch (method) - { - case "GET": - break; - case "POST": - case "PATCH": - case "PUT": - case "DELETE": - using (Stream requestStream = client.GetRequestStream()) - { - if (formData != null) - { - requestStream.Write(formData, 0, formData.Length); - } - - var swRequestWriter = new StreamWriter(requestStream); - swRequestWriter.Write(serialize(body)); - swRequestWriter.Close(); - } - break; - default: - throw new ApiException(500, "unknown method type " + method); - } - - try - { - var webResponse = (HttpWebResponse)client.GetResponse(); - if (webResponse.StatusCode != HttpStatusCode.OK) - { - webResponse.Close(); - throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription); - } - - if (binaryResponse) - { - using (var memoryStream = new MemoryStream()) - { - webResponse.GetResponseStream().CopyTo(memoryStream); - return memoryStream.ToArray(); - } - } - else - { - using (var responseReader = new StreamReader(webResponse.GetResponseStream())) - { - var responseData = responseReader.ReadToEnd(); - return responseData; - } - } - } - catch(WebException ex) - { - var response = ex.Response as HttpWebResponse; - int statusCode = 0; - if (response != null) - { - statusCode = (int)response.StatusCode; - response.Close(); - } - throw new ApiException(statusCode, ex.Message); - } - } - - private static byte[] GetMultipartFormData(Dictionary postParameters, string boundary) - { - Stream formDataStream = new System.IO.MemoryStream(); - bool needsCLRF = false; - - foreach (var param in postParameters) - { - // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added. - // Skip it on the first parameter, add it to subsequent parameters. - if (needsCLRF) - formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n")); - - needsCLRF = true; - - if (param.Value is byte[]) - { - string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", - boundary, - param.Key, - "application/octet-stream"); - formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); - - // Write the file data directly to the Stream, rather than serializing it to a string. - formDataStream.Write((param.Value as byte[]), 0, (param.Value as byte[]).Length); - } - else - { - string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", - boundary, - param.Key, - param.Value); - formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); - } - } - - // Add the end of the request. Start with a newline - string footer = "\r\n--" + boundary + "--\r\n"; - formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer)); - - // Dump the Stream into a byte[] - formDataStream.Position = 0; - byte[] formData = new byte[formDataStream.Length]; - formDataStream.Read(formData, 0, formData.Length); - formDataStream.Close(); - - return formData; + catch (Exception e) { + throw new ApiException(500, e.Message); } } } +} diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java index b5d6bb70d79..10326d8a2d6 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java @@ -57,7 +57,7 @@ public class PetApi { String[] contentTypes = { - "application/json","application/xml", + "application/json","application/xml" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -107,7 +107,7 @@ public class PetApi { String[] contentTypes = { - "application/json","application/xml", + "application/json","application/xml" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -325,7 +325,7 @@ public class PetApi { String[] contentTypes = { - "application/x-www-form-urlencoded", + "application/x-www-form-urlencoded" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -449,7 +449,7 @@ public class PetApi { String[] contentTypes = { - "multipart/form-data", + "multipart/form-data" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj index c22d57fa0ac..a3f7b4cae6b 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj @@ -8,6 +8,8 @@ /* Begin PBXBuildFile section */ BA525648922D4C0E9F44D4F1 /* libPods.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 73DA4F1067C343C3962F1542 /* libPods.a */; }; + 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 */; }; EA66999C1811D2FA00A70D03 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA66999B1811D2FA00A70D03 /* CoreGraphics.framework */; }; EA66999E1811D2FA00A70D03 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA66999D1811D2FA00A70D03 /* UIKit.framework */; }; @@ -28,7 +30,6 @@ EAB26B0D1AC8DF78002F5C7A /* PetApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = EA6699C71811D2FB00A70D03 /* PetApiTest.m */; }; EAEA85E41811D3AE00F06E69 /* SWGApiClient.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85CD1811D3AE00F06E69 /* SWGApiClient.m */; }; EAEA85E51811D3AE00F06E69 /* SWGCategory.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85CF1811D3AE00F06E69 /* SWGCategory.m */; }; - EAEA85E61811D3AE00F06E69 /* SWGDate.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85D11811D3AE00F06E69 /* SWGDate.m */; }; EAEA85E71811D3AE00F06E69 /* SWGFile.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85D31811D3AE00F06E69 /* SWGFile.m */; }; EAEA85E81811D3AE00F06E69 /* SWGObject.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85D51811D3AE00F06E69 /* SWGObject.m */; }; EAEA85E91811D3AE00F06E69 /* SWGOrder.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85D71811D3AE00F06E69 /* SWGOrder.m */; }; @@ -54,6 +55,8 @@ /* 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 = ""; }; + 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 = ""; }; EA6699961811D2FA00A70D03 /* PetstoreClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = PetstoreClient.app; sourceTree = BUILT_PRODUCTS_DIR; }; EA6699991811D2FA00A70D03 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; @@ -84,8 +87,6 @@ EAEA85CD1811D3AE00F06E69 /* SWGApiClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGApiClient.m; sourceTree = ""; }; EAEA85CE1811D3AE00F06E69 /* SWGCategory.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGCategory.h; sourceTree = ""; }; EAEA85CF1811D3AE00F06E69 /* SWGCategory.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGCategory.m; sourceTree = ""; }; - EAEA85D01811D3AE00F06E69 /* SWGDate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGDate.h; sourceTree = ""; }; - EAEA85D11811D3AE00F06E69 /* SWGDate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGDate.m; sourceTree = ""; }; EAEA85D21811D3AE00F06E69 /* SWGFile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGFile.h; sourceTree = ""; }; EAEA85D31811D3AE00F06E69 /* SWGFile.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGFile.m; sourceTree = ""; }; EAEA85D41811D3AE00F06E69 /* SWGObject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGObject.h; sourceTree = ""; }; @@ -224,14 +225,14 @@ EAEA85CB1811D3AE00F06E69 /* client */ = { isa = PBXGroup; children = ( + CFD1B66E1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.h */, + CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */, EA8B8AA21AC6683700638FBB /* SWGQueryParamCollection.h */, EA8B8AA31AC6683700638FBB /* SWGQueryParamCollection.m */, EAEA85CC1811D3AE00F06E69 /* SWGApiClient.h */, EAEA85CD1811D3AE00F06E69 /* SWGApiClient.m */, EAEA85CE1811D3AE00F06E69 /* SWGCategory.h */, EAEA85CF1811D3AE00F06E69 /* SWGCategory.m */, - EAEA85D01811D3AE00F06E69 /* SWGDate.h */, - EAEA85D11811D3AE00F06E69 /* SWGDate.m */, EAEA85D21811D3AE00F06E69 /* SWGFile.h */, EAEA85D31811D3AE00F06E69 /* SWGFile.m */, EAEA85D41811D3AE00F06E69 /* SWGObject.h */, @@ -397,8 +398,8 @@ EAEA85EE1811D3AE00F06E69 /* SWGUser.m in Sources */, EAEA85EF1811D3AE00F06E69 /* SWGUserApi.m in Sources */, EAEA85EB1811D3AE00F06E69 /* SWGPetApi.m in Sources */, - EAEA85E61811D3AE00F06E69 /* SWGDate.m in Sources */, EA6699A61811D2FA00A70D03 /* main.m in Sources */, + CFD1B6701B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m in Sources */, EAEA85EA1811D3AE00F06E69 /* SWGPet.m in Sources */, EAEA85E41811D3AE00F06E69 /* SWGApiClient.m in Sources */, EAEA85EC1811D3AE00F06E69 /* SWGStoreApi.m in Sources */, @@ -414,6 +415,7 @@ buildActionMask = 2147483647; files = ( EAB26B0C1AC8DF78002F5C7A /* PetApiTest.h in Sources */, + CFD1B6711B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m in Sources */, EAB26B0D1AC8DF78002F5C7A /* PetApiTest.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/samples/client/petstore/objc/Podfile b/samples/client/petstore/objc/Podfile index 925e26812b9..9a1ad058940 100644 --- a/samples/client/petstore/objc/Podfile +++ b/samples/client/petstore/objc/Podfile @@ -2,3 +2,4 @@ platform :ios, '6.0' xcodeproj 'PetstoreClient/PetstoreClient.xcodeproj' pod 'AFNetworking', '~> 2.1' pod 'JSONModel', '~> 1.0' +pod 'ISO8601' diff --git a/samples/client/petstore/objc/Podfile.lock b/samples/client/petstore/objc/Podfile.lock index de949a0e238..fe43a2c80eb 100644 --- a/samples/client/petstore/objc/Podfile.lock +++ b/samples/client/petstore/objc/Podfile.lock @@ -1,33 +1,36 @@ PODS: - - AFNetworking (2.5.1): - - AFNetworking/NSURLConnection (= 2.5.1) - - AFNetworking/NSURLSession (= 2.5.1) - - AFNetworking/Reachability (= 2.5.1) - - AFNetworking/Security (= 2.5.1) - - AFNetworking/Serialization (= 2.5.1) - - AFNetworking/UIKit (= 2.5.1) - - AFNetworking/NSURLConnection (2.5.1): + - 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/Reachability - AFNetworking/Security - AFNetworking/Serialization - - AFNetworking/NSURLSession (2.5.1): + - AFNetworking/NSURLSession (2.5.3): - AFNetworking/Reachability - AFNetworking/Security - AFNetworking/Serialization - - AFNetworking/Reachability (2.5.1) - - AFNetworking/Security (2.5.1) - - AFNetworking/Serialization (2.5.1) - - AFNetworking/UIKit (2.5.1): + - AFNetworking/Reachability (2.5.3) + - AFNetworking/Security (2.5.3) + - AFNetworking/Serialization (2.5.3) + - AFNetworking/UIKit (2.5.3): - AFNetworking/NSURLConnection - AFNetworking/NSURLSession - - JSONModel (1.0.2) + - ISO8601 (0.2.0) + - JSONModel (1.1.0) DEPENDENCIES: - AFNetworking (~> 2.1) + - ISO8601 - JSONModel (~> 1.0) SPEC CHECKSUMS: - AFNetworking: 10e85a00bb0f475124e4ff2677bf15693b2c1523 - JSONModel: 6ffcb4ffa3659c9e9a2e5d45d6c7705bab187c03 + AFNetworking: e1d86c2a96bb5d2e7408da36149806706ee122fe + ISO8601: 962282de75074c38bbfaa7b133b0e743ed6deb8d + JSONModel: ec77e9865236a7a09d9cf7668df6b4b328d9ec1d COCOAPODS: 0.36.0 diff --git a/samples/client/petstore/objc/client/JSONValueTransformer+ISO8601.h b/samples/client/petstore/objc/client/JSONValueTransformer+ISO8601.h new file mode 100644 index 00000000000..832f485f4f0 --- /dev/null +++ b/samples/client/petstore/objc/client/JSONValueTransformer+ISO8601.h @@ -0,0 +1,6 @@ +#import +#import +#import + +@interface JSONValueTransformer (ISO8601) +@end diff --git a/samples/client/petstore/objc/client/JSONValueTransformer+ISO8601.m b/samples/client/petstore/objc/client/JSONValueTransformer+ISO8601.m new file mode 100644 index 00000000000..cec8bdeea27 --- /dev/null +++ b/samples/client/petstore/objc/client/JSONValueTransformer+ISO8601.m @@ -0,0 +1,10 @@ +#import "JSONValueTransformer+ISO8601.h" + +@implementation JSONValueTransformer (ISO8601) + +- (NSDate *) NSDateFromNSString:(NSString *)string +{ + return [NSDate dateWithISO8601String:string]; +} + +@end diff --git a/samples/client/petstore/objc/client/SWGDate.h b/samples/client/petstore/objc/client/SWGDate.h deleted file mode 100644 index 2c6c7cfe01b..00000000000 --- a/samples/client/petstore/objc/client/SWGDate.h +++ /dev/null @@ -1,12 +0,0 @@ -#import -#import "SWGObject.h" - -@interface SWGDate : SWGObject { -@private - NSDate *_date; -} -@property(nonatomic, readonly) NSDate* date; - -- (id) initWithValues: (NSString*)input; --(NSString*) toString; -@end \ No newline at end of file diff --git a/samples/client/petstore/objc/client/SWGDate.m b/samples/client/petstore/objc/client/SWGDate.m deleted file mode 100644 index 07a1405626b..00000000000 --- a/samples/client/petstore/objc/client/SWGDate.m +++ /dev/null @@ -1,34 +0,0 @@ -#import "SWGDate.h" - -@implementation SWGDate - -@synthesize date = _date; - -- (id) initWithValues:(NSString*)input { - if([input isKindOfClass:[NSString class]]){ - NSDateFormatter* df = [NSDateFormatter new]; - NSLocale *locale = [[NSLocale new] - initWithLocaleIdentifier:@"en_US_POSIX"]; - [df setLocale:locale]; - [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"]; - - _date = [df dateFromString:input]; - } - else if([input isKindOfClass:[NSNumber class]]) { - NSTimeInterval interval = [input doubleValue]; - _date = [[NSDate alloc] initWithTimeIntervalSince1970:interval]; - } - return self; -} - --(NSString*) toString { - NSDateFormatter* df = [NSDateFormatter new]; - NSLocale *locale = [[NSLocale new] - initWithLocaleIdentifier:@"en_US_POSIX"]; - [df setLocale:locale]; - [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"]; - - return [df stringFromDate:_date]; -} - -@end \ No newline at end of file diff --git a/samples/client/petstore/objc/client/SWGPetApi.m b/samples/client/petstore/objc/client/SWGPetApi.m index 5b34337af07..2589241dbe4 100644 --- a/samples/client/petstore/objc/client/SWGPetApi.m +++ b/samples/client/petstore/objc/client/SWGPetApi.m @@ -67,6 +67,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet", basePath]; // remove format in URL if needed @@ -162,6 +164,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet", basePath]; // remove format in URL if needed @@ -170,6 +174,15 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; +<<<<<<< HEAD +======= + 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"; + +>>>>>>> develop_2.0 NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; @@ -257,6 +270,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/findByStatus", basePath]; // remove format in URL if needed @@ -348,6 +363,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/findByTags", basePath]; // remove format in URL if needed @@ -439,6 +456,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock { + + // verify the required parameter 'petId' is set + NSAssert(petId != nil, @"Missing the required parameter `petId` when calling getPetById"); + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; // remove format in URL if needed @@ -538,6 +560,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + // verify the required parameter 'petId' is set + NSAssert(petId != nil, @"Missing the required parameter `petId` when calling updatePetWithForm"); + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; // remove format in URL if needed @@ -547,6 +574,15 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; +<<<<<<< HEAD +======= + 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"; + +>>>>>>> develop_2.0 NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; @@ -629,6 +665,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + // verify the required parameter 'petId' is set + NSAssert(petId != nil, @"Missing the required parameter `petId` when calling deletePet"); + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; // remove format in URL if needed @@ -708,6 +749,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + // verify the required parameter 'petId' is set + NSAssert(petId != nil, @"Missing the required parameter `petId` when calling uploadFile"); + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}/uploadImage", basePath]; // remove format in URL if needed @@ -717,6 +763,15 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; +<<<<<<< HEAD +======= + 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"; + +>>>>>>> develop_2.0 NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; diff --git a/samples/client/petstore/objc/client/SWGStoreApi.m b/samples/client/petstore/objc/client/SWGStoreApi.m index c3870cbe51f..e4ac4f4e8c0 100644 --- a/samples/client/petstore/objc/client/SWGStoreApi.m +++ b/samples/client/petstore/objc/client/SWGStoreApi.m @@ -64,6 +64,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; (void (^)(NSDictionary* output, NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/inventory", basePath]; // remove format in URL if needed @@ -142,6 +144,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order", basePath]; // remove format in URL if needed @@ -251,6 +255,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock { + + // verify the required parameter 'orderId' is set + NSAssert(orderId != nil, @"Missing the required parameter `orderId` when calling getOrderById"); + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath]; // remove format in URL if needed @@ -338,6 +347,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + // verify the required parameter 'orderId' is set + NSAssert(orderId != nil, @"Missing the required parameter `orderId` when calling deleteOrder"); + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath]; // remove format in URL if needed diff --git a/samples/client/petstore/objc/client/SWGUserApi.m b/samples/client/petstore/objc/client/SWGUserApi.m index 13c37b80023..30af7788af7 100644 --- a/samples/client/petstore/objc/client/SWGUserApi.m +++ b/samples/client/petstore/objc/client/SWGUserApi.m @@ -66,6 +66,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user", basePath]; // remove format in URL if needed @@ -161,6 +163,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/createWithArray", basePath]; // remove format in URL if needed @@ -256,6 +260,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/createWithList", basePath]; // remove format in URL if needed @@ -353,6 +359,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSString* output, NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/login", basePath]; // remove format in URL if needed @@ -443,6 +451,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; (void (^)(NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/logout", basePath]; // remove format in URL if needed @@ -515,6 +525,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock { + + // verify the required parameter 'username' is set + NSAssert(username != nil, @"Missing the required parameter `username` when calling getUserByName"); + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; // remove format in URL if needed @@ -604,6 +619,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + // verify the required parameter 'username' is set + NSAssert(username != nil, @"Missing the required parameter `username` when calling updateUser"); + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; // remove format in URL if needed @@ -700,6 +720,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + // verify the required parameter 'username' is set + NSAssert(username != nil, @"Missing the required parameter `username` when calling deleteUser"); + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; // remove format in URL if needed diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index d6d14c72527..85087520c8f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -24,6 +24,8 @@ class APIClient { public static $GET = "GET"; public static $PUT = "PUT"; public static $DELETE = "DELETE"; + + private static $default_header = array(); /* * @var string timeout (second) of the HTTP request, by default set to 0, no timeout @@ -36,37 +38,115 @@ class APIClient { protected $user_agent = "PHP-Swagger"; /** - * @param string $host the address of the API server - * @param string $headerName a header to pass on requests + * @param string $host Base url of the API server (optional) */ - function __construct($host, $headerName = null, $headerValue = null) { - $this->host = $host; - $this->headerName = $headerName; - $this->headerValue = $headerValue; + function __construct($host = null) { + if ($host == null) { + $this->host = 'http://petstore.swagger.io/v2'; + } else { + $this->host = $host; + } } /** - * Set the user agent of the API client + * add default header * - * @param string $user_agent The user agent of the API client + * @param string $header_name header name (e.g. Token) + * @param string $header_value header value (e.g. 1z8wp3) + */ + public function addDefaultHeader($header_name, $header_value) { + if (!is_string($header_name)) + throw new \InvalidArgumentException('Header name must be a string.'); + + self::$default_header[$header_name] = $header_value; + } + + /** + * get the default header + * + * @return array default header + */ + public function getDefaultHeader() { + return self::$default_header; + } + + /** + * delete the default header based on header name + * + * @param string $header_name header name (e.g. Token) + */ + public function deleteDefaultHeader($header_name) { + unset(self::$default_header[$header_name]); + } + + /** + * set the user agent of the api client + * + * @param string $user_agent the user agent of the api client */ public function setUserAgent($user_agent) { - if (!is_string($user_agent)) { - throw new Exception('User-agent must be a string.'); - } + if (!is_string($user_agent)) + throw new \InvalidArgumentException('User-agent must be a string.'); + $this->user_agent= $user_agent; } /** * @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 Exception('Timeout variable must be numeric.'); - } + if (!is_numeric($seconds)) + throw new \InvalidArgumentException('Timeout variable must be numeric.'); + $this->curl_timeout = $seconds; } + /** + * 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]) { + return Configuration::$apiKeyPrefix[$apiKey]." ".Configuration::$apiKey[$apiKey]; + } else { + return Configuration::$apiKey[$apiKey]; + } + } + + /** + * update hearder and query param based on authentication setting + * + * @param array $headerParams header parameters (by ref) + * @param array $queryParams query parameters (by ref) + * @param array $authSettings array of authentication scheme (e.g ['api_key']) + */ + public function updateParamsForAuth(&$headerParams, &$queryParams, $authSettings) + { + if (count($authSettings) == 0) + return; + + // one endpoint can have more than 1 auth settings + foreach($authSettings as $auth) { + // determine which one to use + switch($auth) { + + case 'api_key': + $headerParams['api_key'] = $this->getApiKeyWithPrefix('api_key'); + + break; + + case 'petstore_auth': + + //TODO support oauth + break; + + default: + //TODO show warning about security definition not found + } + } + } + /** * @param string $resourcePath path to method endpoint * @param string $method method to call @@ -76,23 +156,22 @@ class APIClient { * @return mixed */ public function callAPI($resourcePath, $method, $queryParams, $postData, - $headerParams) { + $headerParams, $authSettings) { $headers = array(); - # Allow API key from $headerParams to override default - $added_api_key = False; + # determine authentication setting + $this->updateParamsForAuth($headerParams, $queryParams, $authSettings); + + # construct the http header if ($headerParams != null) { + # add default header + $headerParams = array_merge((array)self::$default_header, $headerParams); + foreach ($headerParams as $key => $val) { $headers[] = "$key: $val"; - if ($key == $this->headerName) { - $added_api_key = True; - } } } - if (! $added_api_key && $this->headerName != null) { - $headers[] = $this->headerName . ": " . $this->headerValue; - } // form data if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { @@ -111,6 +190,7 @@ class APIClient { } // return the result on success, rather than just TRUE curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); if (! empty($queryParams)) { @@ -130,7 +210,7 @@ class APIClient { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); } else if ($method != self::$GET) { - throw new Exception('Method ' . $method . ' is not recognized.'); + throw new APIClientException('Method ' . $method . ' is not recognized.'); } curl_setopt($curl, CURLOPT_URL, $url); @@ -142,20 +222,21 @@ class APIClient { $response_info = curl_getinfo($curl); // Handle the response - if ($response === false) { // error, likely in the client side - throw new APIClientException("API Error ($url): ".curl_error($curl), 0, $response_info, $response); + if ($response_info['http_code'] == 0) { + throw new APIClientException("TIMEOUT: api call to " . $url . + " took more than 5s to return", 0, $response_info, $response); } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { $data = json_decode($response); if (json_last_error() > 0) { // if response is a string $data = $response; } - } else if ($response_info['http_code'] == 401) { // server returns 401 + } else if ($response_info['http_code'] == 401) { throw new APIClientException("Unauthorized API request to " . $url . ": " . serialize($response), 0, $response_info, $response); - } else if ($response_info['http_code'] == 404) { // server returns 404 + } else if ($response_info['http_code'] == 404) { $data = null; } else { - throw new APIClientException("Can't connect to the API: " . $url . + throw new APIClientException("Can't connect to the api: " . $url . " response code: " . $response_info['http_code'], 0, $response_info, $response); } @@ -260,7 +341,6 @@ class APIClient { * @param string $class class name is passed as a string * @return object an instance of $class */ - public static function deserialize($data, $class) { if (null === $data) { @@ -303,5 +383,37 @@ class APIClient { return $deserialized; } + /* + * return the header 'Accept' based on an array of Accept provided + * + * @param array[string] $accept Array of header + * @return string Accept (e.g. application/json) + */ + public static function selectHeaderAccept($accept) { + if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) { + return NULL; + } elseif (preg_grep("/application\/json/i", $accept)) { + return 'application/json'; + } else { + return implode(',', $accept); + } + } + + /* + * return the content type based on an array of content-type provided + * + * @param array[string] content_type_array Array fo content-type + * @return string Content-Type (e.g. application/json) + */ + public static function selectHeaderContentType($content_type) { + if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) { + return 'application/json'; + } elseif (preg_grep("/application\/json/i", $content_type)) { + return 'application/json'; + } else { + return implode(',', $content_type); + } + } + } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php new file mode 100644 index 00000000000..9426efa9170 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -0,0 +1,36 @@ +apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array('application/json','application/xml',); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml')); @@ -73,10 +72,13 @@ class PetApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array('petstore_auth'); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } @@ -100,12 +102,11 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array('application/json','application/xml',); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml')); @@ -125,10 +126,13 @@ class PetApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array('petstore_auth'); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } @@ -152,12 +156,11 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); // query params if($status !== null) { @@ -176,18 +179,20 @@ class PetApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array('petstore_auth'); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); if(! $response) { return null; } - $responseObject = $this->apiClient->deserialize($response, - 'array[Pet]'); - return $responseObject; + $responseObject = $this->apiClient->deserialize($response,'array[Pet]'); + return $responseObject; } /** @@ -209,12 +214,11 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); // query params if($tags !== null) { @@ -233,18 +237,20 @@ class PetApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array('petstore_auth'); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); if(! $response) { return null; } - $responseObject = $this->apiClient->deserialize($response, - 'array[Pet]'); - return $responseObject; + $responseObject = $this->apiClient->deserialize($response,'array[Pet]'); + return $responseObject; } /** @@ -259,7 +265,7 @@ class PetApi { // verify the required parameter 'pet_id' is set if ($pet_id === null) { - throw new \Exception("Missing the required parameter $pet_id when calling getPetById"); + throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetById'); } @@ -271,12 +277,11 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -296,18 +301,20 @@ class PetApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array('api_key', 'petstore_auth'); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); if(! $response) { return null; } - $responseObject = $this->apiClient->deserialize($response, - 'Pet'); - return $responseObject; + $responseObject = $this->apiClient->deserialize($response,'Pet'); + return $responseObject; } /** @@ -324,7 +331,7 @@ class PetApi { // verify the required parameter 'pet_id' is set if ($pet_id === null) { - throw new \Exception("Missing the required parameter $pet_id when calling updatePetWithForm"); + throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling updatePetWithForm'); } @@ -336,12 +343,11 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array('application/x-www-form-urlencoded',); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/x-www-form-urlencoded')); @@ -367,10 +373,13 @@ class PetApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array('petstore_auth'); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } @@ -388,7 +397,7 @@ class PetApi { // verify the required parameter 'pet_id' is set if ($pet_id === null) { - throw new \Exception("Missing the required parameter $pet_id when calling deletePet"); + throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling deletePet'); } @@ -400,12 +409,11 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); // header params @@ -428,10 +436,13 @@ class PetApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array('petstore_auth'); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } @@ -450,7 +461,7 @@ class PetApi { // verify the required parameter 'pet_id' is set if ($pet_id === null) { - throw new \Exception("Missing the required parameter $pet_id when calling uploadFile"); + throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling uploadFile'); } @@ -462,12 +473,11 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array('multipart/form-data',); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('multipart/form-data')); @@ -493,10 +503,13 @@ class PetApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array('petstore_auth'); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php index 78e23ec9034..609e6568ed4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php @@ -47,12 +47,11 @@ class StoreApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -68,18 +67,20 @@ class StoreApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array('api_key'); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); if(! $response) { return null; } - $responseObject = $this->apiClient->deserialize($response, - 'map[string,int]'); - return $responseObject; + $responseObject = $this->apiClient->deserialize($response,'map[string,int]'); + return $responseObject; } /** @@ -101,12 +102,11 @@ class StoreApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -126,18 +126,20 @@ class StoreApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); if(! $response) { return null; } - $responseObject = $this->apiClient->deserialize($response, - 'Order'); - return $responseObject; + $responseObject = $this->apiClient->deserialize($response,'Order'); + return $responseObject; } /** @@ -152,7 +154,7 @@ class StoreApi { // verify the required parameter 'order_id' is set if ($order_id === null) { - throw new \Exception("Missing the required parameter $order_id when calling getOrderById"); + throw new \InvalidArgumentException('Missing the required parameter $order_id when calling getOrderById'); } @@ -164,12 +166,11 @@ class StoreApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -189,18 +190,20 @@ class StoreApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); if(! $response) { return null; } - $responseObject = $this->apiClient->deserialize($response, - 'Order'); - return $responseObject; + $responseObject = $this->apiClient->deserialize($response,'Order'); + return $responseObject; } /** @@ -215,7 +218,7 @@ class StoreApi { // verify the required parameter 'order_id' is set if ($order_id === null) { - throw new \Exception("Missing the required parameter $order_id when calling deleteOrder"); + throw new \InvalidArgumentException('Missing the required parameter $order_id when calling deleteOrder'); } @@ -227,12 +230,11 @@ class StoreApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -252,10 +254,13 @@ class StoreApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php index a3ed8a8ab25..985ed22a40c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php @@ -48,12 +48,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -73,10 +72,13 @@ class UserApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } @@ -100,12 +102,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -125,10 +126,13 @@ class UserApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } @@ -152,12 +156,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -177,10 +180,13 @@ class UserApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } @@ -205,12 +211,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); // query params if($username !== null) { @@ -232,18 +237,20 @@ class UserApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); if(! $response) { return null; } - $responseObject = $this->apiClient->deserialize($response, - 'string'); - return $responseObject; + $responseObject = $this->apiClient->deserialize($response,'string'); + return $responseObject; } /** @@ -264,12 +271,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -285,10 +291,13 @@ class UserApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } @@ -305,7 +314,7 @@ class UserApi { // verify the required parameter 'username' is set if ($username === null) { - throw new \Exception("Missing the required parameter $username when calling getUserByName"); + throw new \InvalidArgumentException('Missing the required parameter $username when calling getUserByName'); } @@ -317,12 +326,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -342,18 +350,20 @@ class UserApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); if(! $response) { return null; } - $responseObject = $this->apiClient->deserialize($response, - 'User'); - return $responseObject; + $responseObject = $this->apiClient->deserialize($response,'User'); + return $responseObject; } /** @@ -369,7 +379,7 @@ class UserApi { // verify the required parameter 'username' is set if ($username === null) { - throw new \Exception("Missing the required parameter $username when calling updateUser"); + throw new \InvalidArgumentException('Missing the required parameter $username when calling updateUser'); } @@ -381,12 +391,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -410,10 +419,13 @@ class UserApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } @@ -430,7 +442,7 @@ class UserApi { // verify the required parameter 'username' is set if ($username === null) { - throw new \Exception("Missing the required parameter $username when calling deleteUser"); + throw new \InvalidArgumentException('Missing the required parameter $username when calling deleteUser'); } @@ -442,12 +454,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -467,10 +478,13 @@ class UserApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index d2d398ae140..bf941756fa6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -31,11 +31,37 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $add_response = $pet_api->addPet($new_pet); } + // test static functions defined in APIClient + public function testAPIClient() + { + # 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 + $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 + SwaggerClient\APIClient::addDefaultHeader('test1', 'value1'); + SwaggerClient\APIClient::addDefaultHeader('test2', 200); + $this->assertSame('value1', SwaggerClient\APIClient::getDefaultHeader()['test1']); + $this->assertSame(200, SwaggerClient\APIClient::getDefaultHeader()['test2']); + + # test deleteDefaultHeader + SwaggerClient\APIClient::deleteDefaultHeader('test2'); + $this->assertFalse(isset(SwaggerClient\APIClient::getDefaultHeader()['test2'])); + + } + // test getPetById with a Pet object (id 10005) public function testGetPetById() { - // initialize the API client - $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); + // initialize the API client without host + $api_client = new SwaggerClient\APIClient(); + SwaggerClient\Configuration::$apiKey['api_key'] = '111222333444555'; $pet_id = 10005; // ID of pet that needs to be fetched $pet_api = new SwaggerClient\PetAPI($api_client); // return Pet (model) @@ -77,7 +103,8 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // create updated pet object $updated_pet = new SwaggerClient\models\Pet; $updated_pet->id = $pet_id; - $updated_pet->status = "pending"; // new status + $updated_pet->name = 'updatePet'; // new name + $updated_pet->status = 'pending'; // new status // update Pet (model/json) $update_response = $pet_api->updatePet($updated_pet); // return nothing (void) @@ -86,6 +113,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $response = $pet_api->getPetById($pet_id); $this->assertSame($response->id, $pet_id); $this->assertSame($response->status, 'pending'); + $this->assertSame($response->name, 'updatePet'); } // test updatePet and verify by the "id" of the response @@ -96,15 +124,13 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $pet_id = 10001; // ID of pet that needs to be fetched $pet_api = new SwaggerClient\PetAPI($api_client); // update Pet (form) - $update_response = $pet_api->updatePetWithForm($pet_id, null, 'sold'); + $update_response = $pet_api->updatePetWithForm($pet_id, 'update pet with form', 'sold'); // return nothing (void) $this->assertSame($update_response, NULL); - // TODO commented out for the time being since it's broken - // https://github.com/swagger-api/swagger-codegen/issues/656 - // verify updated Pet - //$response = $pet_api->getPetById($pet_id); - //$this->assertSame($response->id, $pet_id); - //$this->assertSame($response->status, 'sold'); + $response = $pet_api->getPetById($pet_id); + $this->assertSame($response->id, $pet_id); + $this->assertSame($response->name, 'update pet with form'); + $this->assertSame($response->status, 'sold'); } // test addPet and verify by the "id" and "name" of the response diff --git a/samples/client/petstore/php/test.php b/samples/client/petstore/php/test.php index 7cbbfce3cbb..7d46d8b5821 100644 --- a/samples/client/petstore/php/test.php +++ b/samples/client/petstore/php/test.php @@ -4,6 +4,8 @@ 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"); + $petId = 10005; // ID of pet that needs to be fetched try { $pet_api = new SwaggerClient\PetAPI($api_client); diff --git a/samples/client/petstore/python/SwaggerPetstore-python/Makefile b/samples/client/petstore/python/SwaggerPetstore-python/Makefile new file mode 100644 index 00000000000..2811b735b54 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/Makefile @@ -0,0 +1,37 @@ +REQUIREMENTS_FILE=dev-requirements.txt +REQUIREMENTS_OUT=dev-requirements.txt.log +SETUP_OUT=*.egg-info + +virtualenv: +ifndef VIRTUAL_ENV + $(error Must be run inside of a virtualenv\ + http://docs.python-guide.org/en/latest/dev/virtualenvs/) +endif + +setup: virtualenv $(SETUP_OUT) + +$(SETUP_OUT): setup.py setup.cfg + python setup.py develop + touch $(SETUP_OUT) + +$(REQUIREMENTS_OUT): $(REQUIREMENTS_FILE) + pip install -r $(REQUIREMENTS_FILE) | tee -a $(REQUIREMENTS_OUT) + python setup.py develop + +clean: + rm -rf $(REQUIREMENTS_OUT) + rm -rf $(SETUP_OUT) + rm -rf .tox + rm -rf .coverage + find . -name "*.py[oc]" -delete + find . -name "__pycache__" -delete + +requirements: setup $(REQUIREMENTS_OUT) + +test: clean requirements + nosetests + +test-all: clean requirements + tox + + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/README.md b/samples/client/petstore/python/SwaggerPetstore-python/README.md index 3b69aba0f82..9c590a9a508 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/README.md +++ b/samples/client/petstore/python/SwaggerPetstore-python/README.md @@ -38,5 +38,37 @@ TODO ## Tests -TODO +(Make sure you are running it inside of a [virtualenv](http://docs.python-guide.org/en/latest/dev/virtualenvs/)) + +You can run the tests in the current python platform: + +```sh +$ make test +[... magically installs dependencies and runs tests on your virtualenv] +Ran 7 tests in 19.289s + +OK +``` +or + +``` +$ mvn integration-test -rf :PythonPetstoreClientTests +Using 2195432783 as seed +[INFO] ------------------------------------------------------------------------ +[INFO] BUILD SUCCESS +[INFO] ------------------------------------------------------------------------ +[INFO] Total time: 37.594 s +[INFO] Finished at: 2015-05-16T18:00:35+08:00 +[INFO] Final Memory: 11M/156M +[INFO] ------------------------------------------------------------------------ +``` +If you want to run the tests in all the python platforms: + +```sh +$ make test-all +[... tox creates a virtualenv for every platform and runs tests inside of each] + py27: commands succeeded + py34: commands succeeded + congratulations :) +``` diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py index 30d634bc4b3..9d4b2db3de5 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py @@ -1,34 +1,16 @@ -#!/usr/bin/env python -"""Add all of the modules in the current directory to __all__""" -import os - -# import models into package +from __future__ import absolute_import +# import models into sdk package from .models.user import User - from .models.category import Category - from .models.pet import Pet - from .models.tag import Tag - from .models.order import Order - -# import apis into package - -from .user_api import UserApi - -from .pet_api import PetApi - -from .store_api import StoreApi - +# import apis into sdk package +from .apis.user_api import UserApi +from .apis.pet_api import PetApi +from .apis.store_api import StoreApi # import ApiClient from .swagger import ApiClient - -__all__ = [] - -for module in os.listdir(os.path.dirname(__file__)): - if module != '__init__.py' and module[-3:] == '.py': - __all__.append(module[:-3]) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/__init__.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/__init__.py new file mode 100644 index 00000000000..128b25dad82 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/__init__.py @@ -0,0 +1,7 @@ +from __future__ import absolute_import + +# import apis into api package +from .user_api import UserApi +from .pet_api import PetApi +from .store_api import StoreApi + 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 new file mode 100644 index 00000000000..bf8a51d7ca2 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py @@ -0,0 +1,384 @@ +#!/usr/bin/env python +# coding: utf-8 + +""" +PetApi.py +Copyright 2015 Reverb Technologies, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +""" +from __future__ import absolute_import + +import sys +import os + +# python 2 and python 3 compatibility library +from six import iteritems + +from ..util import remove_none + +class PetApi(object): + + def __init__(self, api_client): + self.api_client = api_client + + def update_pet(self, **kwargs): + """ + Update an existing pet + + + :param Pet body: Pet object that needs to be added to the store + + :return: None + """ + + all_params = ['body'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method update_pet" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/pet'.replace('{format}', 'json') + method = 'PUT' + + path_params = remove_none(dict()) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) + body_params = params.get('body') + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = ['application/json', 'application/xml'] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + def add_pet(self, **kwargs): + """ + Add a new pet to the store + + + :param Pet body: Pet object that needs to be added to the store + + :return: None + """ + + all_params = ['body'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method add_pet" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/pet'.replace('{format}', 'json') + method = 'POST' + + path_params = remove_none(dict()) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) + body_params = params.get('body') + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = ['application/json', 'application/xml'] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + def find_pets_by_status(self, **kwargs): + """ + Finds Pets by status + Multiple status values can be provided with comma seperated strings + + :param list[str] status: Status values that need to be considered for filter + + :return: list[Pet] + """ + + all_params = ['status'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method find_pets_by_status" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/pet/findByStatus'.replace('{format}', 'json') + method = 'GET' + + path_params = remove_none(dict()) + query_params = remove_none(dict(status=params.get('status'))) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response='list[Pet]') + + return response + + def find_pets_by_tags(self, **kwargs): + """ + Finds Pets by tags + Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + + :param list[str] tags: Tags to filter by + + :return: list[Pet] + """ + + all_params = ['tags'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method find_pets_by_tags" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/pet/findByTags'.replace('{format}', 'json') + method = 'GET' + + path_params = remove_none(dict()) + query_params = remove_none(dict(tags=params.get('tags'))) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response='list[Pet]') + + return response + + def get_pet_by_id(self, pet_id, **kwargs): + """ + Find pet by ID + Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + + :param int pet_id: ID of pet that needs to be fetched (required) + + :return: Pet + """ + + # verify the required parameter 'pet_id' is set + if pet_id is None: + raise ValueError("Missing the required parameter `pet_id` when calling `get_pet_by_id`") + + all_params = ['pet_id'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method get_pet_by_id" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/pet/{petId}'.replace('{format}', 'json') + method = 'GET' + + path_params = remove_none(dict(petId=params.get('pet_id'))) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response='Pet') + + return response + + def update_pet_with_form(self, pet_id, **kwargs): + """ + Updates a pet in the store with form data + + + :param str pet_id: ID of pet that needs to be updated (required) + :param str name: Updated name of the pet + :param str status: Updated status of the pet + + :return: None + """ + + # verify the required parameter 'pet_id' is set + if pet_id is None: + raise ValueError("Missing the required parameter `pet_id` when calling `update_pet_with_form`") + + all_params = ['pet_id', 'name', 'status'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method update_pet_with_form" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/pet/{petId}'.replace('{format}', 'json') + method = 'POST' + + path_params = remove_none(dict(petId=params.get('pet_id'))) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict(name=params.get('name'), status=params.get('status'))) + files = remove_none(dict()) + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = ['application/x-www-form-urlencoded'] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + def delete_pet(self, pet_id, **kwargs): + """ + Deletes a pet + + + :param str api_key: + :param int pet_id: Pet id to delete (required) + + :return: None + """ + + # verify the required parameter 'pet_id' is set + if pet_id is None: + raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`") + + all_params = ['api_key', 'pet_id'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method delete_pet" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/pet/{petId}'.replace('{format}', 'json') + method = 'DELETE' + + path_params = remove_none(dict(petId=params.get('pet_id'))) + query_params = remove_none(dict()) + header_params = remove_none(dict(api_key=params.get('api_key'))) + form_params = remove_none(dict()) + files = remove_none(dict()) + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + def upload_file(self, pet_id, **kwargs): + """ + uploads an image + + + :param int pet_id: ID of pet to update (required) + :param str additional_metadata: Additional data to pass to server + :param File file: file to upload + + :return: None + """ + + # verify the required parameter 'pet_id' is set + if pet_id is None: + raise ValueError("Missing the required parameter `pet_id` when calling `upload_file`") + + all_params = ['pet_id', 'additional_metadata', 'file'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method upload_file" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/pet/{petId}/uploadImage'.replace('{format}', 'json') + method = 'POST' + + path_params = remove_none(dict(petId=params.get('pet_id'))) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict(additionalMetadata=params.get('additional_metadata'), )) + files = remove_none(dict(file=params.get('file'))) + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = ['multipart/form-data'] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + + + + + + + + + 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 new file mode 100644 index 00000000000..0df9a84fe75 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py @@ -0,0 +1,214 @@ +#!/usr/bin/env python +# coding: utf-8 + +""" +StoreApi.py +Copyright 2015 Reverb Technologies, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +""" +from __future__ import absolute_import + +import sys +import os + +# python 2 and python 3 compatibility library +from six import iteritems + +from ..util import remove_none + +class StoreApi(object): + + def __init__(self, api_client): + self.api_client = api_client + + def get_inventory(self, **kwargs): + """ + Returns pet inventories by status + Returns a map of status codes to quantities + + + :return: map(String, int) + """ + + all_params = [] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method get_inventory" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/store/inventory'.replace('{format}', 'json') + method = 'GET' + + path_params = remove_none(dict()) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response='map(String, int)') + + return response + + def place_order(self, **kwargs): + """ + Place an order for a pet + + + :param Order body: order placed for purchasing the pet + + :return: Order + """ + + all_params = ['body'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method place_order" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/store/order'.replace('{format}', 'json') + method = 'POST' + + path_params = remove_none(dict()) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) + body_params = params.get('body') + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response='Order') + + return response + + def get_order_by_id(self, order_id, **kwargs): + """ + Find purchase order by ID + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + + :param str order_id: ID of pet that needs to be fetched (required) + + :return: Order + """ + + # verify the required parameter 'order_id' is set + if order_id is None: + raise ValueError("Missing the required parameter `order_id` when calling `get_order_by_id`") + + all_params = ['order_id'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method get_order_by_id" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/store/order/{orderId}'.replace('{format}', 'json') + method = 'GET' + + path_params = remove_none(dict(orderId=params.get('order_id'))) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response='Order') + + return response + + def delete_order(self, order_id, **kwargs): + """ + Delete purchase order by ID + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + + :param str order_id: ID of the order that needs to be deleted (required) + + :return: None + """ + + # verify the required parameter 'order_id' is set + if order_id is None: + raise ValueError("Missing the required parameter `order_id` when calling `delete_order`") + + all_params = ['order_id'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method delete_order" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/store/order/{orderId}'.replace('{format}', 'json') + method = 'DELETE' + + path_params = remove_none(dict(orderId=params.get('order_id'))) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + + + + + + + + + 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 new file mode 100644 index 00000000000..720843bd508 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py @@ -0,0 +1,374 @@ +#!/usr/bin/env python +# coding: utf-8 + +""" +UserApi.py +Copyright 2015 Reverb Technologies, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +""" +from __future__ import absolute_import + +import sys +import os + +# python 2 and python 3 compatibility library +from six import iteritems + +from ..util import remove_none + +class UserApi(object): + + def __init__(self, api_client): + self.api_client = api_client + + def create_user(self, **kwargs): + """ + Create user + This can only be done by the logged in user. + + :param User body: Created user object + + :return: None + """ + + all_params = ['body'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method create_user" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/user'.replace('{format}', 'json') + method = 'POST' + + path_params = remove_none(dict()) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) + body_params = params.get('body') + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + def create_users_with_array_input(self, **kwargs): + """ + Creates list of users with given input array + + + :param list[User] body: List of user object + + :return: None + """ + + all_params = ['body'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method create_users_with_array_input" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/user/createWithArray'.replace('{format}', 'json') + method = 'POST' + + path_params = remove_none(dict()) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) + body_params = params.get('body') + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + def create_users_with_list_input(self, **kwargs): + """ + Creates list of users with given input array + + + :param list[User] body: List of user object + + :return: None + """ + + all_params = ['body'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method create_users_with_list_input" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/user/createWithList'.replace('{format}', 'json') + method = 'POST' + + path_params = remove_none(dict()) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) + body_params = params.get('body') + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + def login_user(self, **kwargs): + """ + Logs user into the system + + + :param str username: The user name for login + :param str password: The password for login in clear text + + :return: str + """ + + all_params = ['username', 'password'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method login_user" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/user/login'.replace('{format}', 'json') + method = 'GET' + + path_params = remove_none(dict()) + query_params = remove_none(dict(username=params.get('username'), password=params.get('password'))) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response='str') + + return response + + def logout_user(self, **kwargs): + """ + Logs out current logged in user session + + + + :return: None + """ + + all_params = [] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method logout_user" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/user/logout'.replace('{format}', 'json') + method = 'GET' + + path_params = remove_none(dict()) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + def get_user_by_name(self, username, **kwargs): + """ + Get user by user name + + + :param str username: The name that needs to be fetched. Use user1 for testing. (required) + + :return: User + """ + + # verify the required parameter 'username' is set + if username is None: + raise ValueError("Missing the required parameter `username` when calling `get_user_by_name`") + + all_params = ['username'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method get_user_by_name" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/user/{username}'.replace('{format}', 'json') + method = 'GET' + + path_params = remove_none(dict(username=params.get('username'))) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response='User') + + return response + + def update_user(self, username, **kwargs): + """ + Updated user + This can only be done by the logged in user. + + :param str username: name that need to be deleted (required) + :param User body: Updated user object + + :return: None + """ + + # verify the required parameter 'username' is set + if username is None: + raise ValueError("Missing the required parameter `username` when calling `update_user`") + + all_params = ['username', 'body'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method update_user" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/user/{username}'.replace('{format}', 'json') + method = 'PUT' + + path_params = remove_none(dict(username=params.get('username'))) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) + body_params = params.get('body') + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + def delete_user(self, username, **kwargs): + """ + Delete user + This can only be done by the logged in user. + + :param str username: The name that needs to be deleted (required) + + :return: None + """ + + # verify the required parameter 'username' is set + if username is None: + raise ValueError("Missing the required parameter `username` when calling `delete_user`") + + all_params = ['username'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method delete_user" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/user/{username}'.replace('{format}', 'json') + method = 'DELETE' + + path_params = remove_none(dict(username=params.get('username'))) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + + + + + + + + + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/__init__.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/__init__.py index ce94c72a70c..de307a26503 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/__init__.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/__init__.py @@ -1,21 +1,9 @@ -#!/usr/bin/env python -"""Add all of the modules in the current directory to __all__""" -import os - +from __future__ import absolute_import +# import models into model package from .user import User - from .category import Category - from .pet import Pet - from .tag import Tag - from .order import Order - -__all__ = [] - -for module in os.listdir(os.path.dirname(__file__)): - if module != '__init__.py' and module[-3:] == '.py': - __all__.append(module[:-3]) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/category.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/category.py index 7b41a32a7d7..8fba78ca18e 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/category.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/category.py @@ -18,37 +18,41 @@ Copyright 2015 Reverb Technologies, Inc. """ class Category(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ def __init__(self): """ - Attributes: - swaggerTypes (dict): The key is attribute name and the value is attribute type. - attributeMap (dict): The key is attribute name and the value is json key in definition. + Swagger model + + :param dict swaggerTypes: The key is attribute name and the value is attribute type. + :param dict attributeMap: The key is attribute name and the value is json key in definition. """ - self.swaggerTypes = { - - 'id': 'long', - - + self.swagger_types = { + 'id': 'int', 'name': 'str' - } - self.attributeMap = { - + self.attribute_map = { 'id': 'id', - 'name': 'name' - } + + + self.id = None # int + + + self.name = None # str + + + def __repr__(self): + properties = [] + for p in self.__dict__: + if p != 'swaggerTypes' and p != 'attributeMap': + properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) + + return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) + - - - self.id = None # long - - - self.name = None # str - diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/order.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/order.py index 84780db3780..8a84ee81bea 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/order.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/order.py @@ -18,70 +18,61 @@ Copyright 2015 Reverb Technologies, Inc. """ class Order(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ def __init__(self): """ - Attributes: - swaggerTypes (dict): The key is attribute name and the value is attribute type. - attributeMap (dict): The key is attribute name and the value is json key in definition. + Swagger model + + :param dict swaggerTypes: The key is attribute name and the value is attribute type. + :param dict attributeMap: The key is attribute name and the value is json key in definition. """ - self.swaggerTypes = { - - 'id': 'long', - - - 'pet_id': 'long', - - + self.swagger_types = { + 'id': 'int', + 'pet_id': 'int', 'quantity': 'int', - - 'ship_date': 'DateTime', - - 'status': 'str', - - 'complete': 'bool' - } - self.attributeMap = { - + self.attribute_map = { 'id': 'id', - 'pet_id': 'petId', - 'quantity': 'quantity', - 'ship_date': 'shipDate', - 'status': 'status', - 'complete': 'complete' - } + + + self.id = None # int + + + self.pet_id = None # int + + + self.quantity = None # int + + + self.ship_date = None # DateTime + + # Order Status + self.status = None # str + + + self.complete = None # bool + + + def __repr__(self): + properties = [] + for p in self.__dict__: + if p != 'swaggerTypes' and p != 'attributeMap': + properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) + + return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) + - - - self.id = None # long - - - self.pet_id = None # long - - - self.quantity = None # int - - - self.ship_date = None # DateTime - - #Order Status - - self.status = None # str - - - self.complete = None # bool - diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/pet.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/pet.py index 1415d6f8535..af667e42489 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/pet.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/pet.py @@ -18,70 +18,61 @@ Copyright 2015 Reverb Technologies, Inc. """ class Pet(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ def __init__(self): """ - Attributes: - swaggerTypes (dict): The key is attribute name and the value is attribute type. - attributeMap (dict): The key is attribute name and the value is json key in definition. + Swagger model + + :param dict swaggerTypes: The key is attribute name and the value is attribute type. + :param dict attributeMap: The key is attribute name and the value is json key in definition. """ - self.swaggerTypes = { - - 'id': 'long', - - + self.swagger_types = { + 'id': 'int', 'category': 'Category', - - 'name': 'str', - - 'photo_urls': 'list[str]', - - 'tags': 'list[Tag]', - - 'status': 'str' - } - self.attributeMap = { - + self.attribute_map = { 'id': 'id', - 'category': 'category', - 'name': 'name', - 'photo_urls': 'photoUrls', - 'tags': 'tags', - 'status': 'status' - } + + + self.id = None # int + + + self.category = None # Category + + + self.name = None # str + + + self.photo_urls = None # list[str] + + + self.tags = None # list[Tag] + + # pet status in the store + self.status = None # str + + + def __repr__(self): + properties = [] + for p in self.__dict__: + if p != 'swaggerTypes' and p != 'attributeMap': + properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) + + return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) + - - - self.id = None # long - - - self.category = None # Category - - - self.name = None # str - - - self.photo_urls = None # list[str] - - - self.tags = None # list[Tag] - - #pet status in the store - - self.status = None # str - diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/tag.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/tag.py index a6ed3083422..08918be37fb 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/tag.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/tag.py @@ -18,37 +18,41 @@ Copyright 2015 Reverb Technologies, Inc. """ class Tag(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ def __init__(self): """ - Attributes: - swaggerTypes (dict): The key is attribute name and the value is attribute type. - attributeMap (dict): The key is attribute name and the value is json key in definition. + Swagger model + + :param dict swaggerTypes: The key is attribute name and the value is attribute type. + :param dict attributeMap: The key is attribute name and the value is json key in definition. """ - self.swaggerTypes = { - - 'id': 'long', - - + self.swagger_types = { + 'id': 'int', 'name': 'str' - } - self.attributeMap = { - + self.attribute_map = { 'id': 'id', - 'name': 'name' - } + + + self.id = None # int + + + self.name = None # str + + + def __repr__(self): + properties = [] + for p in self.__dict__: + if p != 'swaggerTypes' and p != 'attributeMap': + properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) + + return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) + - - - self.id = None # long - - - self.name = None # str - diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/user.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/user.py index 8559b331203..b218c720fae 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/user.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/user.py @@ -18,86 +18,71 @@ Copyright 2015 Reverb Technologies, Inc. """ class User(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ def __init__(self): """ - Attributes: - swaggerTypes (dict): The key is attribute name and the value is attribute type. - attributeMap (dict): The key is attribute name and the value is json key in definition. + Swagger model + + :param dict swaggerTypes: The key is attribute name and the value is attribute type. + :param dict attributeMap: The key is attribute name and the value is json key in definition. """ - self.swaggerTypes = { - - 'id': 'long', - - + self.swagger_types = { + 'id': 'int', 'username': 'str', - - 'first_name': 'str', - - 'last_name': 'str', - - 'email': 'str', - - 'password': 'str', - - 'phone': 'str', - - 'user_status': 'int' - } - self.attributeMap = { - + self.attribute_map = { 'id': 'id', - 'username': 'username', - 'first_name': 'firstName', - 'last_name': 'lastName', - 'email': 'email', - 'password': 'password', - 'phone': 'phone', - 'user_status': 'userStatus' - } + + + self.id = None # int + + + self.username = None # str + + + self.first_name = None # str + + + self.last_name = None # str + + + self.email = None # str + + + self.password = None # str + + + self.phone = None # str + + # User Status + self.user_status = None # int + + + def __repr__(self): + properties = [] + for p in self.__dict__: + if p != 'swaggerTypes' and p != 'attributeMap': + properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) + + return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) + - - - self.id = None # long - - - self.username = None # str - - - self.first_name = None # str - - - self.last_name = None # str - - - self.email = None # str - - - self.password = None # str - - - self.phone = None # str - - #User Status - - self.user_status = None # int - diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/pet_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/pet_api.py deleted file mode 100644 index d842c2f0a0f..00000000000 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/pet_api.py +++ /dev/null @@ -1,551 +0,0 @@ -#!/usr/bin/env python -# coding: utf-8 - -""" -PetApi.py -Copyright 2015 Reverb Technologies, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os -import urllib - -from models import * - - -class PetApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def update_pet(self, **kwargs): - """Update an existing pet - - - Args: - body, Pet: Pet object that needs to be added to the store (required) - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method update_pet" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'PUT' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = ['application/json', 'application/xml', ] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - - - - - if ('body' in params): - bodyParam = params['body'] - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - def add_pet(self, **kwargs): - """Add a new pet to the store - - - Args: - body, Pet: Pet object that needs to be added to the store (required) - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method add_pet" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = ['application/json', 'application/xml', ] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - - - - - if ('body' in params): - bodyParam = params['body'] - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - def find_pets_by_status(self, **kwargs): - """Finds Pets by status - Multiple status values can be provided with comma seperated strings - - Args: - status, list[str]: Status values that need to be considered for filter (required) - - - Returns: list[Pet] - """ - - allParams = ['status'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method find_pets_by_status" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/findByStatus' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - if ('status' in params): - queryParams['status'] = self.apiClient.toPathValue(params['status']) - - - - - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[Pet]') - return responseObject - - - - - def find_pets_by_tags(self, **kwargs): - """Finds Pets by tags - Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - - Args: - tags, list[str]: Tags to filter by (required) - - - Returns: list[Pet] - """ - - allParams = ['tags'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method find_pets_by_tags" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/findByTags' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - if ('tags' in params): - queryParams['tags'] = self.apiClient.toPathValue(params['tags']) - - - - - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[Pet]') - return responseObject - - - - - def get_pet_by_id(self, **kwargs): - """Find pet by ID - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - - Args: - pet_id, long: ID of pet that needs to be fetched (required) - - - Returns: Pet - """ - - allParams = ['pet_id'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method get_pet_by_id" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/{petId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - if ('pet_id' in params): - replacement = str(self.apiClient.toPathValue(params['pet_id'])) - replacement = urllib.quote(replacement) - resourcePath = resourcePath.replace('{' + 'petId' + '}', - replacement) - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'Pet') - return responseObject - - - - - def update_pet_with_form(self, **kwargs): - """Updates a pet in the store with form data - - - Args: - pet_id, str: ID of pet that needs to be updated (required) - name, str: Updated name of the pet (required) - status, str: Updated status of the pet (required) - - - Returns: - """ - - allParams = ['pet_id', 'name', 'status'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method update_pet_with_form" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/{petId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = ['application/x-www-form-urlencoded', ] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - if ('pet_id' in params): - replacement = str(self.apiClient.toPathValue(params['pet_id'])) - replacement = urllib.quote(replacement) - resourcePath = resourcePath.replace('{' + 'petId' + '}', - replacement) - - - - if ('name' in params): - formParams['name'] = params['name'] - - if ('status' in params): - formParams['status'] = params['status'] - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - def delete_pet(self, **kwargs): - """Deletes a pet - - - Args: - api_key, str: (required) - pet_id, long: Pet id to delete (required) - - - Returns: - """ - - allParams = ['api_key', 'pet_id'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method delete_pet" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/{petId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'DELETE' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - if ('api_key' in params): - headerParams['api_key'] = params['api_key'] - - - - if ('pet_id' in params): - replacement = str(self.apiClient.toPathValue(params['pet_id'])) - replacement = urllib.quote(replacement) - resourcePath = resourcePath.replace('{' + 'petId' + '}', - replacement) - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - def upload_file(self, **kwargs): - """uploads an image - - - Args: - pet_id, long: ID of pet to update (required) - additional_metadata, str: Additional data to pass to server (required) - file, file: file to upload (required) - - - Returns: - """ - - allParams = ['pet_id', 'additional_metadata', 'file'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method upload_file" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/{petId}/uploadImage' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = ['multipart/form-data', ] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - if ('pet_id' in params): - replacement = str(self.apiClient.toPathValue(params['pet_id'])) - replacement = urllib.quote(replacement) - resourcePath = resourcePath.replace('{' + 'petId' + '}', - replacement) - - - - if ('additional_metadata' in params): - formParams['additionalMetadata'] = params['additional_metadata'] - - if ('file' in params): - files['file'] = params['file'] - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - - diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py new file mode 100644 index 00000000000..06b817da757 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py @@ -0,0 +1,223 @@ +# coding: utf-8 +import sys +import io +import json + +# python 2 and python 3 compatibility library +from six import iteritems + +try: + import urllib3 +except ImportError: + raise ImportError('Swagger python client requires urllib3.') + +try: + # for python3 + from urllib.parse import urlencode +except ImportError: + # for python2 + from urllib import urlencode + + +class RESTResponse(io.IOBase): + + def __init__(self, resp): + self.urllib3_response = resp + self.status = resp.status + self.reason = resp.reason + self.data = resp.data + + def getheaders(self): + """ + Returns a dictionary of the response headers. + """ + return self.urllib3_response.getheaders() + + def getheader(self, name, default=None): + """ + Returns a given response header. + """ + return self.urllib3_response.getheader(name, default) + +class RESTClientObject(object): + + def __init__(self, pools_size=4): + self.pool_manager = urllib3.PoolManager( + num_pools=pools_size + ) + + def request(self, method, url, query_params=None, headers=None, + body=None, post_params=None): + """ + :param method: http request method + :param url: http request url + :param query_params: query parameters in the url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, `application/x-www-form-urlencode` + and `multipart/form-data` + :param raw_response: if return the raw response + """ + method = method.upper() + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH'] + + if post_params and body: + raise ValueError("body parameter cannot be used with post_params parameter.") + + post_params = post_params or {} + headers = headers or {} + + if 'Content-Type' not in headers: + headers['Content-Type'] = 'application/json' + + # For `POST`, `PUT`, `PATCH` + if method in ['POST', 'PUT', 'PATCH']: + if query_params: + url += '?' + urlencode(query_params) + if headers['Content-Type'] == 'application/json': + r = self.pool_manager.request(method, url, + body=json.dumps(body), + headers=headers) + if headers['Content-Type'] == 'application/x-www-form-urlencoded': + r = self.pool_manager.request(method, url, + fields=post_params, + encode_multipart=False, + headers=headers) + if headers['Content-Type'] == 'multipart/form-data': + # must del headers['Content-Type'], or the correct Content-Type + # which generated by urllib3 will be overwritten. + del headers['Content-Type'] + r = self.pool_manager.request(method, url, + fields=post_params, + encode_multipart=True, + headers=headers) + # For `GET`, `HEAD`, `DELETE` + else: + r = self.pool_manager.request(method, url, + fields=query_params, + headers=headers) + r = RESTResponse(r) + + if r.status not in range(200, 206): + raise ErrorResponse(r) + + return self.process_response(r) + + def process_response(self, response): + # In the python 3, the response.data is bytes. + # we need to decode it to string. + if sys.version_info > (3,): + data = response.data.decode('utf8') + else: + data = response.data + try: + resp = json.loads(data) + except ValueError: + resp = data + + return resp + + def GET(self, url, headers=None, query_params=None): + return self.request("GET", url, headers=headers, query_params=query_params) + + def HEAD(self, url, headers=None, query_params=None): + return self.request("HEAD", url, headers=headers, query_params=query_params) + + def DELETE(self, url, headers=None, query_params=None): + return self.request("DELETE", url, headers=headers, query_params=query_params) + + def POST(self, url, headers=None, post_params=None, body=None): + return self.request("POST", url, headers=headers, post_params=post_params, body=body) + + def PUT(self, url, headers=None, post_params=None, body=None): + return self.request("PUT", url, headers=headers, post_params=post_params, body=body) + + def PATCH(self, url, headers=None, post_params=None, body=None): + return self.request("PATCH", url, headers=headers, post_params=post_params, body=body) + + +class ErrorResponse(Exception): + """ + Non-2xx HTTP response + """ + + def __init__(self, http_resp): + self.status = http_resp.status + self.reason = http_resp.reason + self.body = http_resp.data + self.headers = http_resp.getheaders() + + # In the python 3, the self.body is bytes. + # we need to decode it to string. + if sys.version_info > (3,): + data = self.body.decode('utf8') + else: + data = self.body + + try: + self.body = json.loads(data) + except ValueError: + self.body = data + + def __str__(self): + """ + Custom error response messages + """ + return "({0})\nReason: {1}\nHeader: {2}\nBody: {3}\n".\ + format(self.status, self.reason, self.headers, self.body) + +class RESTClient(object): + """ + A class with all class methods to perform JSON requests. + """ + + IMPL = RESTClientObject() + + @classmethod + def request(cls, *n, **kw): + """ + Perform a REST request and parse the response. + """ + return cls.IMPL.request(*n, **kw) + + @classmethod + def GET(cls, *n, **kw): + """ + Perform a GET request using `RESTClient.request()`. + """ + return cls.IMPL.GET(*n, **kw) + + @classmethod + def HEAD(cls, *n, **kw): + """ + Perform a HEAD request using `RESTClient.request()`. + """ + return cls.IMPL.GET(*n, **kw) + + @classmethod + def POST(cls, *n, **kw): + """ + Perform a POST request using `RESTClient.request()` + """ + return cls.IMPL.POST(*n, **kw) + + @classmethod + def PUT(cls, *n, **kw): + """ + Perform a PUT request using `RESTClient.request()` + """ + return cls.IMPL.PUT(*n, **kw) + + @classmethod + def PATCH(cls, *n, **kw): + """ + Perform a PATCH request using `RESTClient.request()` + """ + return cls.IMPL.PATCH(*n, **kw) + + @classmethod + def DELETE(cls, *n, **kw): + """ + Perform a DELETE request using `RESTClient.request()` + """ + return cls.IMPL.DELETE(*n, **kw) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/store_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/store_api.py deleted file mode 100644 index b2de83e85da..00000000000 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/store_api.py +++ /dev/null @@ -1,289 +0,0 @@ -#!/usr/bin/env python -# coding: utf-8 - -""" -StoreApi.py -Copyright 2015 Reverb Technologies, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os -import urllib - -from models import * - - -class StoreApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def get_inventory(self, **kwargs): - """Returns pet inventories by status - Returns a map of status codes to quantities - - Args: - - - Returns: map(String, int) - """ - - allParams = [] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method get_inventory" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/store/inventory' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'map(String, int)') - return responseObject - - - - - def place_order(self, **kwargs): - """Place an order for a pet - - - Args: - body, Order: order placed for purchasing the pet (required) - - - Returns: Order - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method place_order" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/store/order' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - - - - - if ('body' in params): - bodyParam = params['body'] - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'Order') - return responseObject - - - - - def get_order_by_id(self, **kwargs): - """Find purchase order by ID - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - Args: - order_id, str: ID of pet that needs to be fetched (required) - - - Returns: Order - """ - - allParams = ['order_id'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method get_order_by_id" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/store/order/{orderId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - if ('order_id' in params): - replacement = str(self.apiClient.toPathValue(params['order_id'])) - replacement = urllib.quote(replacement) - resourcePath = resourcePath.replace('{' + 'orderId' + '}', - replacement) - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'Order') - return responseObject - - - - - def delete_order(self, **kwargs): - """Delete purchase order by ID - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - - Args: - order_id, str: ID of the order that needs to be deleted (required) - - - Returns: - """ - - allParams = ['order_id'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method delete_order" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/store/order/{orderId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'DELETE' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - if ('order_id' in params): - replacement = str(self.apiClient.toPathValue(params['order_id'])) - replacement = urllib.quote(replacement) - resourcePath = resourcePath.replace('{' + 'orderId' + '}', - replacement) - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, 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 10ac54d527d..549106014e3 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py @@ -6,118 +6,109 @@ server communication, and is invariant across implementations. Specifics of the methods and models for each application are generated from the Swagger templates.""" -import sys +from __future__ import absolute_import +from . import models +from .rest import RESTClient + import os import re import urllib -import urllib2 -import httplib import json import datetime import mimetypes import random -import string -import models + +# python 2 and python 3 compatibility library +from six import iteritems + +try: + # for python3 + from urllib.parse import quote +except ImportError: + # for python2 + from urllib import quote class ApiClient(object): - """Generic API client for Swagger client library builds - - Attributes: - host: The base path for the server to call - headerName: a header to pass when making calls to the API - headerValue: a header value to pass when making calls to the API """ - def __init__(self, host=None, headerName=None, headerValue=None): - self.defaultHeaders = {} - if (headerName is not None): - self.defaultHeaders[headerName] = headerValue + Generic API client for Swagger client library builds + + :param host: The base path for the server to call + :param header_name: a header to pass when making calls to the API + :param header_value: a header value to pass when making calls to the API + """ + def __init__(self, host=None, header_name=None, header_value=None): + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value self.host = host self.cookie = None - self.boundary = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(30)) # Set default User-Agent. self.user_agent = 'Python-Swagger' @property def user_agent(self): - return self.defaultHeaders['User-Agent'] + return self.default_headers['User-Agent'] @user_agent.setter def user_agent(self, value): - self.defaultHeaders['User-Agent'] = value + self.default_headers['User-Agent'] = value - def setDefaultHeader(self, headerName, headerValue): - self.defaultHeaders[headerName] = headerValue + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value - def callAPI(self, resourcePath, method, queryParams, postData, - headerParams=None, files=None): - - url = self.host + resourcePath - - mergedHeaderParams = self.defaultHeaders.copy() - mergedHeaderParams.update(headerParams) - headers = {} - if mergedHeaderParams: - for param, value in mergedHeaderParams.iteritems(): - headers[param] = ApiClient.sanitizeForSerialization(value) + def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, + body=None, post_params=None, files=None, response=None): + # headers parameters + headers = self.default_headers.copy() + headers.update(header_params) if self.cookie: - headers['Cookie'] = ApiClient.sanitizeForSerialization(self.cookie) + headers['Cookie'] = self.cookie + if headers: + headers = ApiClient.sanitize_for_serialization(headers) - data = None + # path parameters + if path_params: + path_params = ApiClient.sanitize_for_serialization(path_params) + for k, v in iteritems(path_params): + replacement = quote(str(self.to_path_value(v))) + resource_path = resource_path.replace('{' + k + '}', replacement) - if queryParams: - # Need to remove None values, these should not be sent - sentQueryParams = {} - for param, value in queryParams.items(): - if value is not None: - sentQueryParams[param] = ApiClient.sanitizeForSerialization(value) - url = url + '?' + urllib.urlencode(sentQueryParams) + # query parameters + if query_params: + query_params = ApiClient.sanitize_for_serialization(query_params) + query_params = {k: self.to_path_value(v) for k, v in iteritems(query_params)} - if method in ['GET']: - #Options to add statements later on and for compatibility - pass + # post parameters + if post_params: + post_params = self.prepare_post_parameters(post_params, files) + post_params = ApiClient.sanitize_for_serialization(post_params) - elif method in ['POST', 'PUT', 'DELETE']: - if postData: - postData = ApiClient.sanitizeForSerialization(postData) - if 'Content-Type' not in headers: - headers['Content-Type'] = 'application/json' - data = json.dumps(postData) - elif headers['Content-Type'] == 'application/json': - data = json.dumps(postData) - elif headers['Content-Type'] == 'multipart/form-data': - data = self.buildMultipartFormData(postData, files) - headers['Content-Type'] = 'multipart/form-data; boundary={0}'.format(self.boundary) - headers['Content-length'] = str(len(data)) - else: - data = urllib.urlencode(postData) + # body + if body: + body = ApiClient.sanitize_for_serialization(body) + # request url + url = self.host + resource_path + + # perform request and return response + response_data = self.request(method, url, query_params=query_params, headers=headers, + post_params=post_params, body=body) + + # deserialize response data + if response: + return self.deserialize(response_data, response) else: - raise Exception('Method ' + method + ' is not recognized.') + return None - request = MethodRequest(method=method, url=url, headers=headers, - data=data) + def to_path_value(self, obj): + """ + Convert a string or object to a path-friendly value + + :param obj: object or string value - # Make the request - response = urllib2.urlopen(request) - if 'Set-Cookie' in response.headers: - self.cookie = response.headers['Set-Cookie'] - string = response.read() - - try: - data = json.loads(string) - except ValueError: # PUT requests don't return anything - data = None - - return data - - def toPathValue(self, obj): - """Convert a string or object to a path-friendly value - Args: - obj -- object or string value - Returns: - string -- quoted value + :return string: quoted value """ if type(obj) == list: return ','.join(obj) @@ -125,12 +116,12 @@ class ApiClient(object): return str(obj) @staticmethod - def sanitizeForSerialization(obj): + def sanitize_for_serialization(obj): """ Sanitize an object for Request. If obj is None, return None. - If obj is str, int, long, float, bool, return directly. + If obj is str, int, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. If obj is list, santize each element in the list. If obj is dict, return the dict. @@ -138,113 +129,80 @@ class ApiClient(object): """ if isinstance(obj, type(None)): return None - elif isinstance(obj, (str, int, long, float, bool, file)): + elif isinstance(obj, (str, int, float, bool, tuple)): return obj elif isinstance(obj, list): - return [ApiClient.sanitizeForSerialization(subObj) for subObj in obj] + return [ApiClient.sanitize_for_serialization(sub_obj) for sub_obj in obj] elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() else: if isinstance(obj, dict): - objDict = obj + obj_dict = obj else: - # Convert model obj to dict except attributes `swaggerTypes`, `attributeMap` + # Convert model obj to dict except attributes `swagger_types`, `attribute_map` # and attributes which value is not None. # Convert attribute name to json key in model definition for request. - objDict = {obj.attributeMap[key]: val - for key, val in obj.__dict__.iteritems() - if key != 'swaggerTypes' and key != 'attributeMap' and val is not None} - return {key: ApiClient.sanitizeForSerialization(val) - for (key, val) in objDict.iteritems()} + obj_dict = {obj.attribute_map[key]: val + for key, val in iteritems(obj.__dict__) + if key != 'swagger_types' and key != 'attribute_map' and val is not None} + return {key: ApiClient.sanitize_for_serialization(val) + for key, val in iteritems(obj_dict)} - def buildMultipartFormData(self, postData, files): - def escape_quotes(s): - return s.replace('"', '\\"') + def deserialize(self, obj, obj_class): + """ + Derialize a JSON string into an object. - lines = [] + :param obj: string or object to be deserialized + :param obj_class: class literal for deserialzied object, or string of class name - for name, value in postData.items(): - lines.extend(( - '--{0}'.format(self.boundary), - 'Content-Disposition: form-data; name="{0}"'.format(escape_quotes(name)), - '', - str(value), - )) - - for name, filepath in files.items(): - f = open(filepath, 'r') - filename = filepath.split('/')[-1] - mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' - lines.extend(( - '--{0}'.format(self.boundary), - 'Content-Disposition: form-data; name="{0}"; filename="{1}"'.format(escape_quotes(name), escape_quotes(filename)), - 'Content-Type: {0}'.format(mimetype), - '', - f.read() - )) - - lines.extend(( - '--{0}--'.format(self.boundary), - '' - )) - return '\r\n'.join(lines) - - def deserialize(self, obj, objClass): - """Derialize a JSON string into an object. - - Args: - obj -- string or object to be deserialized - objClass -- class literal for deserialzied object, or string - of class name - Returns: - object -- deserialized object""" - - # Have to accept objClass as string or actual type. Type could be a + :return object: deserialized object + """ + # Have to accept obj_class as string or actual type. Type could be a # native Python type, or one of the model classes. - if type(objClass) == str: - if 'list[' in objClass: - match = re.match('list\[(.*)\]', objClass) - subClass = match.group(1) - return [self.deserialize(subObj, subClass) for subObj in obj] + if type(obj_class) == str: + if 'list[' in obj_class: + match = re.match('list\[(.*)\]', obj_class) + sub_class = match.group(1) + return [self.deserialize(sub_obj, sub_class) for sub_obj in obj] - if (objClass in ['int', 'float', 'long', 'dict', 'list', 'str', 'bool', 'datetime']): - objClass = eval(objClass) + if obj_class in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime']: + obj_class = eval(obj_class) else: # not a native type, must be model class - objClass = eval('models.' + objClass) + obj_class = eval('models.' + obj_class) - if objClass in [int, long, float, dict, list, str, bool]: - return objClass(obj) - elif objClass == datetime: + if obj_class in [int, float, dict, list, str, bool]: + return obj_class(obj) + elif obj_class == datetime: return self.__parse_string_to_datetime(obj) - instance = objClass() + instance = obj_class() - for attr, attrType in instance.swaggerTypes.iteritems(): - if obj is not None and instance.attributeMap[attr] in obj and type(obj) in [list, dict]: - value = obj[instance.attributeMap[attr]] - if attrType in ['str', 'int', 'long', 'float', 'bool']: - attrType = eval(attrType) + for attr, attr_type in iteritems(instance.swagger_types): + if obj is not None and instance.attribute_map[attr] in obj and type(obj) in [list, dict]: + value = obj[instance.attribute_map[attr]] + if attr_type in ['str', 'int', 'float', 'bool']: + attr_type = eval(attr_type) try: - value = attrType(value) + value = attr_type(value) except UnicodeEncodeError: value = unicode(value) except TypeError: value = value setattr(instance, attr, value) - elif (attrType == 'datetime'): + elif attr_type == 'datetime': setattr(instance, attr, self.__parse_string_to_datetime(value)) - elif 'list[' in attrType: - match = re.match('list\[(.*)\]', attrType) - subClass = match.group(1) - subValues = [] + elif 'list[' in attr_type: + match = re.match('list\[(.*)\]', attr_type) + sub_class = match.group(1) + sub_values = [] if not value: setattr(instance, attr, None) else: - for subValue in value: - subValues.append(self.deserialize(subValue, subClass)) - setattr(instance, attr, subValues) + for sub_value in value: + sub_values.append(self.deserialize(sub_value, sub_class)) + setattr(instance, attr, sub_values) else: - setattr(instance, attr, self.deserialize(value, attrType)) + setattr(instance, attr, self.deserialize(value, attr_type)) return instance @@ -260,16 +218,42 @@ class ApiClient(object): except ImportError: return string -class MethodRequest(urllib2.Request): - def __init__(self, *args, **kwargs): - """Construct a MethodRequest. Usage is the same as for - `urllib2.Request` except it also takes an optional `method` - keyword argument. If supplied, `method` will be used instead of - the default.""" + def request(self, method, url, query_params=None, headers=None, post_params=None, body=None): + """ + Perform http request using RESTClient. + """ + if method == "GET": + return RESTClient.GET(url, query_params=query_params, headers=headers) + elif method == "HEAD": + return RESTClient.HEAD(url, query_params=query_params, headers=headers) + elif method == "POST": + return RESTClient.POST(url, headers=headers, post_params=post_params, body=body) + elif method == "PUT": + return RESTClient.PUT(url, headers=headers, post_params=post_params, body=body) + elif method == "PATCH": + return RESTClient.PATCH(url, headers=headers, post_params=post_params, body=body) + elif method == "DELETE": + return RESTClient.DELETE(url, query_params=query_params, headers=headers) + else: + raise ValueError("http method must be `GET`, `HEAD`, `POST`, `PATCH`, `PUT` or `DELETE`") + + def prepare_post_parameters(self, post_params=None, files=None): + params = {} + + if post_params: + params.update(post_params) + + if files: + for k, v in iteritems(files): + with open(v, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' + params[k] = tuple([filename, filedata, mimetype]) + + return params + + + - if 'method' in kwargs: - self.method = kwargs.pop('method') - return urllib2.Request.__init__(self, *args, **kwargs) - def get_method(self): - return getattr(self, 'method', urllib2.Request.get_method(self)) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/user_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/user_api.py deleted file mode 100644 index d36a95514bd..00000000000 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/user_api.py +++ /dev/null @@ -1,526 +0,0 @@ -#!/usr/bin/env python -# coding: utf-8 - -""" -UserApi.py -Copyright 2015 Reverb Technologies, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os -import urllib - -from models import * - - -class UserApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def create_user(self, **kwargs): - """Create user - This can only be done by the logged in user. - - Args: - body, User: Created user object (required) - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method create_user" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - - - - - if ('body' in params): - bodyParam = params['body'] - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - def create_users_with_array_input(self, **kwargs): - """Creates list of users with given input array - - - Args: - body, list[User]: List of user object (required) - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method create_users_with_array_input" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/createWithArray' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - - - - - if ('body' in params): - bodyParam = params['body'] - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - def create_users_with_list_input(self, **kwargs): - """Creates list of users with given input array - - - Args: - body, list[User]: List of user object (required) - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method create_users_with_list_input" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/createWithList' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - - - - - if ('body' in params): - bodyParam = params['body'] - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - def login_user(self, **kwargs): - """Logs user into the system - - - Args: - username, str: The user name for login (required) - password, str: The password for login in clear text (required) - - - Returns: str - """ - - allParams = ['username', 'password'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method login_user" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/login' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - if ('username' in params): - queryParams['username'] = self.apiClient.toPathValue(params['username']) - - if ('password' in params): - queryParams['password'] = self.apiClient.toPathValue(params['password']) - - - - - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'str') - return responseObject - - - - - def logout_user(self, **kwargs): - """Logs out current logged in user session - - - Args: - - - Returns: - """ - - allParams = [] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method logout_user" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/logout' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - def get_user_by_name(self, **kwargs): - """Get user by user name - - - Args: - username, str: The name that needs to be fetched. Use user1 for testing. (required) - - - Returns: User - """ - - allParams = ['username'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method get_user_by_name" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/{username}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - if ('username' in params): - replacement = str(self.apiClient.toPathValue(params['username'])) - replacement = urllib.quote(replacement) - resourcePath = resourcePath.replace('{' + 'username' + '}', - replacement) - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'User') - return responseObject - - - - - def update_user(self, **kwargs): - """Updated user - This can only be done by the logged in user. - - Args: - username, str: name that need to be deleted (required) - body, User: Updated user object (required) - - - Returns: - """ - - allParams = ['username', 'body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method update_user" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/{username}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'PUT' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - if ('username' in params): - replacement = str(self.apiClient.toPathValue(params['username'])) - replacement = urllib.quote(replacement) - resourcePath = resourcePath.replace('{' + 'username' + '}', - replacement) - - - - - - if ('body' in params): - bodyParam = params['body'] - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - def delete_user(self, **kwargs): - """Delete user - This can only be done by the logged in user. - - Args: - username, str: The name that needs to be deleted (required) - - - Returns: - """ - - allParams = ['username'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method delete_user" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/{username}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'DELETE' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - if ('username' in params): - replacement = str(self.apiClient.toPathValue(params['username'])) - replacement = urllib.quote(replacement) - resourcePath = resourcePath.replace('{' + 'username' + '}', - replacement) - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - - diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/util.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/util.py new file mode 100644 index 00000000000..1137a5d2d23 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/util.py @@ -0,0 +1,17 @@ +from six import iteritems + +def remove_none(obj): + if isinstance(obj, (list, tuple, set)): + return type(obj)(remove_none(x) for x in obj if x is not None) + elif isinstance(obj, dict): + return type(obj)((remove_none(k), remove_none(v)) + for k, v in iteritems(obj) if k is not None and v is not None) + else: + return obj + + +def inspect_vars(obj): + if not hasattr(obj, '__dict__'): + return obj + else: + return {k: inspect_vars(getattr(obj, k)) for k in dir(obj)} diff --git a/samples/client/petstore/python/SwaggerPetstore-python/dev-requirements.txt b/samples/client/petstore/python/SwaggerPetstore-python/dev-requirements.txt new file mode 100644 index 00000000000..01a2e25f1c7 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/dev-requirements.txt @@ -0,0 +1,4 @@ +nose +tox +coverage +randomize diff --git a/samples/client/petstore/python/SwaggerPetstore-python/pom.xml b/samples/client/petstore/python/SwaggerPetstore-python/pom.xml index c06d3a1cdf6..e21eb2f5a96 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/pom.xml +++ b/samples/client/petstore/python/SwaggerPetstore-python/pom.xml @@ -26,21 +26,6 @@ exec-maven-plugin 1.2.1 - - nose-install - pre-integration-test - - exec - - - pip - - install - nose - --user - - - nose-test integration-test @@ -48,9 +33,9 @@ exec - nosetests + make - -v + test diff --git a/samples/client/petstore/python/SwaggerPetstore-python/setup.cfg b/samples/client/petstore/python/SwaggerPetstore-python/setup.cfg new file mode 100644 index 00000000000..e62af080034 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/setup.cfg @@ -0,0 +1,11 @@ +[nosetests] +logging-clear-handlers=true +verbosity=2 +randomize=true +exe=true +with-coverage=true +cover-package=SwaggerPetstore +cover-erase=true + +[flake8] +max-line-length=99 diff --git a/samples/client/petstore/python/SwaggerPetstore-python/setup.py b/samples/client/petstore/python/SwaggerPetstore-python/setup.py index 14d6a73b3b1..fd0b786efa3 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/setup.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/setup.py @@ -12,7 +12,7 @@ from setuptools import setup, find_packages # Try reading the setuptools documentation: # http://pypi.python.org/pypi/setuptools -REQUIRES = [] +REQUIRES = ["urllib3 >= 1.10", "six >= 1.9"] setup( name="SwaggerPetstore", @@ -30,3 +30,11 @@ setup( ) + + + + + + + + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py index b6088ae34b9..f0b8ab03d81 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py @@ -10,9 +10,9 @@ $ nosetests -v import os import time import unittest -import urllib2 import SwaggerPetstore +from SwaggerPetstore.rest import ErrorResponse HOST = 'http://petstore.swagger.io/v2' @@ -31,15 +31,15 @@ class PetApiTests(unittest.TestCase): def setUpModels(self): self.category = SwaggerPetstore.Category() - self.category.id = 1010 + self.category.id = int(time.time()) self.category.name = "dog" self.tag = SwaggerPetstore.Tag() - self.tag.id = 1010 + self.tag.id = int(time.time()) self.tag.name = "blank" self.pet = SwaggerPetstore.Pet() - self.pet.id = 1010 + self.pet.id = int(time.time()) self.pet.name = "hello kity" - self.pet.photo_urls = ["sample urls"] + self.pet.photo_urls = ["http://foo.bar.com/1", "http://foo.bar.com/2"] self.pet.status = "sold" self.pet.category = self.category self.pet.tags = [self.tag] @@ -49,48 +49,55 @@ class PetApiTests(unittest.TestCase): self.test_file_dir = os.path.realpath(self.test_file_dir) self.foo = os.path.join(self.test_file_dir, "foo.png") - def test_1_add_pet(self): - try: - self.pet_api.add_pet(body=self.pet) - except (urllib2.HTTPError, urllib2.URLError) as e: - self.fail("add_pet() raised {0} unexpectedly".format(type(e))) + def test_add_pet_and_get_pet_by_id(self): + self.pet_api.add_pet(body=self.pet) - def test_2_get_pet_by_id(self): - self.assertEqual( - dir(self.pet_api.get_pet_by_id(pet_id=self.pet.id)), - dir(self.pet) - ) + fetched = self.pet_api.get_pet_by_id(pet_id=self.pet.id) + self.assertIsNotNone(fetched) + self.assertEqual(self.pet.id, fetched.id) + self.assertIsNotNone(fetched.category) + self.assertEqual(self.pet.category.name, fetched.category.name) - def test_3_update_pet(self): - try: - self.pet.name = "hello kity with updated" - self.pet_api.update_pet(body=self.pet) - except (urllib2.HTTPError, urllib2.URLError) as e: - self.fail("update_pet() raised {0} unexpectedly".format(type(e))) + def test_update_pet(self): + self.pet.name = "hello kity with updated" + self.pet_api.update_pet(body=self.pet) - def test_4_find_pets_by_status(self): + fetched = self.pet_api.get_pet_by_id(pet_id=self.pet.id) + self.assertIsNotNone(fetched) + self.assertEqual(self.pet.id, fetched.id) + self.assertEqual(self.pet.name, fetched.name) + self.assertIsNotNone(fetched.category) + self.assertEqual(fetched.category.name, self.pet.category.name) + + def test_find_pets_by_status(self): + self.pet_api.add_pet(body=self.pet) + self.assertIn( - dir(self.pet), - map(dir, self.pet_api.find_pets_by_status(status=["sold"])) + self.pet.id, + list(map(lambda x: getattr(x, 'id'), self.pet_api.find_pets_by_status(status=[self.pet.status]))) ) - def test_5_find_pets_by_tags(self): + def test_find_pets_by_tags(self): + self.pet_api.add_pet(body=self.pet) + self.assertIn( - dir(self.pet), - map(dir, self.pet_api.find_pets_by_tags(tags=["blank"])) + self.pet.id, + list(map(lambda x: getattr(x, 'id'), self.pet_api.find_pets_by_tags(tags=[self.tag.name]))) ) - def test_6_update_pet_with_form(self): - try: - name = "hello kity with form updated" - status = "pending" - self.pet_api.update_pet_with_form( - pet_id=self.pet.id, name=name, status=status - ) - except (urllib2.HTTPError, urllib2.URLError) as e: - self.fail("update_pet_with_form() raised {0} unexpectedly".format(type(e))) + def test_update_pet_with_form(self): + self.pet_api.add_pet(body=self.pet) + + name = "hello kity with form updated" + status = "pending" + self.pet_api.update_pet_with_form(pet_id=self.pet.id, name=name, status=status) - def test_7_upload_file(self): + fetched = self.pet_api.get_pet_by_id(pet_id=self.pet.id) + self.assertEqual(self.pet.id, fetched.id) + self.assertEqual(name, fetched.name) + self.assertEqual(status, fetched.status) + + def test_upload_file(self): try: additional_metadata = "special" self.pet_api.upload_file( @@ -98,16 +105,23 @@ class PetApiTests(unittest.TestCase): additional_metadata=additional_metadata, file=self.foo ) - except (urllib2.HTTPError, urllib2.URLError) as e: + except ErrorResponse as e: self.fail("upload_file() raised {0} unexpectedly".format(type(e))) - def test_8_delete_pet(self): + def test_delete_pet(self): + self.pet_api.add_pet(body=self.pet) + self.pet_api.delete_pet(pet_id=self.pet.id, api_key="special-key") + try: - api_key = "special-key" - self.pet_api.delete_pet(pet_id=self.pet.id, api_key=api_key) - except (urllib2.HTTPError, urllib2.URLError) as e: - self.fail("delete_pet() raised {0} unexpectedly".format(type(e))) - + self.pet_api.get_pet_by_id(pet_id=self.pet.id) + raise "expected an error" + except ErrorResponse as e: + self.assertEqual(404, e.status) if __name__ == '__main__': unittest.main() + + + + + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tox.ini b/samples/client/petstore/python/SwaggerPetstore-python/tox.ini new file mode 100644 index 00000000000..9f62f3845bf --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/tox.ini @@ -0,0 +1,10 @@ +[tox] +envlist = py27, py34 + +[testenv] +deps= -r{toxinidir}/dev-requirements.txt +commands= + nosetests \ + [] +setenv = + PYTHONWARNINGS=always::DeprecationWarning diff --git a/samples/client/petstore/qt5cpp/client/SWGPet.h b/samples/client/petstore/qt5cpp/client/SWGPet.h index 3f9320f1507..e9cb4d08233 100644 --- a/samples/client/petstore/qt5cpp/client/SWGPet.h +++ b/samples/client/petstore/qt5cpp/client/SWGPet.h @@ -10,10 +10,10 @@ #include -#include -#include "SWGCategory.h" -#include #include "SWGTag.h" +#include +#include "SWGCategory.h" +#include #include "SWGObject.h" diff --git a/samples/client/petstore/ruby/Gemfile.lock b/samples/client/petstore/ruby/Gemfile.lock index 232facf4677..e9e03f10b77 100644 --- a/samples/client/petstore/ruby/Gemfile.lock +++ b/samples/client/petstore/ruby/Gemfile.lock @@ -1,10 +1,10 @@ PATH remote: . specs: - swagger-client (4.06.08) - addressable (>= 2.2.4) - json (>= 1.4.6) - typhoeus (>= 0.2.1) + swagger_client (1.0.0) + addressable (~> 2.2, >= 2.2.4) + json (~> 1.4, >= 1.4.6) + typhoeus (~> 0.2, >= 0.2.1) GEM remote: http://rubygems.org/ @@ -51,11 +51,11 @@ PLATFORMS ruby DEPENDENCIES - autotest - autotest-fsevent - autotest-growl - autotest-rails-pure - rspec (>= 2.5.0) - swagger-client! - vcr (>= 1.5.1) - webmock (>= 1.6.2) + autotest (~> 4.4, >= 4.4.6) + autotest-fsevent (~> 0.2, >= 0.2.10) + autotest-growl (~> 0.2, >= 0.2.16) + autotest-rails-pure (~> 4.1, >= 4.1.2) + rspec (~> 3.2, >= 3.2.0) + swagger_client! + vcr (~> 2.9, >= 2.9.3) + webmock (~> 1.6, >= 1.6.2) diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 29a7ce844ce..2a15c1661cc 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -5,20 +5,20 @@ You can build the generated client into a gem: ```shell -gem build swagger-client.gemspec +gem build swagger_client.gemspec ``` Then you can either install the gem: ```shell -gem install ./swagger-client-4.06.08.gem +gem install ./swagger_client-1.0.0.gem ``` or publish the gem to a gem server like [RubyGems](https://rubygems.org/). Finally add this to your Gemfile: - gem 'swagger-client', '~> 4.06.08' + gem 'swagger_client', '~> 1.0.0' ### Host as a git repository @@ -27,7 +27,7 @@ https://github.com/xhh/swagger-petstore-ruby Then you can reference it in Gemfile: - gem 'swagger-client', :git => 'https://github.com/xhh/swagger-petstore-ruby.git' + gem 'swagger_client', :git => 'https://github.com/xhh/swagger-petstore-ruby.git' ### Use without installation @@ -40,9 +40,9 @@ ruby -Ilib script.rb ## Configuration ```ruby -require 'swagger-client' +require 'swagger_client' -Swagger.configure do |config| +SwaggerClient::Swagger.configure do |config| config.api_key = 'special-key' config.host = 'petstore.swagger.io' config.base_path = '/v2' @@ -52,6 +52,6 @@ end ## Getting Started ```ruby -pet = PetApi.getPetById(5) +pet = SwaggerClient::PetApi.get_pet_by_id(5) puts pet.to_body ``` diff --git a/samples/client/petstore/ruby/lib/pet_api.rb b/samples/client/petstore/ruby/lib/pet_api.rb deleted file mode 100644 index b15198588aa..00000000000 --- a/samples/client/petstore/ruby/lib/pet_api.rb +++ /dev/null @@ -1,313 +0,0 @@ -require "uri" - -class PetApi - basePath = "http://petstore.swagger.io/v2" - # apiInvoker = APIInvoker - - # Update an existing pet - # - # @param [Hash] opts the optional parameters - # @option opts [Pet] :body Pet object that needs to be added to the store - # @return void - def self.update_pet(opts = {}) - - - # resource path - path = "/pet".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = ['application/json', 'application/xml', ] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - 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 - - # 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 - def self.add_pet(opts = {}) - - - # resource path - path = "/pet".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = ['application/json', 'application/xml', ] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - 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 - - # 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] - def self.find_pets_by_status(opts = {}) - - - # resource path - path = "/pet/findByStatus".sub('{format}','json') - - # query parameters - query_params = {} - query_params[:'status'] = opts[:'status'] if opts[:'status'] - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - 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 - - # 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] - def self.find_pets_by_tags(opts = {}) - - - # resource path - path = "/pet/findByTags".sub('{format}','json') - - # query parameters - query_params = {} - query_params[:'tags'] = opts[:'tags'] if opts[:'tags'] - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - 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 - - # 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 - def self.get_pet_by_id(pet_id, opts = {}) - - # verify the required parameter 'pet_id' is set - raise "Missing the required parameter 'pet_id' when calling get_pet_by_id" if pet_id.nil? - - - # resource path - path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - 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 - - # Updates a pet in the store with form data - # - # @param pet_id ID of pet that needs to be updated - # @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 - def self.update_pet_with_form(pet_id, opts = {}) - - # verify the required parameter 'pet_id' is set - raise "Missing the required parameter 'pet_id' when calling update_pet_with_form" if pet_id.nil? - - - # resource path - path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = ['application/x-www-form-urlencoded', ] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - form_params["name"] = opts[:'name'] if opts[:'name'] - form_params["status"] = opts[:'status'] if opts[:'status'] - - # http body (model) - post_body = nil - - - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end - - # Deletes a pet - # - # @param pet_id Pet id to delete - # @param [Hash] opts the optional parameters - # @option opts [string] :api_key - # @return void - def self.delete_pet(pet_id, opts = {}) - - # verify the required parameter 'pet_id' is set - raise "Missing the required parameter 'pet_id' when calling delete_pet" if pet_id.nil? - - - # resource path - path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - header_params[:'api_key'] = opts[:'api_key'] if opts[:'api_key'] - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end - - # uploads an image - # - # @param pet_id ID of pet to update - # @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 - def self.upload_file(pet_id, opts = {}) - - # verify the required parameter 'pet_id' is set - raise "Missing the required parameter 'pet_id' when calling upload_file" if pet_id.nil? - - - # resource path - path = "/pet/{petId}/uploadImage".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = ['multipart/form-data', ] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - form_params["additionalMetadata"] = opts[:'additional_metadata'] if opts[:'additional_metadata'] - form_params["file"] = opts[:'file'] if opts[:'file'] - - # http body (model) - post_body = nil - - - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end -end diff --git a/samples/client/petstore/ruby/lib/store_api.rb b/samples/client/petstore/ruby/lib/store_api.rb deleted file mode 100644 index c6d670cd8c0..00000000000 --- a/samples/client/petstore/ruby/lib/store_api.rb +++ /dev/null @@ -1,154 +0,0 @@ -require "uri" - -class StoreApi - basePath = "http://petstore.swagger.io/v2" - # apiInvoker = APIInvoker - - # Returns pet inventories by status - # Returns a map of status codes to quantities - # @param [Hash] opts the optional parameters - # @return map[string,int] - def self.get_inventory(opts = {}) - - - # resource path - path = "/store/inventory".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - 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 - - # Place an order for a pet - # - # @param [Hash] opts the optional parameters - # @option opts [Order] :body order placed for purchasing the pet - # @return Order - def self.place_order(opts = {}) - - - # resource path - path = "/store/order".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) - - - 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 - - # 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 - def self.get_order_by_id(order_id, opts = {}) - - # verify the required parameter 'order_id' is set - raise "Missing the required parameter 'order_id' when calling get_order_by_id" if order_id.nil? - - - # resource path - path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - 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 - - # 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 - def self.delete_order(order_id, opts = {}) - - # verify the required parameter 'order_id' is set - raise "Missing the required parameter 'order_id' when calling delete_order" if order_id.nil? - - - # resource path - path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end -end diff --git a/samples/client/petstore/ruby/lib/swagger-client.rb b/samples/client/petstore/ruby/lib/swagger-client.rb deleted file mode 100644 index b13f83b1dbc..00000000000 --- a/samples/client/petstore/ruby/lib/swagger-client.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'monkey' -require 'swagger' - -Dir[File.join(File.dirname(__FILE__), "../lib/*.rb")].each {|file| require file if file !~ /swagger-client\.rb\z/ } -Dir[File.join(File.dirname(__FILE__), "../models/*.rb")].each {|file| require file } diff --git a/samples/client/petstore/ruby/lib/swagger.rb b/samples/client/petstore/ruby/lib/swagger.rb deleted file mode 100644 index f393330b148..00000000000 --- a/samples/client/petstore/ruby/lib/swagger.rb +++ /dev/null @@ -1,86 +0,0 @@ -require 'monkey' -require 'swagger/configuration' -require 'swagger/request' -require 'swagger/response' -require 'swagger/version' -require 'logger' -require 'json' - -module Swagger - - @configuration = Configuration.new - - class << self - attr_accessor :logger - - # A Swagger configuration object. Must act like a hash and return sensible - # values for all Swagger configuration options. See Swagger::Configuration. - attr_accessor :configuration - - attr_accessor :resources - - # Call this method to modify defaults in your initializers. - # - # @example - # Swagger.configure do |config| - # config.api_key = '1234567890abcdef' # required - # config.username = 'wordlover' # optional, but needed for user-related functions - # config.password = 'i<3words' # optional, but needed for user-related functions - # config.format = 'json' # optional, defaults to 'json' - # end - # - def configure - yield(configuration) if block_given? - - # Configure logger. Default to use Rails - self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT)) - - # remove :// from scheme - configuration.scheme.sub!(/:\/\//, '') - - # remove http(s):// and anything after a slash - configuration.host.sub!(/https?:\/\//, '') - configuration.host = configuration.host.split('/').first - - # Add leading and trailing slashes to base_path - configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') - configuration.base_path = "" if configuration.base_path == "/" - end - - def authenticated? - Swagger.configuration.auth_token.present? - end - - def de_authenticate - Swagger.configuration.auth_token = nil - end - - def authenticate - return if Swagger.authenticated? - - if Swagger.configuration.username.blank? || Swagger.configuration.password.blank? - raise ClientError, "Username and password are required to authenticate." - end - - request = Swagger::Request.new( - :get, - "account/authenticate/{username}", - :params => { - :username => Swagger.configuration.username, - :password => Swagger.configuration.password - } - ) - - response_body = request.response.body - Swagger.configuration.auth_token = response_body['token'] - end - - end - -end - -class ServerError < StandardError -end - -class ClientError < StandardError -end diff --git a/samples/client/petstore/ruby/lib/swagger/configuration.rb b/samples/client/petstore/ruby/lib/swagger/configuration.rb deleted file mode 100644 index 2a3728483f5..00000000000 --- a/samples/client/petstore/ruby/lib/swagger/configuration.rb +++ /dev/null @@ -1,22 +0,0 @@ -module Swagger - - class Configuration - require 'swagger/version' - - attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent - - # Defaults go in here.. - def initialize - @format = 'json' - @scheme = 'http' - @host = 'petstore.swagger.io' - @base_path = '/v2' - @user_agent = "ruby-swagger-#{Swagger::VERSION}" - @inject_format = false - @force_ending_format = false - @camelize_params = true - end - - end - -end diff --git a/samples/client/petstore/ruby/lib/swagger/request.rb b/samples/client/petstore/ruby/lib/swagger/request.rb deleted file mode 100644 index 4ec071b93d5..00000000000 --- a/samples/client/petstore/ruby/lib/swagger/request.rb +++ /dev/null @@ -1,263 +0,0 @@ -module Swagger - - class Request - require 'uri' - require 'addressable/uri' - require 'typhoeus' - require "swagger/version" - - attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params - - - # All requests must have an HTTP method and a path - # Optionals parameters are :params, :headers, :body, :format, :host - # - def initialize(http_method, path, attributes={}) - attributes[:format] ||= Swagger.configuration.format - attributes[:params] ||= {} - - # Set default headers - default_headers = { - 'Content-Type' => "application/#{attributes[:format].downcase}", - :api_key => Swagger.configuration.api_key, - 'User-Agent' => Swagger.configuration.user_agent - } - - # api_key from headers hash trumps the default, even if its value is blank - if attributes[:headers].present? && attributes[:headers].has_key?(:api_key) - default_headers.delete(:api_key) - end - - # api_key from params hash trumps all others (headers and default_headers) - if attributes[:params].present? && attributes[:params].has_key?(:api_key) - default_headers.delete(:api_key) - attributes[:headers].delete(:api_key) if attributes[:headers].present? - end - - # Merge argument headers into defaults - attributes[:headers] = default_headers.merge(attributes[:headers] || {}) - - # Stick in the auth token if there is one - if Swagger.authenticated? - attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) - end - - self.http_method = http_method.to_sym - self.path = path - attributes.each do |name, value| - send("#{name.to_s.underscore.to_sym}=", value) - end - end - - # Construct a base URL - # - def url(options = {}) - u = Addressable::URI.new( - :scheme => Swagger.configuration.scheme, - :host => Swagger.configuration.host, - :path => self.interpreted_path, - :query => self.query_string.sub(/\?/, '') - ).to_s - - # Drop trailing question mark, if present - u.sub! /\?$/, '' - - # Obfuscate API key? - u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated] - - u - end - - # Iterate over the params hash, injecting any path values into the path string - # - # e.g. /word.{format}/{word}/entries => /word.json/cat/entries - def interpreted_path - p = self.path.dup - - # Stick a .{format} placeholder into the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words.{format}/blah - if Swagger.configuration.inject_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = p.sub(/^(\/?\w+)/, "\\1.#{format}") - end - end - - # Stick a .{format} placeholder on the end of the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words/blah.{format} - if Swagger.configuration.force_ending_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = "#{p}.#{format}" - end - end - - p = p.sub("{format}", self.format.to_s) - - URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') - end - - # Massage the request body into a state of readiness - # If body is a hash, camelize all keys then convert to a json string - # - def body=(value) - if value.is_a?(Hash) - value = value.inject({}) do |memo, (k,v)| - memo[k.to_s.camelize(:lower).to_sym] = v - memo - end - end - @body = value - end - - # If body is an object, JSONify it before making the actual request. - # For form parameters, remove empty value - def outgoing_body - # http form - if @body.nil? && @form_params && !@form_params.empty? - data = form_params.dup - data.each do |key, value| - data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter - end - data - else # http body is JSON - @body.is_a?(String) ? @body : @body.to_json - end - end - - # Construct a query string from the query-string-type params - def query_string - - # Iterate over all params, - # .. removing the ones that are part of the path itself. - # .. stringifying values so Addressable doesn't blow up. - query_values = {} - self.params.each_pair do |key, value| - next if self.path.include? "{#{key}}" # skip path params - next if value.blank? && value.class != FalseClass # skip empties - if Swagger.configuration.camelize_params - key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param - end - query_values[key] = value.to_s - end - - # We don't want to end up with '?' as our query string - # if there aren't really any params - return "" if query_values.blank? - - # Addressable requires query_values to be set after initialization.. - qs = Addressable::URI.new - qs.query_values = query_values - qs.to_s - end - - def make - #TODO use configuration setting to determine if debugging - #logger = Logger.new STDOUT - #logger.debug self.url - response = case self.http_method.to_sym - when :get,:GET - Typhoeus::Request.get( - self.url, - :headers => self.headers.stringify_keys, - ) - - when :post,:POST - Typhoeus::Request.post( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :patch,:PATCH - Typhoeus::Request.patch( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :put,:PUT - Typhoeus::Request.put( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :delete,:DELETE - Typhoeus::Request.delete( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - end - Response.new(response) - end - - def response - self.make - end - - def response_code_pretty - return unless @response.present? - @response.code.to_s - end - - def response_headers_pretty - return unless @response.present? - # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient - @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus - end - - # return 'Accept' based on an array of accept provided - # @param [Array] header_accept_array Array fo 'Accept' - # @return String Accept (e.g. application/json) - def self.select_header_accept header_accept_array - if header_accept_array.empty? - return - elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # look for json data by default - else - header_accept_array.join(',') - end - end - - # return the content type based on an array of content-type provided - # @param [Array] content_type_array Array fo content-type - # @return String Content-Type (e.g. application/json) - def self.select_header_content_type content_type_array - if content_type_array.empty? - 'application/json' # use application/json by default - elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # use application/json if it's included - else - content_type_array[0]; # otherwise, use the first one - end - end - - # static method to convert object (array, hash, object, etc) to JSON string - # @param model object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_http_body model - return if model.nil? - _body = nil - if model.is_a?(Array) - _body = model.map{|m| object_to_hash(m) } - else - _body = object_to_hash(model) - end - _body.to_json - end - - # static method to convert object(non-array) to hash - # @param obj object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_hash obj - if obj.respond_to?(:to_hash) - obj.to_hash - else - obj - end - end - - end -end diff --git a/samples/client/petstore/ruby/lib/swagger/response.rb b/samples/client/petstore/ruby/lib/swagger/response.rb deleted file mode 100644 index 641b7ccc756..00000000000 --- a/samples/client/petstore/ruby/lib/swagger/response.rb +++ /dev/null @@ -1,70 +0,0 @@ -module Swagger - - class Response - require 'json' - - attr_accessor :raw - - def initialize(raw) - self.raw = raw - - case self.code - when 500..510 then raise(ServerError, self.error_message) - when 299..426 then raise(ClientError, self.error_message) - end - end - - def code - raw.code - end - - # Account for error messages that take different forms... - def error_message - body['message'] - rescue - body - end - - # If body is JSON, parse it - # Otherwise return raw string - def body - JSON.parse(raw.body, :symbolize_names => true) - rescue - raw.body - end - - # `headers_hash` is a Typhoeus-specific extension of Hash, - # so simplify it back into a regular old Hash. - def headers - h = {} - raw.headers_hash.each {|k,v| h[k] = v } - h - end - - # Extract the response format from the header hash - # e.g. {'Content-Type' => 'application/json'} - def format - headers['Content-Type'].split("/").last.downcase - end - - def json? - format == 'json' - end - - def xml? - format == 'xml' - end - - def pretty_body - return unless body.present? - case format - when 'json' then JSON.pretty_generate(body).gsub(/\n/, '
') - end - end - - def pretty_headers - JSON.pretty_generate(headers).gsub(/\n/, '
') - end - - end -end diff --git a/samples/client/petstore/ruby/lib/swagger/version.rb b/samples/client/petstore/ruby/lib/swagger/version.rb deleted file mode 100644 index 39357c0ed6d..00000000000 --- a/samples/client/petstore/ruby/lib/swagger/version.rb +++ /dev/null @@ -1,4 +0,0 @@ -module Swagger - VERSION = "4.06.08" -end - diff --git a/samples/client/petstore/ruby/lib/swagger_client.rb b/samples/client/petstore/ruby/lib/swagger_client.rb new file mode 100644 index 00000000000..6d239185005 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client.rb @@ -0,0 +1,25 @@ +# Swagger common files +require 'swagger_client/monkey' +require 'swagger_client/swagger' +require 'swagger_client/swagger/configuration' +require 'swagger_client/swagger/request' +require 'swagger_client/swagger/response' +require 'swagger_client/swagger/version' + +# Models +require 'swagger_client/models/base_object' +require 'swagger_client/models/user' +require 'swagger_client/models/category' +require 'swagger_client/models/pet' +require 'swagger_client/models/tag' +require 'swagger_client/models/order' + +# APIs +require 'swagger_client/api/user_api' +require 'swagger_client/api/pet_api' +require 'swagger_client/api/store_api' + +module SwaggerClient + # Initialize the default configuration + Swagger.configuration ||= Swagger::Configuration.new +end 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 new file mode 100644 index 00000000000..d89cb6ae566 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb @@ -0,0 +1,315 @@ +require "uri" + +module SwaggerClient + class PetApi + basePath = "http://petstore.swagger.io/v2" + # apiInvoker = APIInvoker + + # Update an existing pet + # + # @param [Hash] opts the optional parameters + # @option opts [Pet] :body Pet object that needs to be added to the store + # @return void + def self.update_pet(opts = {}) + + + # resource path + path = "/pet".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = ['application/json', 'application/xml'] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + 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 + + # 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 + def self.add_pet(opts = {}) + + + # resource path + path = "/pet".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = ['application/json', 'application/xml'] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + 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 + + # 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] + def self.find_pets_by_status(opts = {}) + + + # resource path + path = "/pet/findByStatus".sub('{format}','json') + + # query parameters + query_params = {} + query_params[:'status'] = opts[:'status'] if opts[:'status'] + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + 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 + + # 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] + def self.find_pets_by_tags(opts = {}) + + + # resource path + path = "/pet/findByTags".sub('{format}','json') + + # query parameters + query_params = {} + query_params[:'tags'] = opts[:'tags'] if opts[:'tags'] + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + 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 + + # 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 + def self.get_pet_by_id(pet_id, opts = {}) + + # verify the required parameter 'pet_id' is set + raise "Missing the required parameter 'pet_id' when calling get_pet_by_id" if pet_id.nil? + + + # resource path + path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + 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 + + # Updates a pet in the store with form data + # + # @param pet_id ID of pet that needs to be updated + # @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 + def self.update_pet_with_form(pet_id, opts = {}) + + # verify the required parameter 'pet_id' is set + raise "Missing the required parameter 'pet_id' when calling update_pet_with_form" if pet_id.nil? + + + # resource path + path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = ['application/x-www-form-urlencoded'] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + form_params["name"] = opts[:'name'] if opts[:'name'] + form_params["status"] = opts[:'status'] if opts[:'status'] + + # http body (model) + post_body = nil + + + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + + # Deletes a pet + # + # @param pet_id Pet id to delete + # @param [Hash] opts the optional parameters + # @option opts [string] :api_key + # @return void + def self.delete_pet(pet_id, opts = {}) + + # verify the required parameter 'pet_id' is set + raise "Missing the required parameter 'pet_id' when calling delete_pet" if pet_id.nil? + + + # resource path + path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params[:'api_key'] = opts[:'api_key'] if opts[:'api_key'] + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + + # uploads an image + # + # @param pet_id ID of pet to update + # @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 + def self.upload_file(pet_id, opts = {}) + + # verify the required parameter 'pet_id' is set + raise "Missing the required parameter 'pet_id' when calling upload_file" if pet_id.nil? + + + # resource path + path = "/pet/{petId}/uploadImage".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = ['multipart/form-data'] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + form_params["additionalMetadata"] = opts[:'additional_metadata'] if opts[:'additional_metadata'] + form_params["file"] = opts[:'file'] if opts[:'file'] + + # http body (model) + post_body = nil + + + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + 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 new file mode 100644 index 00000000000..37595c2147e --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb @@ -0,0 +1,156 @@ +require "uri" + +module SwaggerClient + class StoreApi + basePath = "http://petstore.swagger.io/v2" + # apiInvoker = APIInvoker + + # Returns pet inventories by status + # Returns a map of status codes to quantities + # @param [Hash] opts the optional parameters + # @return map[string,int] + def self.get_inventory(opts = {}) + + + # resource path + path = "/store/inventory".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + 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 + + # Place an order for a pet + # + # @param [Hash] opts the optional parameters + # @option opts [Order] :body order placed for purchasing the pet + # @return Order + def self.place_order(opts = {}) + + + # resource path + path = "/store/order".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = Swagger::Request.object_to_http_body(opts[:'body']) + + + 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 + + # 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 + def self.get_order_by_id(order_id, opts = {}) + + # verify the required parameter 'order_id' is set + raise "Missing the required parameter 'order_id' when calling get_order_by_id" if order_id.nil? + + + # resource path + path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + 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 + + # 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 + def self.delete_order(order_id, opts = {}) + + # verify the required parameter 'order_id' is set + raise "Missing the required parameter 'order_id' when calling delete_order" if order_id.nil? + + + # resource path + path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + 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 new file mode 100644 index 00000000000..12a45561e3f --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb @@ -0,0 +1,302 @@ +require "uri" + +module SwaggerClient + class UserApi + basePath = "http://petstore.swagger.io/v2" + # apiInvoker = APIInvoker + + # Create user + # 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 + def self.create_user(opts = {}) + + + # resource path + path = "/user".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + 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 + + # 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 + def self.create_users_with_array_input(opts = {}) + + + # resource path + path = "/user/createWithArray".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + 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 + + # 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 + def self.create_users_with_list_input(opts = {}) + + + # resource path + path = "/user/createWithList".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + 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 + + # 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 + def self.login_user(opts = {}) + + + # resource path + path = "/user/login".sub('{format}','json') + + # query parameters + query_params = {} + query_params[:'username'] = opts[:'username'] if opts[:'username'] + query_params[:'password'] = opts[:'password'] if opts[:'password'] + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + 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 + + # Logs out current logged in user session + # + # @param [Hash] opts the optional parameters + # @return void + def self.logout_user(opts = {}) + + + # resource path + path = "/user/logout".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + Swagger::Request.new(:GET, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + 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 + def self.get_user_by_name(username, opts = {}) + + # verify the required parameter 'username' is set + raise "Missing the required parameter 'username' when calling get_user_by_name" if username.nil? + + + # resource path + path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + 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 + + # 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 + def self.update_user(username, opts = {}) + + # verify the required parameter 'username' is set + raise "Missing the required parameter 'username' when calling update_user" if username.nil? + + + # resource path + path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + 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 + + # 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 + def self.delete_user(username, opts = {}) + + # verify the required parameter 'username' is set + raise "Missing the required parameter 'username' when calling delete_user" if username.nil? + + + # resource path + path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + + # HTTP header 'Content-Type' + _header_content_type = [] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + + Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/base_object.rb b/samples/client/petstore/ruby/lib/swagger_client/models/base_object.rb new file mode 100644 index 00000000000..642e4769e55 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/models/base_object.rb @@ -0,0 +1,83 @@ +module SwaggerClient + # base class containing fundamental method such as to_hash, build_from_hash and more + class BaseObject + + # return the object in the form of hash + def to_body + body = {} + self.class.attribute_map.each_pair do |key, value| + body[value] = self.send(key) unless self.send(key).nil? + end + body + end + + # build the object from hash + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /^array\[(.*)\]/i + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + else + #TODO show warning in debug mode + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + else + # data not found in attributes(hash), not an issue as the data can be optional + end + end + + self + end + + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :string + value.to_s + when :int + value.to_i + when :double + value.to_f + when :boolean + if value =~ /^(true|t|yes|y|1)$/i + true + else + false + end + else # model + _model = SwaggerClient.const_get(type).new + _model.build_from_hash(value) + end + end + + # to_body is an alias to to_body (backward compatibility) + def to_hash + hash = {} + self.class.attribute_map.each_pair do |key, value| + if self.send(key).is_a?(Array) + next if self.send(key).empty? + hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil? + else + unless (_tmp_value = _to_hash self.send(key)).nil? + hash[value] = _tmp_value + end + end + end + hash + end + + # Method to output non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + def _to_hash(value) + if value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/category.rb b/samples/client/petstore/ruby/lib/swagger_client/models/category.rb new file mode 100644 index 00000000000..fe195c7ac87 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/models/category.rb @@ -0,0 +1,44 @@ +module SwaggerClient + # + class Category < BaseObject + attr_accessor :id, :name + # attribute mapping from ruby-style variable name to JSON key + def self.attribute_map + { + + # + :'id' => :'id', + + # + :'name' => :'name' + + } + end + + # attribute type + def self.swagger_types + { + :'id' => :'int', + :'name' => :'string' + + } + end + + def initialize(attributes = {}) + return if !attributes.is_a?(Hash) || attributes.empty? + + # convert string to symbol for hash key + attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + + + if attributes[:'id'] + @id = attributes[:'id'] + end + + if attributes[:'name'] + @name = attributes[:'name'] + end + + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/order.rb b/samples/client/petstore/ruby/lib/swagger_client/models/order.rb new file mode 100644 index 00000000000..3fe0282ed9b --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/models/order.rb @@ -0,0 +1,76 @@ +module SwaggerClient + # + class Order < BaseObject + attr_accessor :id, :pet_id, :quantity, :ship_date, :status, :complete + # attribute mapping from ruby-style variable name to JSON key + def self.attribute_map + { + + # + :'id' => :'id', + + # + :'pet_id' => :'petId', + + # + :'quantity' => :'quantity', + + # + :'ship_date' => :'shipDate', + + # Order Status + :'status' => :'status', + + # + :'complete' => :'complete' + + } + end + + # attribute type + def self.swagger_types + { + :'id' => :'int', + :'pet_id' => :'int', + :'quantity' => :'int', + :'ship_date' => :'DateTime', + :'status' => :'string', + :'complete' => :'boolean' + + } + end + + def initialize(attributes = {}) + return if !attributes.is_a?(Hash) || attributes.empty? + + # convert string to symbol for hash key + attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + + + if attributes[:'id'] + @id = attributes[:'id'] + end + + if attributes[:'petId'] + @pet_id = attributes[:'petId'] + end + + if attributes[:'quantity'] + @quantity = attributes[:'quantity'] + end + + if attributes[:'shipDate'] + @ship_date = attributes[:'shipDate'] + end + + if attributes[:'status'] + @status = attributes[:'status'] + end + + if attributes[:'complete'] + @complete = attributes[:'complete'] + end + + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/pet.rb b/samples/client/petstore/ruby/lib/swagger_client/models/pet.rb new file mode 100644 index 00000000000..32f95646c72 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/models/pet.rb @@ -0,0 +1,80 @@ +module SwaggerClient + # + class Pet < BaseObject + attr_accessor :id, :category, :name, :photo_urls, :tags, :status + # attribute mapping from ruby-style variable name to JSON key + def self.attribute_map + { + + # + :'id' => :'id', + + # + :'category' => :'category', + + # + :'name' => :'name', + + # + :'photo_urls' => :'photoUrls', + + # + :'tags' => :'tags', + + # pet status in the store + :'status' => :'status' + + } + end + + # attribute type + def self.swagger_types + { + :'id' => :'int', + :'category' => :'Category', + :'name' => :'string', + :'photo_urls' => :'array[string]', + :'tags' => :'array[Tag]', + :'status' => :'string' + + } + end + + def initialize(attributes = {}) + return if !attributes.is_a?(Hash) || attributes.empty? + + # convert string to symbol for hash key + attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + + + if attributes[:'id'] + @id = attributes[:'id'] + end + + if attributes[:'category'] + @category = attributes[:'category'] + end + + if attributes[:'name'] + @name = attributes[:'name'] + end + + if attributes[:'photoUrls'] + if (value = attributes[:'photoUrls']).is_a?(Array) + @photo_urls = value + end + end + + if attributes[:'tags'] + if (value = attributes[:'tags']).is_a?(Array) + @tags = value + end + end + + if attributes[:'status'] + @status = attributes[:'status'] + end + + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/tag.rb b/samples/client/petstore/ruby/lib/swagger_client/models/tag.rb new file mode 100644 index 00000000000..9c5cdde1af6 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/models/tag.rb @@ -0,0 +1,44 @@ +module SwaggerClient + # + class Tag < BaseObject + attr_accessor :id, :name + # attribute mapping from ruby-style variable name to JSON key + def self.attribute_map + { + + # + :'id' => :'id', + + # + :'name' => :'name' + + } + end + + # attribute type + def self.swagger_types + { + :'id' => :'int', + :'name' => :'string' + + } + end + + def initialize(attributes = {}) + return if !attributes.is_a?(Hash) || attributes.empty? + + # convert string to symbol for hash key + attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + + + if attributes[:'id'] + @id = attributes[:'id'] + end + + if attributes[:'name'] + @name = attributes[:'name'] + end + + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/user.rb b/samples/client/petstore/ruby/lib/swagger_client/models/user.rb new file mode 100644 index 00000000000..2d723da54c4 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/models/user.rb @@ -0,0 +1,92 @@ +module SwaggerClient + # + class User < BaseObject + attr_accessor :id, :username, :first_name, :last_name, :email, :password, :phone, :user_status + # attribute mapping from ruby-style variable name to JSON key + def self.attribute_map + { + + # + :'id' => :'id', + + # + :'username' => :'username', + + # + :'first_name' => :'firstName', + + # + :'last_name' => :'lastName', + + # + :'email' => :'email', + + # + :'password' => :'password', + + # + :'phone' => :'phone', + + # User Status + :'user_status' => :'userStatus' + + } + end + + # attribute type + def self.swagger_types + { + :'id' => :'int', + :'username' => :'string', + :'first_name' => :'string', + :'last_name' => :'string', + :'email' => :'string', + :'password' => :'string', + :'phone' => :'string', + :'user_status' => :'int' + + } + end + + def initialize(attributes = {}) + return if !attributes.is_a?(Hash) || attributes.empty? + + # convert string to symbol for hash key + attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + + + if attributes[:'id'] + @id = attributes[:'id'] + end + + if attributes[:'username'] + @username = attributes[:'username'] + end + + if attributes[:'firstName'] + @first_name = attributes[:'firstName'] + end + + if attributes[:'lastName'] + @last_name = attributes[:'lastName'] + end + + if attributes[:'email'] + @email = attributes[:'email'] + end + + if attributes[:'password'] + @password = attributes[:'password'] + end + + if attributes[:'phone'] + @phone = attributes[:'phone'] + end + + if attributes[:'userStatus'] + @user_status = attributes[:'userStatus'] + end + + end + end +end diff --git a/samples/client/petstore/ruby/lib/monkey.rb b/samples/client/petstore/ruby/lib/swagger_client/monkey.rb similarity index 100% rename from samples/client/petstore/ruby/lib/monkey.rb rename to samples/client/petstore/ruby/lib/swagger_client/monkey.rb diff --git a/samples/client/petstore/ruby/lib/swagger_client/swagger.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger.rb new file mode 100644 index 00000000000..278db36e4ca --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger.rb @@ -0,0 +1,78 @@ +require 'logger' +require 'json' + +module SwaggerClient + module Swagger + class << self + attr_accessor :logger + + # A Swagger configuration object. Must act like a hash and return sensible + # values for all Swagger configuration options. See Swagger::Configuration. + attr_accessor :configuration + + attr_accessor :resources + + # Call this method to modify defaults in your initializers. + # + # @example + # Swagger.configure do |config| + # config.api_key = '1234567890abcdef' # required + # config.username = 'wordlover' # optional, but needed for user-related functions + # config.password = 'i<3words' # optional, but needed for user-related functions + # config.format = 'json' # optional, defaults to 'json' + # end + # + def configure + yield(configuration) if block_given? + + # Configure logger. Default to use Rails + self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT)) + + # remove :// from scheme + configuration.scheme.sub!(/:\/\//, '') + + # remove http(s):// and anything after a slash + configuration.host.sub!(/https?:\/\//, '') + configuration.host = configuration.host.split('/').first + + # Add leading and trailing slashes to base_path + configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') + configuration.base_path = "" if configuration.base_path == "/" + end + + def authenticated? + Swagger.configuration.auth_token.present? + end + + def de_authenticate + Swagger.configuration.auth_token = nil + end + + def authenticate + return if Swagger.authenticated? + + if Swagger.configuration.username.blank? || Swagger.configuration.password.blank? + raise ClientError, "Username and password are required to authenticate." + end + + request = Swagger::Request.new( + :get, + "account/authenticate/{username}", + :params => { + :username => Swagger.configuration.username, + :password => Swagger.configuration.password + } + ) + + response_body = request.response.body + Swagger.configuration.auth_token = response_body['token'] + end + end + end + + class ServerError < StandardError + end + + class ClientError < StandardError + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/swagger/configuration.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/configuration.rb new file mode 100644 index 00000000000..51f9539a9ab --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/configuration.rb @@ -0,0 +1,19 @@ +module SwaggerClient + module Swagger + class Configuration + attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent + + # Defaults go in here.. + def initialize + @format = 'json' + @scheme = 'http' + @host = 'petstore.swagger.io' + @base_path = '/v2' + @user_agent = "ruby-swagger-#{Swagger::VERSION}" + @inject_format = false + @force_ending_format = false + @camelize_params = true + end + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/swagger/request.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/request.rb new file mode 100644 index 00000000000..d5f266267da --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/request.rb @@ -0,0 +1,257 @@ +module SwaggerClient + module Swagger + class Request + require 'uri' + require 'addressable/uri' + require 'typhoeus' + + attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params + + # All requests must have an HTTP method and a path + # Optionals parameters are :params, :headers, :body, :format, :host + def initialize(http_method, path, attributes={}) + attributes[:format] ||= Swagger.configuration.format + attributes[:params] ||= {} + + # Set default headers + default_headers = { + 'Content-Type' => "application/#{attributes[:format].downcase}", + :api_key => Swagger.configuration.api_key, + 'User-Agent' => Swagger.configuration.user_agent + } + + # api_key from headers hash trumps the default, even if its value is blank + if attributes[:headers].present? && attributes[:headers].has_key?(:api_key) + default_headers.delete(:api_key) + end + + # api_key from params hash trumps all others (headers and default_headers) + if attributes[:params].present? && attributes[:params].has_key?(:api_key) + default_headers.delete(:api_key) + attributes[:headers].delete(:api_key) if attributes[:headers].present? + end + + # Merge argument headers into defaults + attributes[:headers] = default_headers.merge(attributes[:headers] || {}) + + # Stick in the auth token if there is one + if Swagger.authenticated? + attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) + end + + self.http_method = http_method.to_sym + self.path = path + attributes.each do |name, value| + send("#{name.to_s.underscore.to_sym}=", value) + end + end + + # Construct a base URL + def url(options = {}) + u = Addressable::URI.new( + :scheme => Swagger.configuration.scheme, + :host => Swagger.configuration.host, + :path => self.interpreted_path, + :query => self.query_string.sub(/\?/, '') + ).to_s + + # Drop trailing question mark, if present + u.sub! /\?$/, '' + + # Obfuscate API key? + u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated] + + u + end + + # Iterate over the params hash, injecting any path values into the path string + # e.g. /word.{format}/{word}/entries => /word.json/cat/entries + def interpreted_path + p = self.path.dup + + # Stick a .{format} placeholder into the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words.{format}/blah + if Swagger.configuration.inject_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = p.sub(/^(\/?\w+)/, "\\1.#{format}") + end + end + + # Stick a .{format} placeholder on the end of the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words/blah.{format} + if Swagger.configuration.force_ending_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = "#{p}.#{format}" + end + end + + p = p.sub("{format}", self.format.to_s) + + URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') + end + + # Massage the request body into a state of readiness + # If body is a hash, camelize all keys then convert to a json string + def body=(value) + if value.is_a?(Hash) + value = value.inject({}) do |memo, (k,v)| + memo[k.to_s.camelize(:lower).to_sym] = v + memo + end + end + @body = value + end + + # If body is an object, JSONify it before making the actual request. + # For form parameters, remove empty value + def outgoing_body + # http form + if @body.nil? && @form_params && !@form_params.empty? + data = form_params.dup + data.each do |key, value| + data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter + end + data + else # http body is JSON + @body.is_a?(String) ? @body : @body.to_json + end + end + + # Construct a query string from the query-string-type params + def query_string + # Iterate over all params, + # .. removing the ones that are part of the path itself. + # .. stringifying values so Addressable doesn't blow up. + query_values = {} + self.params.each_pair do |key, value| + next if self.path.include? "{#{key}}" # skip path params + next if value.blank? && value.class != FalseClass # skip empties + if Swagger.configuration.camelize_params + key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param + end + query_values[key] = value.to_s + end + + # We don't want to end up with '?' as our query string + # if there aren't really any params + return "" if query_values.blank? + + # Addressable requires query_values to be set after initialization.. + qs = Addressable::URI.new + qs.query_values = query_values + qs.to_s + end + + def make + #TODO use configuration setting to determine if debugging + #logger = Logger.new STDOUT + #logger.debug self.url + response = case self.http_method.to_sym + when :get,:GET + Typhoeus::Request.get( + self.url, + :headers => self.headers.stringify_keys, + ) + + when :post,:POST + Typhoeus::Request.post( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :patch,:PATCH + Typhoeus::Request.patch( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :put,:PUT + Typhoeus::Request.put( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :delete,:DELETE + Typhoeus::Request.delete( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + end + Response.new(response) + end + + def response + self.make + end + + def response_code_pretty + return unless @response.present? + @response.code.to_s + end + + def response_headers_pretty + return unless @response.present? + # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient + @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus + end + + # return 'Accept' based on an array of accept provided + # @param [Array] header_accept_array Array fo 'Accept' + # @return String Accept (e.g. application/json) + def self.select_header_accept header_accept_array + if header_accept_array.empty? + return + elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # look for json data by default + else + header_accept_array.join(',') + end + end + + # return the content type based on an array of content-type provided + # @param [Array] content_type_array Array fo content-type + # @return String Content-Type (e.g. application/json) + def self.select_header_content_type content_type_array + if content_type_array.empty? + 'application/json' # use application/json by default + elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # use application/json if it's included + else + content_type_array[0]; # otherwise, use the first one + end + end + + # static method to convert object (array, hash, object, etc) to JSON string + # @param model object to be converted into JSON string + # @return string JSON string representation of the object + def self.object_to_http_body model + return if model.nil? + _body = nil + if model.is_a?(Array) + _body = model.map{|m| object_to_hash(m) } + else + _body = object_to_hash(model) + end + _body.to_json + end + + # static method to convert object(non-array) to hash + # @param obj object to be converted into JSON string + # @return string JSON string representation of the object + def self.object_to_hash obj + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end + end + + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb new file mode 100644 index 00000000000..538821bea69 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb @@ -0,0 +1,70 @@ +module SwaggerClient + module Swagger + class Response + require 'json' + + attr_accessor :raw + + def initialize(raw) + self.raw = raw + + case self.code + when 500..510 then raise(ServerError, self.error_message) + when 299..426 then raise(ClientError, self.error_message) + end + end + + def code + raw.code + end + + # Account for error messages that take different forms... + def error_message + body['message'] + rescue + body + end + + # If body is JSON, parse it + # Otherwise return raw string + def body + JSON.parse(raw.body, :symbolize_names => true) + rescue + raw.body + end + + # `headers_hash` is a Typhoeus-specific extension of Hash, + # so simplify it back into a regular old Hash. + def headers + h = {} + raw.headers_hash.each {|k,v| h[k] = v } + h + end + + # Extract the response format from the header hash + # e.g. {'Content-Type' => 'application/json'} + def format + headers['Content-Type'].split("/").last.downcase + end + + def json? + format == 'json' + end + + def xml? + format == 'xml' + end + + def pretty_body + return unless body.present? + case format + when 'json' then JSON.pretty_generate(body).gsub(/\n/, '
') + end + end + + def pretty_headers + JSON.pretty_generate(headers).gsub(/\n/, '
') + end + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/swagger/version.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/version.rb new file mode 100644 index 00000000000..c6e8d5aee53 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/version.rb @@ -0,0 +1,5 @@ +module SwaggerClient + module Swagger + VERSION = "1.0.0" + end +end diff --git a/samples/client/petstore/ruby/lib/user_api.rb b/samples/client/petstore/ruby/lib/user_api.rb deleted file mode 100644 index e7d0644d320..00000000000 --- a/samples/client/petstore/ruby/lib/user_api.rb +++ /dev/null @@ -1,300 +0,0 @@ -require "uri" - -class UserApi - basePath = "http://petstore.swagger.io/v2" - # apiInvoker = APIInvoker - - # Create user - # 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 - def self.create_user(opts = {}) - - - # resource path - path = "/user".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - 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 - - # 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 - def self.create_users_with_array_input(opts = {}) - - - # resource path - path = "/user/createWithArray".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - 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 - - # 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 - def self.create_users_with_list_input(opts = {}) - - - # resource path - path = "/user/createWithList".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - 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 - - # 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 - def self.login_user(opts = {}) - - - # resource path - path = "/user/login".sub('{format}','json') - - # query parameters - query_params = {} - query_params[:'username'] = opts[:'username'] if opts[:'username'] - query_params[:'password'] = opts[:'password'] if opts[:'password'] - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - 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 - - # Logs out current logged in user session - # - # @param [Hash] opts the optional parameters - # @return void - def self.logout_user(opts = {}) - - - # resource path - path = "/user/logout".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - Swagger::Request.new(:GET, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - 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 - def self.get_user_by_name(username, opts = {}) - - # verify the required parameter 'username' is set - raise "Missing the required parameter 'username' when calling get_user_by_name" if username.nil? - - - # resource path - path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - 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 - - # 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 - def self.update_user(username, opts = {}) - - # verify the required parameter 'username' is set - raise "Missing the required parameter 'username' when calling update_user" if username.nil? - - - # resource path - path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - 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 - - # 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 - def self.delete_user(username, opts = {}) - - # verify the required parameter 'username' is set - raise "Missing the required parameter 'username' when calling delete_user" if username.nil? - - - # resource path - path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end -end diff --git a/samples/client/petstore/ruby/models/base_object.rb b/samples/client/petstore/ruby/models/base_object.rb deleted file mode 100644 index ecad551c77b..00000000000 --- a/samples/client/petstore/ruby/models/base_object.rb +++ /dev/null @@ -1,83 +0,0 @@ -# base class containing fundamental method such as to_hash, build_from_hash and more -class BaseObject - - # return the object in the form of hash - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? - end - body - end - - # build the object from hash - def build_from_hash(attributes) - return nil unless attributes.is_a?(Hash) - self.class.swagger_types.each_pair do |key, type| - if type =~ /^array\[(.*)\]/i - if attributes[self.class.attribute_map[key]].is_a?(Array) - self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) - else - #TODO show warning in debug mode - end - elsif !attributes[self.class.attribute_map[key]].nil? - self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) - else - # data not found in attributes(hash), not an issue as the data can be optional - end - end - - self - end - - def _deserialize(type, value) - case type.to_sym - when :DateTime - DateTime.parse(value) - when :string - value.to_s - when :int - value.to_i - when :double - value.to_f - when :boolean - if value =~ /^(true|t|yes|y|1)$/i - true - else - false - end - else # model - _model = Object.const_get(type).new - _model.build_from_hash(value) - end - end - - - - # to_body is an alias to to_body (backward compatibility) - def to_hash - hash = {} - self.class.attribute_map.each_pair do |key, value| - if self.send(key).is_a?(Array) - next if self.send(key).empty? - hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil? - else - unless (_tmp_value = _to_hash self.send(key)).nil? - hash[value] = _tmp_value - end - end - end - hash - end - - # Method to output non-array value in the form of hash - # For object, use to_hash. Otherwise, just return the value - def _to_hash(value) - if value.respond_to? :to_hash - value.to_hash - else - value - end - end - -end diff --git a/samples/client/petstore/ruby/models/category.rb b/samples/client/petstore/ruby/models/category.rb deleted file mode 100644 index c1da69482e0..00000000000 --- a/samples/client/petstore/ruby/models/category.rb +++ /dev/null @@ -1,45 +0,0 @@ -require_relative 'base_object' - -# -class Category < BaseObject - attr_accessor :id, :name - # attribute mapping from ruby-style variable name to JSON key - def self.attribute_map - { - - # - :'id' => :'id', - - # - :'name' => :'name' - - } - end - - # attribute type - def self.swagger_types - { - :'id' => :'int', - :'name' => :'string' - - } - end - - def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? - - # convert string to symbol for hash key - attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} - - - if attributes[:'id'] - @id = attributes[:'id'] - end - - if attributes[:'name'] - @name = attributes[:'name'] - end - - end - -end diff --git a/samples/client/petstore/ruby/models/order.rb b/samples/client/petstore/ruby/models/order.rb deleted file mode 100644 index 6347167c860..00000000000 --- a/samples/client/petstore/ruby/models/order.rb +++ /dev/null @@ -1,77 +0,0 @@ -require_relative 'base_object' - -# -class Order < BaseObject - attr_accessor :id, :pet_id, :quantity, :ship_date, :status, :complete - # attribute mapping from ruby-style variable name to JSON key - def self.attribute_map - { - - # - :'id' => :'id', - - # - :'pet_id' => :'petId', - - # - :'quantity' => :'quantity', - - # - :'ship_date' => :'shipDate', - - # Order Status - :'status' => :'status', - - # - :'complete' => :'complete' - - } - end - - # attribute type - def self.swagger_types - { - :'id' => :'int', - :'pet_id' => :'int', - :'quantity' => :'int', - :'ship_date' => :'DateTime', - :'status' => :'string', - :'complete' => :'boolean' - - } - end - - def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? - - # convert string to symbol for hash key - attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} - - - if attributes[:'id'] - @id = attributes[:'id'] - end - - if attributes[:'petId'] - @pet_id = attributes[:'petId'] - end - - if attributes[:'quantity'] - @quantity = attributes[:'quantity'] - end - - if attributes[:'shipDate'] - @ship_date = attributes[:'shipDate'] - end - - if attributes[:'status'] - @status = attributes[:'status'] - end - - if attributes[:'complete'] - @complete = attributes[:'complete'] - end - - end - -end diff --git a/samples/client/petstore/ruby/models/pet.rb b/samples/client/petstore/ruby/models/pet.rb deleted file mode 100644 index 9accf4d1c81..00000000000 --- a/samples/client/petstore/ruby/models/pet.rb +++ /dev/null @@ -1,81 +0,0 @@ -require_relative 'base_object' - -# -class Pet < BaseObject - attr_accessor :id, :category, :name, :photo_urls, :tags, :status - # attribute mapping from ruby-style variable name to JSON key - def self.attribute_map - { - - # - :'id' => :'id', - - # - :'category' => :'category', - - # - :'name' => :'name', - - # - :'photo_urls' => :'photoUrls', - - # - :'tags' => :'tags', - - # pet status in the store - :'status' => :'status' - - } - end - - # attribute type - def self.swagger_types - { - :'id' => :'int', - :'category' => :'Category', - :'name' => :'string', - :'photo_urls' => :'array[string]', - :'tags' => :'array[Tag]', - :'status' => :'string' - - } - end - - def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? - - # convert string to symbol for hash key - attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} - - - if attributes[:'id'] - @id = attributes[:'id'] - end - - if attributes[:'category'] - @category = attributes[:'category'] - end - - if attributes[:'name'] - @name = attributes[:'name'] - end - - if attributes[:'photoUrls'] - if (value = attributes[:'photoUrls']).is_a?(Array) - @photo_urls = value - end - end - - if attributes[:'tags'] - if (value = attributes[:'tags']).is_a?(Array) - @tags = value - end - end - - if attributes[:'status'] - @status = attributes[:'status'] - end - - end - -end diff --git a/samples/client/petstore/ruby/models/tag.rb b/samples/client/petstore/ruby/models/tag.rb deleted file mode 100644 index 7eb332a3218..00000000000 --- a/samples/client/petstore/ruby/models/tag.rb +++ /dev/null @@ -1,45 +0,0 @@ -require_relative 'base_object' - -# -class Tag < BaseObject - attr_accessor :id, :name - # attribute mapping from ruby-style variable name to JSON key - def self.attribute_map - { - - # - :'id' => :'id', - - # - :'name' => :'name' - - } - end - - # attribute type - def self.swagger_types - { - :'id' => :'int', - :'name' => :'string' - - } - end - - def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? - - # convert string to symbol for hash key - attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} - - - if attributes[:'id'] - @id = attributes[:'id'] - end - - if attributes[:'name'] - @name = attributes[:'name'] - end - - end - -end diff --git a/samples/client/petstore/ruby/models/user.rb b/samples/client/petstore/ruby/models/user.rb deleted file mode 100644 index 20420e1c69b..00000000000 --- a/samples/client/petstore/ruby/models/user.rb +++ /dev/null @@ -1,93 +0,0 @@ -require_relative 'base_object' - -# -class User < BaseObject - attr_accessor :id, :username, :first_name, :last_name, :email, :password, :phone, :user_status - # attribute mapping from ruby-style variable name to JSON key - def self.attribute_map - { - - # - :'id' => :'id', - - # - :'username' => :'username', - - # - :'first_name' => :'firstName', - - # - :'last_name' => :'lastName', - - # - :'email' => :'email', - - # - :'password' => :'password', - - # - :'phone' => :'phone', - - # User Status - :'user_status' => :'userStatus' - - } - end - - # attribute type - def self.swagger_types - { - :'id' => :'int', - :'username' => :'string', - :'first_name' => :'string', - :'last_name' => :'string', - :'email' => :'string', - :'password' => :'string', - :'phone' => :'string', - :'user_status' => :'int' - - } - end - - def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? - - # convert string to symbol for hash key - attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} - - - if attributes[:'id'] - @id = attributes[:'id'] - end - - if attributes[:'username'] - @username = attributes[:'username'] - end - - if attributes[:'firstName'] - @first_name = attributes[:'firstName'] - end - - if attributes[:'lastName'] - @last_name = attributes[:'lastName'] - end - - if attributes[:'email'] - @email = attributes[:'email'] - end - - if attributes[:'password'] - @password = attributes[:'password'] - end - - if attributes[:'phone'] - @phone = attributes[:'phone'] - end - - if attributes[:'userStatus'] - @user_status = attributes[:'userStatus'] - end - - end - -end diff --git a/samples/client/petstore/ruby/spec/pet_spec.rb b/samples/client/petstore/ruby/spec/pet_spec.rb index 90df1cd821b..f66f33cf84c 100644 --- a/samples/client/petstore/ruby/spec/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/pet_spec.rb @@ -6,17 +6,17 @@ describe "Pet" do configure_swagger prepare_pet end - + describe "pet methods" do it "should construct a new pet object" do - tag1 = Tag.new({'id' => 1, 'name'=> 'tag1'}) - tag2 = Tag.new({'id' => 2, 'name'=> 'tag2'}) - category1 = Category.new({:id => 1, :name => 'category unknown'}) + tag1 = SwaggerClient::Tag.new({'id' => 1, 'name'=> 'tag1'}) + tag2 = SwaggerClient::Tag.new({'id' => 2, 'name'=> 'tag2'}) + category1 = SwaggerClient::Category.new({:id => 1, :name => 'category unknown'}) # initalize using both string and symbol key pet_hash = {:'id' => 10002, :'name' => "RUBY UNIT TESTING", :'status' => "pending", :'photo_urls' => ["url1", "url2"], :'category' => category1, :'tags' => [tag1, tag2]} - pet = Pet.new(pet_hash) + pet = SwaggerClient::Pet.new(pet_hash) # test new pet.name.should == "RUBY UNIT TESTING" pet.status.should == "pending" @@ -26,7 +26,7 @@ describe "Pet" do pet.category.name.should == 'category unknown' # test build_from_hash - pet2 = Pet.new + pet2 = SwaggerClient::Pet.new pet2.build_from_hash(pet.to_hash) pet.to_hash.should == pet2.to_hash @@ -37,8 +37,8 @@ describe "Pet" do end it "should fetch a pet object" do - pet = PetApi.get_pet_by_id(10002) - pet.should be_a(Pet) + pet = SwaggerClient::PetApi.get_pet_by_id(10002) + pet.should be_a(SwaggerClient::Pet) pet.id.should == 10002 pet.name.should == "RUBY UNIT TESTING" pet.tags[0].name.should == "tag test" @@ -46,38 +46,38 @@ describe "Pet" do end it "should find pets by status" do - pets = PetApi.find_pets_by_status(:status => 'available') + pets = SwaggerClient::PetApi.find_pets_by_status(:status => 'available') pets.length.should >= 3 end - + it "should not find a pet with invalid status" do - pets = PetApi.find_pets_by_status(:status => 'invalid-status') + pets = SwaggerClient::PetApi.find_pets_by_status(:status => 'invalid-status') pets.length.should == 0 end it "should find a pet by status" do - pets = PetApi.find_pets_by_status(:status => "available,sold") - pets.map {|pet| - if(pet.status != 'available' && pet.status != 'sold') + pets = SwaggerClient::PetApi.find_pets_by_status(:status => "available,sold") + pets.map {|pet| + if(pet.status != 'available' && pet.status != 'sold') raise "pet status wasn't right" end } end - + it "should update a pet" do - pet = Pet.new({'id' => 10002, 'status' => 'sold'}) - PetApi.add_pet(:body => pet) - - fetched = PetApi.get_pet_by_id(10002) + pet = SwaggerClient::Pet.new({'id' => 10002, 'status' => 'sold'}) + SwaggerClient::PetApi.add_pet(:body => pet) + + fetched = SwaggerClient::PetApi.get_pet_by_id(10002) fetched.id.should == 10002 fetched.status.should == 'sold' end - it "should create a pet" do - pet = Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING") - PetApi.add_pet(:body => pet) + it "should create a pet" do + pet = SwaggerClient::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING") + SwaggerClient::PetApi.add_pet(:body => pet) - pet = PetApi.get_pet_by_id(10002) + pet = SwaggerClient::PetApi.get_pet_by_id(10002) pet.id.should == 10002 pet.name.should == "RUBY UNIT TESTING" end diff --git a/samples/client/petstore/ruby/spec/request_spec.rb b/samples/client/petstore/ruby/spec/request_spec.rb index 61389eddc9c..8856a0cf315 100644 --- a/samples/client/petstore/ruby/spec/request_spec.rb +++ b/samples/client/petstore/ruby/spec/request_spec.rb @@ -1,9 +1,9 @@ require 'spec_helper' -describe Swagger::Request do +describe SwaggerClient::Swagger::Request do before(:each) do - Swagger.configure do |config| + SwaggerClient::Swagger.configure do |config| inject_format = true config.api_key = 'special-key' config.host = 'petstore.swagger.io' @@ -15,7 +15,7 @@ describe Swagger::Request do @default_params = { :params => {:foo => "1", :bar => "2"} } - @request = Swagger::Request.new(@default_http_method, @default_path, @default_params) + @request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, @default_params) end describe "initialization" do @@ -24,7 +24,7 @@ describe Swagger::Request do end it "allows params to be nil" do - @request = Swagger::Request.new(@default_http_method, @default_path, :params => nil) + @request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, :params => nil) @request.query_string.should == "" end @@ -59,7 +59,7 @@ describe Swagger::Request do describe "body" do it "camelCases parameters" do - @request = Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ :body => { :bad_dog => 'bud', :goodDog => "dud" @@ -73,7 +73,7 @@ describe Swagger::Request do describe "path" do it "accounts for a total absence of format in the path string" do - @request = Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({ :format => "xml", :params => { } @@ -82,7 +82,7 @@ describe Swagger::Request do end it "does string substitution (format) on path params" do - @request = Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({ :format => "xml", :params => { } @@ -91,7 +91,7 @@ describe Swagger::Request do end it "leaves path-bound params out of the query string" do - @request = Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({ :params => { :word => "cat", :limit => 20 @@ -101,7 +101,7 @@ describe Swagger::Request do end it "returns a question-mark free (blank) query string if no query params are present" do - @request = Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({ :params => { :word => "cat", } @@ -110,7 +110,7 @@ describe Swagger::Request do end it "removes blank params" do - @request = Swagger::Request.new(:get, "words/fancy", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "words/fancy", @default_params.merge({ :params => { :word => "dog", :limit => "", @@ -121,7 +121,7 @@ describe Swagger::Request do end it "URI encodes the path" do - @request = Swagger::Request.new(:get, "word.{format}/bill gates/definitions", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "word.{format}/bill gates/definitions", @default_params.merge({ :params => { :word => "bill gates" } @@ -130,7 +130,7 @@ describe Swagger::Request do end it "converts numeric params to strings" do - @request = Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ :params => { :limit => 100 } @@ -142,7 +142,7 @@ describe Swagger::Request do end it "camelCases parameters" do - @request = Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ :params => { :bad_dog => 'bud', :goodDog => "dud" @@ -153,7 +153,7 @@ describe Swagger::Request do it "converts boolean values to their string representation" do params = {:stringy => "fish", :truthy => true, :falsey => false} - @request = Swagger::Request.new(:get, 'fakeMethod', :params => params) + @request = SwaggerClient::Swagger::Request.new(:get, 'fakeMethod', :params => params) @request.query_string.should == "?falsey=false&stringy=fish&truthy=true" end @@ -162,12 +162,12 @@ describe Swagger::Request do describe "API key" do it "is inferred from the Swagger base configuration by default" do - Swagger.configure {|c| c.api_key = "xyz" } - Swagger::Request.new(:get, "word/json").headers[:api_key].should == "xyz" + SwaggerClient::Swagger.configure {|c| c.api_key = "xyz" } + SwaggerClient::Swagger::Request.new(:get, "word/json").headers[:api_key].should == "xyz" end it "can be obfuscated for public display" do - @request = Swagger::Request.new(:get, "words/fancy", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "words/fancy", @default_params.merge({ :params => { :word => "dog", :api_key => "123456" @@ -179,21 +179,21 @@ describe Swagger::Request do end it "allows a key in the params to override the configuration-level key, even if it's blank" do - Swagger.configure {|c| c.api_key = "abc" } - @request_with_key = Swagger::Request.new(:get, "word/json", :params => {:api_key => "jkl"}) + SwaggerClient::Swagger.configure {|c| c.api_key = "abc" } + @request_with_key = SwaggerClient::Swagger::Request.new(:get, "word/json", :params => {:api_key => "jkl"}) @request_with_key.headers[:api_key].should be_nil @request_with_key.params[:api_key].should == "jkl" - @request_without_key = Swagger::Request.new(:get, "word/json", :params => {:api_key => nil}) + @request_without_key = SwaggerClient::Swagger::Request.new(:get, "word/json", :params => {:api_key => nil}) @request_without_key.headers[:api_key].should be_nil @request_without_key.params[:api_key].should be_nil end it "allows a key in the headers to override the configuration-level key, even if it's blank" do - Swagger.configure {|c| c.api_key = "hij" } - Swagger::Request.new(:get, "word/json").headers[:api_key].should == "hij" - Swagger::Request.new(:get, "word/json", :headers => {:api_key => "jkl"}).headers[:api_key].should == "jkl" - Swagger::Request.new(:get, "word/json", :headers => {:api_key => nil}).headers[:api_key].should be_nil + SwaggerClient::Swagger.configure {|c| c.api_key = "hij" } + SwaggerClient::Swagger::Request.new(:get, "word/json").headers[:api_key].should == "hij" + SwaggerClient::Swagger::Request.new(:get, "word/json", :headers => {:api_key => "jkl"}).headers[:api_key].should == "jkl" + SwaggerClient::Swagger::Request.new(:get, "word/json", :headers => {:api_key => nil}).headers[:api_key].should be_nil end end diff --git a/samples/client/petstore/ruby/spec/response_spec.rb b/samples/client/petstore/ruby/spec/response_spec.rb index f29a0d2a62f..528b67e1fa7 100644 --- a/samples/client/petstore/ruby/spec/response_spec.rb +++ b/samples/client/petstore/ruby/spec/response_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -describe Swagger::Response do +describe SwaggerClient::Swagger::Response do before do configure_swagger @@ -13,7 +13,7 @@ describe Swagger::Response do @raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002") end - @response = Swagger::Response.new(@raw) + @response = SwaggerClient::Swagger::Response.new(@raw) end describe "initialization" do @@ -43,7 +43,7 @@ describe Swagger::Response do @raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002", :headers => {'Accept'=> "application/xml"}) end - @response = Swagger::Response.new(@raw) + @response = SwaggerClient::Swagger::Response.new(@raw) @response.format.should == 'xml' @response.xml?.should == true end diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index d247ba5cbec..09012db2998 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -1,6 +1,6 @@ require 'rubygems' require 'bundler/setup' -require 'swagger-client' +require 'swagger_client' require 'vcr' require 'typhoeus' require 'json' @@ -37,7 +37,7 @@ end #end def configure_swagger - Swagger.configure do |config| + SwaggerClient::Swagger.configure do |config| config.api_key = 'special-key' config.host = 'petstore.swagger.io' config.base_path = '/v2' @@ -47,29 +47,29 @@ end # always delete and then re-create the pet object with 10002 def prepare_pet # remove the pet - PetApi.delete_pet(10002) + SwaggerClient::PetApi.delete_pet(10002) # recreate the pet - category = Category.new('id' => 20002, 'name' => 'category test') - tag = Tag.new('id' => 30002, 'name' => 'tag test') - pet = Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING", 'photo_urls' => 'photo url', - 'category' => category, 'tags' => [tag], 'status' => 'pending') + category = SwaggerClient::Category.new('id' => 20002, 'name' => 'category test') + tag = SwaggerClient::Tag.new('id' => 30002, 'name' => 'tag test') + pet = SwaggerClient::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING", 'photo_urls' => 'photo url', + 'category' => category, 'tags' => [tag], 'status' => 'pending') - PetApi.add_pet(:'body'=> pet) + SwaggerClient::PetApi.add_pet(:'body'=> pet) end -# always delete and then re-create the store order +# always delete and then re-create the store order def prepare_store - order = Order.new("id" => 10002, + order = SwaggerClient::Order.new("id" => 10002, "petId" => 10002, "quantity" => 789, "shipDate" => "2015-04-06T23:42:01.678Z", "status" => "placed", "complete" => false) - StoreApi.place_order(:body => order) + SwaggerClient::StoreApi.place_order(:body => order) end configure_swagger -# A random string to tack onto stuff to ensure we're not seeing +# A random string to tack onto stuff to ensure we're not seeing # data from a previous test run RAND = ("a".."z").to_a.sample(8).join diff --git a/samples/client/petstore/ruby/spec/store_spec.rb b/samples/client/petstore/ruby/spec/store_spec.rb index a1e2bd3193f..1b37400bc5c 100644 --- a/samples/client/petstore/ruby/spec/store_spec.rb +++ b/samples/client/petstore/ruby/spec/store_spec.rb @@ -7,7 +7,7 @@ describe "Store" do end it "should fetch an order" do - item = StoreApi.get_order_by_id(10002) + item = SwaggerClient::StoreApi.get_order_by_id(10002) item.id.should == 10002 end end diff --git a/samples/client/petstore/ruby/spec/swagger_spec.rb b/samples/client/petstore/ruby/spec/swagger_spec.rb index 4aedc85382c..38b4a850ae9 100644 --- a/samples/client/petstore/ruby/spec/swagger_spec.rb +++ b/samples/client/petstore/ruby/spec/swagger_spec.rb @@ -1,7 +1,7 @@ # require 'spec_helper' require File.dirname(__FILE__) + '/spec_helper' -describe Swagger do +describe SwaggerClient::Swagger do before(:each) do configure_swagger @@ -16,35 +16,35 @@ describe Swagger do context 'host' do it 'removes http from host' do - Swagger.configure {|c| c.host = 'http://example.com' } - Swagger.configuration.host.should == 'example.com' + SwaggerClient::Swagger.configure {|c| c.host = 'http://example.com' } + SwaggerClient::Swagger.configuration.host.should == 'example.com' end it 'removes https from host' do - Swagger.configure {|c| c.host = 'https://wookiee.com' } - Swagger.configuration.host.should == 'wookiee.com' + SwaggerClient::Swagger.configure {|c| c.host = 'https://wookiee.com' } + SwaggerClient::Swagger.configuration.host.should == 'wookiee.com' end it 'removes trailing path from host' do - Swagger.configure {|c| c.host = 'hobo.com/v4' } - Swagger.configuration.host.should == 'hobo.com' + SwaggerClient::Swagger.configure {|c| c.host = 'hobo.com/v4' } + SwaggerClient::Swagger.configuration.host.should == 'hobo.com' end end context 'base_path' do it "prepends a slash to base_path" do - Swagger.configure {|c| c.base_path = 'v4/dog' } - Swagger.configuration.base_path.should == '/v4/dog' + SwaggerClient::Swagger.configure {|c| c.base_path = 'v4/dog' } + SwaggerClient::Swagger.configuration.base_path.should == '/v4/dog' end it "doesn't prepend a slash if one is already there" do - Swagger.configure {|c| c.base_path = '/v4/dog' } - Swagger.configuration.base_path.should == '/v4/dog' + SwaggerClient::Swagger.configure {|c| c.base_path = '/v4/dog' } + SwaggerClient::Swagger.configuration.base_path.should == '/v4/dog' end it "ends up as a blank string if nil" do - Swagger.configure {|c| c.base_path = nil } - Swagger.configuration.base_path.should == '' + SwaggerClient::Swagger.configure {|c| c.base_path = nil } + SwaggerClient::Swagger.configuration.base_path.should == '' end end @@ -53,4 +53,4 @@ describe Swagger do end -end \ No newline at end of file +end diff --git a/samples/client/petstore/ruby/swagger-client.gemspec b/samples/client/petstore/ruby/swagger-client.gemspec deleted file mode 100644 index bbff5f95f6b..00000000000 --- a/samples/client/petstore/ruby/swagger-client.gemspec +++ /dev/null @@ -1,33 +0,0 @@ -# -*- encoding: utf-8 -*- -$:.push File.expand_path("../lib", __FILE__) -require "swagger/version" - -Gem::Specification.new do |s| - s.name = "swagger-client" - s.version = Swagger::VERSION - s.platform = Gem::Platform::RUBY - s.authors = ["Zeke Sikelianos", "Tony Tam"] - s.email = ["zeke@wordnik.com", "tony@wordnik.com"] - s.homepage = "http://developer.wordnik.com" - s.summary = %q{A ruby wrapper for the swagger APIs} - s.description = %q{This gem maps to a swagger API} - - s.rubyforge_project = "swagger-client" - - s.add_dependency 'typhoeus', '>=0.2.1' - s.add_dependency 'addressable', '>=2.2.4' - s.add_dependency 'json', '>=1.4.6' - - s.add_development_dependency 'rspec', '>=2.5.0' - s.add_development_dependency 'vcr', '>=1.5.1' - s.add_development_dependency 'webmock', '>=1.6.2' - s.add_development_dependency 'autotest' - s.add_development_dependency 'autotest-rails-pure' - s.add_development_dependency 'autotest-growl' - s.add_development_dependency 'autotest-fsevent' - - s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? } - s.test_files = `find spec/*`.split("\n") - s.executables = [] - s.require_paths = ["lib"] -end diff --git a/samples/client/petstore/ruby/swagger_client.gemspec b/samples/client/petstore/ruby/swagger_client.gemspec new file mode 100644 index 00000000000..6ec2484e05c --- /dev/null +++ b/samples/client/petstore/ruby/swagger_client.gemspec @@ -0,0 +1,32 @@ +# -*- encoding: utf-8 -*- +$:.push File.expand_path("../lib", __FILE__) +require "swagger_client/swagger/version" + +Gem::Specification.new do |s| + s.name = "swagger_client" + s.version = SwaggerClient::Swagger::VERSION + s.platform = Gem::Platform::RUBY + s.authors = ["Zeke Sikelianos", "Tony Tam"] + s.email = ["zeke@wordnik.com", "tony@wordnik.com"] + s.homepage = "http://developer.wordnik.com" + s.summary = %q{A ruby wrapper for the swagger APIs} + s.description = %q{This gem maps to a swagger API} + s.license = "Apache-2.0" + + s.add_runtime_dependency 'typhoeus', '~> 0.2', '>= 0.2.1' + s.add_runtime_dependency 'addressable', '~> 2.2', '>= 2.2.4' + s.add_runtime_dependency 'json', '~> 1.4', '>= 1.4.6' + + s.add_development_dependency 'rspec', '~> 3.2', '>= 3.2.0' + s.add_development_dependency 'vcr', '~> 2.9', '>= 2.9.3' + s.add_development_dependency 'webmock', '~> 1.6', '>= 1.6.2' + s.add_development_dependency 'autotest', '~> 4.4', '>= 4.4.6' + s.add_development_dependency 'autotest-rails-pure', '~> 4.1', '>= 4.1.2' + s.add_development_dependency 'autotest-growl', '~> 0.2', '>= 0.2.16' + s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.10' + + s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? } + s.test_files = `find spec/*`.split("\n") + s.executables = [] + s.require_paths = ["lib"] +end 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 c17f0a12911..bdf489c08c0 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]) : Option[List[Pet]] = { + def findPetsByStatus (status: List[String] = available) : Option[List[Pet]] = { // create path and map variables val path = "/pet/findByStatus".replaceAll("\\{format\\}","json") diff --git a/samples/client/wordnik/akka-scala/pom.xml b/samples/client/wordnik/akka-scala/pom.xml new file mode 100644 index 00000000000..f865a97c38b --- /dev/null +++ b/samples/client/wordnik/akka-scala/pom.xml @@ -0,0 +1,227 @@ + + 4.0.0 + com.wordnik + swagger-client + jar + swagger-client + 1.0.0 + + 2.2.0 + + + + + maven-mongodb-plugin-repo + maven mongodb plugin repository + http://maven-mongodb-plugin.googlecode.com/svn/maven/repo + default + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + + 1.6 + 1.6 + + + + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin-version} + + + scala-compile-first + process-resources + + add-source + compile + + + + scala-test-compile + process-test-resources + + testCompile + + + + + + -feature + + + -Xms128m + -Xmx1500m + + + + + + + + + org.scala-tools + maven-scala-plugin + + ${scala-version} + + + + + + + org.scala-lang + scala-library + ${scala-version} + + + com.wordnik + swagger-core + ${swagger-core-version} + + + org.scalatest + scalatest_2.10 + ${scala-test-version} + test + + + junit + junit + ${junit-version} + test + + + joda-time + joda-time + ${joda-time-version} + + + org.joda + joda-convert + ${joda-version} + + + com.typesafe + config + 1.2.1 + + + com.typesafe.akka + akka-actor_2.10 + ${akka-version} + + + io.spray + spray-client + ${spray-version} + + + org.json4s + json4s-jackson_2.10 + ${json4s-jackson-version} + + + + 2.10.4 + 3.2.11 + 3.2.11 + 1.3.1 + 2.3.9 + 1.2 + 2.2 + 1.5.0-M1 + 1.0.0 + + 4.8.1 + 3.1.5 + 2.1.3 + + diff --git a/samples/client/wordnik/akka-scala/src/main/resources/reference.conf b/samples/client/wordnik/akka-scala/src/main/resources/reference.conf new file mode 100644 index 00000000000..f993f765edd --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/resources/reference.conf @@ -0,0 +1,24 @@ +io.swagger.client { + + apiRequest { + + compression { + enabled: false + size-threshold: 0 + } + + trust-certificates: true + + connection-timeout: 5000ms + + default-headers { + "userAgent": "swagger-client_1.0.0" + } + + // let you define custom http status code, as in : + // { code: 601, reason: "some custom http status code", success: false } + custom-codes : [] + } +} + +spray.can.host-connector.max-redirects = 10 \ No newline at end of file diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/AccountApi.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/AccountApi.scala new file mode 100644 index 00000000000..8168c1c0f4f --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/AccountApi.scala @@ -0,0 +1,109 @@ +package io.swagger.client.api + +import io.swagger.client.model.ApiTokenStatus +import io.swagger.client.model.AuthenticationToken +import io.swagger.client.model.User +import io.swagger.client.model.WordList +import io.swagger.client.core._ +import io.swagger.client.core.CollectionFormats._ +import io.swagger.client.core.ApiKeyLocations._ + +object AccountApi { + + /** + * + * + * Expected answers: + * code 200 : ApiTokenStatus (Usage statistics for the supplied API key) + * code 400 : (No token supplied.) + * code 404 : (No API account with supplied token.) + * + * @param apiKey Wordnik authentication token + */ + def getApiTokenStatus(apiKey: Option[String] = None): ApiRequest[ApiTokenStatus] = + ApiRequest[ApiTokenStatus](ApiMethods.GET, "https://api.wordnik.com/v4", "/account.json/apiTokenStatus", "application/json") + .withHeaderParam("api_key", apiKey) + .withSuccessResponse[ApiTokenStatus](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : AuthenticationToken (A valid authentication token) + * code 403 : (Account not available.) + * code 404 : (User not found.) + * + * @param username A confirmed Wordnik username + * @param password The user's password + */ + def authenticate(username: String, password: String): ApiRequest[AuthenticationToken] = + ApiRequest[AuthenticationToken](ApiMethods.GET, "https://api.wordnik.com/v4", "/account.json/authenticate/{username}", "application/json") + .withQueryParam("password", password) + .withPathParam("username", username) + .withSuccessResponse[AuthenticationToken](200) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : AuthenticationToken (A valid authentication token) + * code 403 : (Account not available.) + * code 404 : (User not found.) + * + * @param username A confirmed Wordnik username + * @param body The user's password + */ + def authenticatePost(username: String, body: String): ApiRequest[AuthenticationToken] = + ApiRequest[AuthenticationToken](ApiMethods.POST, "https://api.wordnik.com/v4", "/account.json/authenticate/{username}", "application/json") + .withBody(body) + .withPathParam("username", username) + .withSuccessResponse[AuthenticationToken](200) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + /** + * Requires a valid auth_token to be set. + * + * Expected answers: + * code 200 : User (The logged-in user) + * code 403 : (Not logged in.) + * code 404 : (User not found.) + * + * @param authToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + */ + def getLoggedInUser(authToken: String): ApiRequest[User] = + ApiRequest[User](ApiMethods.GET, "https://api.wordnik.com/v4", "/account.json/user", "application/json") + .withHeaderParam("auth_token", authToken) + .withSuccessResponse[User](200) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : Seq[WordList] (success) + * code 403 : (Not authenticated.) + * code 404 : (User account not found.) + * + * @param authToken auth_token of logged-in user + * @param skip Results to skip + * @param limit Maximum number of results to return + */ + def getWordListsForLoggedInUser(authToken: String, skip: Option[Int] = None, limit: Option[Int] = None): ApiRequest[Seq[WordList]] = + ApiRequest[Seq[WordList]](ApiMethods.GET, "https://api.wordnik.com/v4", "/account.json/wordLists", "application/json") + .withQueryParam("skip", skip) + .withQueryParam("limit", limit) + .withHeaderParam("auth_token", authToken) + .withSuccessResponse[Seq[WordList]](200) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + + +} + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/EnumsSerializers.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/EnumsSerializers.scala new file mode 100644 index 00000000000..c95a49ad0b2 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/EnumsSerializers.scala @@ -0,0 +1,41 @@ +package io.swagger.client.api + +import io.swagger.client.model._ +import org.json4s._ +import scala.reflect.ClassTag + +object EnumsSerializers { + + def all = Seq[Serializer[_]]() + + + + private class EnumNameSerializer[E <: Enumeration: ClassTag](enum: E) + extends Serializer[E#Value] { + import JsonDSL._ + + val EnumerationClass = classOf[E#Value] + + def deserialize(implicit format: Formats): + PartialFunction[(TypeInfo, JValue), E#Value] = { + case (t @ TypeInfo(EnumerationClass, _), json) if isValid(json) => { + json match { + case JString(value) => + enum.withName(value) + case value => + throw new MappingException(s"Can't convert $value to $EnumerationClass") + } + } + } + + private[this] def isValid(json: JValue) = json match { + case JString(value) if enum.values.exists(_.toString == value) => true + case _ => false + } + + def serialize(implicit format: Formats): PartialFunction[Any, JValue] = { + case i: E#Value => i.toString + } + } + +} \ No newline at end of file diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordApi.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordApi.scala new file mode 100644 index 00000000000..3c85b1a857f --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordApi.scala @@ -0,0 +1,253 @@ +package io.swagger.client.api + +import io.swagger.client.model.WordObject +import io.swagger.client.model.AudioFile +import io.swagger.client.model.Definition +import io.swagger.client.model.FrequencySummary +import io.swagger.client.model.Bigram +import io.swagger.client.model.Example +import io.swagger.client.core._ +import io.swagger.client.core.CollectionFormats._ +import io.swagger.client.core.ApiKeyLocations._ + +object WordApi { + + /** + * + * + * Expected answers: + * code 200 : WordObject (success) + * code 400 : (Invalid word supplied.) + * + * @param word String value of WordObject to return + * @param useCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param includeSuggestions Return suggestions (for correct spelling, case variants, etc.) + */ + def getWord(word: String, useCanonical: Option[String] = None, includeSuggestions: Option[String] = None): ApiRequest[WordObject] = + ApiRequest[WordObject](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}", "application/json") + .withQueryParam("useCanonical", useCanonical) + .withQueryParam("includeSuggestions", includeSuggestions) + .withPathParam("word", word) + .withSuccessResponse[WordObject](200) + .withErrorResponse[Unit](400) + + /** + * The metadata includes a time-expiring fileUrl which allows reading the audio file directly from the API. Currently only audio pronunciations from the American Heritage Dictionary in mp3 format are supported. + * + * Expected answers: + * code 200 : Seq[AudioFile] (success) + * code 400 : (Invalid word supplied.) + * + * @param word Word to get audio for. + * @param useCanonical Use the canonical form of the word + * @param limit Maximum number of results to return + */ + def getAudio(word: String, useCanonical: Option[String] = None, limit: Option[Int] = None): ApiRequest[Seq[AudioFile]] = + ApiRequest[Seq[AudioFile]](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/audio", "application/json") + .withQueryParam("useCanonical", useCanonical) + .withQueryParam("limit", limit) + .withPathParam("word", word) + .withSuccessResponse[Seq[AudioFile]](200) + .withErrorResponse[Unit](400) + + /** + * + * + * Expected answers: + * code 200 : Seq[Definition] (success) + * code 400 : (Invalid word supplied.) + * code 404 : (No definitions found.) + * + * @param word Word to return definitions for + * @param limit Maximum number of results to return + * @param partOfSpeech CSV list of part-of-speech types + * @param includeRelated Return related words with definitions + * @param sourceDictionaries Source dictionary to return definitions from. If 'all' is received, results are returned from all sources. If multiple values are received (e.g. 'century,wiktionary'), results are returned from the first specified dictionary that has definitions. If left blank, results are returned from the first dictionary that has definitions. By default, dictionaries are searched in this order: ahd, wiktionary, webster, century, wordnet + * @param useCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param includeTags Return a closed set of XML tags in response + */ + def getDefinitions(word: String, limit: Option[Int] = None, partOfSpeech: Option[String] = None, includeRelated: Option[String] = None, sourceDictionaries: Seq[String], useCanonical: Option[String] = None, includeTags: Option[String] = None): ApiRequest[Seq[Definition]] = + ApiRequest[Seq[Definition]](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/definitions", "application/json") + .withQueryParam("limit", limit) + .withQueryParam("partOfSpeech", partOfSpeech) + .withQueryParam("includeRelated", includeRelated) + .withQueryParam("sourceDictionaries", ArrayValues(sourceDictionaries, CSV)) + .withQueryParam("useCanonical", useCanonical) + .withQueryParam("includeTags", includeTags) + .withPathParam("word", word) + .withSuccessResponse[Seq[Definition]](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : Seq[String] (success) + * code 400 : (Invalid word supplied.) + * code 404 : (No definitions found.) + * + * @param word Word to return + * @param useCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + */ + def getEtymologies(word: String, useCanonical: Option[String] = None): ApiRequest[Seq[String]] = + ApiRequest[Seq[String]](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/etymologies", "application/json") + .withQueryParam("useCanonical", useCanonical) + .withPathParam("word", word) + .withSuccessResponse[Seq[String]](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : (success) + * code 400 : (Invalid word supplied.) + * + * @param word Word to return examples for + * @param includeDuplicates Show duplicate examples from different sources + * @param useCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param skip Results to skip + * @param limit Maximum number of results to return + */ + def getExamples(word: String, includeDuplicates: Option[String] = None, useCanonical: Option[String] = None, skip: Option[Int] = None, limit: Option[Int] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/examples", "application/json") + .withQueryParam("includeDuplicates", includeDuplicates) + .withQueryParam("useCanonical", useCanonical) + .withQueryParam("skip", skip) + .withQueryParam("limit", limit) + .withPathParam("word", word) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](400) + + /** + * + * + * Expected answers: + * code 200 : FrequencySummary (success) + * code 400 : (Invalid word supplied.) + * code 404 : (No results.) + * + * @param word Word to return + * @param useCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param startYear Starting Year + * @param endYear Ending Year + */ + def getWordFrequency(word: String, useCanonical: Option[String] = None, startYear: Option[Int] = None, endYear: Option[Int] = None): ApiRequest[FrequencySummary] = + ApiRequest[FrequencySummary](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/frequency", "application/json") + .withQueryParam("useCanonical", useCanonical) + .withQueryParam("startYear", startYear) + .withQueryParam("endYear", endYear) + .withPathParam("word", word) + .withSuccessResponse[FrequencySummary](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : (success) + * code 400 : (Invalid word supplied.) + * + * @param word Word to get syllables for + * @param useCanonical If true will try to return a correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param sourceDictionary Get from a single dictionary. Valid options: ahd, century, wiktionary, webster, and wordnet. + * @param limit Maximum number of results to return + */ + def getHyphenation(word: String, useCanonical: Option[String] = None, sourceDictionary: Option[String] = None, limit: Option[Int] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/hyphenation", "application/json") + .withQueryParam("useCanonical", useCanonical) + .withQueryParam("sourceDictionary", sourceDictionary) + .withQueryParam("limit", limit) + .withPathParam("word", word) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](400) + + /** + * + * + * Expected answers: + * code 200 : Seq[Bigram] (success) + * code 400 : (Invalid word supplied.) + * + * @param word Word to fetch phrases for + * @param limit Maximum number of results to return + * @param wlmi Minimum WLMI for the phrase + * @param useCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + */ + def getPhrases(word: String, limit: Option[Int] = None, wlmi: Option[Int] = None, useCanonical: Option[String] = None): ApiRequest[Seq[Bigram]] = + ApiRequest[Seq[Bigram]](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/phrases", "application/json") + .withQueryParam("limit", limit) + .withQueryParam("wlmi", wlmi) + .withQueryParam("useCanonical", useCanonical) + .withPathParam("word", word) + .withSuccessResponse[Seq[Bigram]](200) + .withErrorResponse[Unit](400) + + /** + * + * + * Expected answers: + * code 200 : (success) + * code 400 : (Invalid word supplied.) + * + * @param word Word to get pronunciations for + * @param useCanonical If true will try to return a correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param sourceDictionary Get from a single dictionary + * @param typeFormat Text pronunciation type + * @param limit Maximum number of results to return + */ + def getTextPronunciations(word: String, useCanonical: Option[String] = None, sourceDictionary: Option[String] = None, typeFormat: Option[String] = None, limit: Option[Int] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/pronunciations", "application/json") + .withQueryParam("useCanonical", useCanonical) + .withQueryParam("sourceDictionary", sourceDictionary) + .withQueryParam("typeFormat", typeFormat) + .withQueryParam("limit", limit) + .withPathParam("word", word) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](400) + + /** + * + * + * Expected answers: + * code 200 : (success) + * code 400 : (Invalid word supplied.) + * + * @param word Word to fetch relationships for + * @param useCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param relationshipTypes Limits the total results per type of relationship type + * @param limitPerRelationshipType Restrict to the supplied relationship types + */ + def getRelatedWords(word: String, useCanonical: Option[String] = None, relationshipTypes: Option[String] = None, limitPerRelationshipType: Option[Int] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/relatedWords", "application/json") + .withQueryParam("useCanonical", useCanonical) + .withQueryParam("relationshipTypes", relationshipTypes) + .withQueryParam("limitPerRelationshipType", limitPerRelationshipType) + .withPathParam("word", word) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](400) + + /** + * + * + * Expected answers: + * code 200 : Example (success) + * code 400 : (Invalid word supplied.) + * + * @param word Word to fetch examples for + * @param useCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + */ + def getTopExample(word: String, useCanonical: Option[String] = None): ApiRequest[Example] = + ApiRequest[Example](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/topExample", "application/json") + .withQueryParam("useCanonical", useCanonical) + .withPathParam("word", word) + .withSuccessResponse[Example](200) + .withErrorResponse[Unit](400) + + + +} + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListApi.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListApi.scala new file mode 100644 index 00000000000..6ff76587e1a --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListApi.scala @@ -0,0 +1,154 @@ +package io.swagger.client.api + +import io.swagger.client.model.WordList +import io.swagger.client.model.StringValue +import io.swagger.client.core._ +import io.swagger.client.core.CollectionFormats._ +import io.swagger.client.core.ApiKeyLocations._ + +object WordListApi { + + /** + * + * + * Expected answers: + * code 200 : WordList (success) + * code 400 : (Invalid ID supplied) + * code 403 : (Not Authorized to access WordList) + * code 404 : (WordList not found) + * + * @param permalink permalink of WordList to fetch + * @param authToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + */ + def getWordListByPermalink(permalink: String, authToken: String): ApiRequest[WordList] = + ApiRequest[WordList](ApiMethods.GET, "https://api.wordnik.com/v4", "/wordList.json/{permalink}", "application/json") + .withPathParam("permalink", permalink) + .withHeaderParam("auth_token", authToken) + .withSuccessResponse[WordList](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : (success) + * code 400 : (Invalid ID supplied) + * code 403 : (Not Authorized to update WordList) + * code 404 : (WordList not found) + * + * @param permalink permalink of WordList to update + * @param body Updated WordList + * @param authToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + */ + def updateWordList(permalink: String, body: Option[WordList] = None, authToken: String): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.PUT, "https://api.wordnik.com/v4", "/wordList.json/{permalink}", "application/json") + .withBody(body) + .withPathParam("permalink", permalink) + .withHeaderParam("auth_token", authToken) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : (success) + * code 400 : (Invalid ID supplied) + * code 403 : (Not Authorized to delete WordList) + * code 404 : (WordList not found) + * + * @param permalink ID of WordList to delete + * @param authToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + */ + def deleteWordList(permalink: String, authToken: String): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.DELETE, "https://api.wordnik.com/v4", "/wordList.json/{permalink}", "application/json") + .withPathParam("permalink", permalink) + .withHeaderParam("auth_token", authToken) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : (success) + * code 400 : (Invalid permalink supplied) + * code 403 : (Not Authorized to modify WordList) + * code 404 : (WordList not found) + * + * @param permalink permalink of WordList to use + * @param body Words to remove from WordList + * @param authToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + */ + def deleteWordsFromWordList(permalink: String, body: Seq[StringValue], authToken: String): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.POST, "https://api.wordnik.com/v4", "/wordList.json/{permalink}/deleteWords", "application/json") + .withBody(body) + .withPathParam("permalink", permalink) + .withHeaderParam("auth_token", authToken) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : (success) + * code 400 : (Invalid ID supplied) + * code 403 : (Not Authorized to access WordList) + * code 404 : (WordList not found) + * + * @param permalink ID of WordList to use + * @param sortBy Field to sort by + * @param sortOrder Direction to sort + * @param skip Results to skip + * @param limit Maximum number of results to return + * @param authToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + */ + def getWordListWords(permalink: String, sortBy: Option[String] = None, sortOrder: Option[String] = None, skip: Option[Int] = None, limit: Option[Int] = None, authToken: String): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.GET, "https://api.wordnik.com/v4", "/wordList.json/{permalink}/words", "application/json") + .withQueryParam("sortBy", sortBy) + .withQueryParam("sortOrder", sortOrder) + .withQueryParam("skip", skip) + .withQueryParam("limit", limit) + .withPathParam("permalink", permalink) + .withHeaderParam("auth_token", authToken) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : (success) + * code 400 : (Invalid permalink supplied) + * code 403 : (Not Authorized to access WordList) + * code 404 : (WordList not found) + * + * @param permalink permalink of WordList to user + * @param body Array of words to add to WordList + * @param authToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + */ + def addWordsToWordList(permalink: String, body: Seq[StringValue], authToken: String): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.POST, "https://api.wordnik.com/v4", "/wordList.json/{permalink}/words", "application/json") + .withBody(body) + .withPathParam("permalink", permalink) + .withHeaderParam("auth_token", authToken) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + + +} + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListsApi.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListsApi.scala new file mode 100644 index 00000000000..cad9a37ba87 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListsApi.scala @@ -0,0 +1,34 @@ +package io.swagger.client.api + +import io.swagger.client.model.WordList +import io.swagger.client.core._ +import io.swagger.client.core.CollectionFormats._ +import io.swagger.client.core.ApiKeyLocations._ + +object WordListsApi { + + /** + * + * + * Expected answers: + * code 200 : WordList (success) + * code 400 : (Invalid WordList supplied or mandatory fields are missing) + * code 403 : (Not authenticated) + * code 404 : (WordList owner not found) + * + * @param body WordList to create + * @param authToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + */ + def createWordList(body: Option[WordList] = None, authToken: String): ApiRequest[WordList] = + ApiRequest[WordList](ApiMethods.POST, "https://api.wordnik.com/v4", "/wordLists.json", "application/json") + .withBody(body) + .withHeaderParam("auth_token", authToken) + .withSuccessResponse[WordList](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + + +} + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordsApi.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordsApi.scala new file mode 100644 index 00000000000..b3b33679252 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordsApi.scala @@ -0,0 +1,181 @@ +package io.swagger.client.api + +import io.swagger.client.model.WordObject +import io.swagger.client.model.DefinitionSearchResults +import io.swagger.client.model.WordSearchResults +import io.swagger.client.model.WordOfTheDay +import io.swagger.client.core._ +import io.swagger.client.core.CollectionFormats._ +import io.swagger.client.core.ApiKeyLocations._ + +object WordsApi { + + /** + * + * + * Expected answers: + * code 200 : WordObject (success) + * code 404 : (No word found.) + * + * @param hasDictionaryDef Only return words with dictionary definitions + * @param includePartOfSpeech CSV part-of-speech values to include + * @param excludePartOfSpeech CSV part-of-speech values to exclude + * @param minCorpusCount Minimum corpus frequency for terms + * @param maxCorpusCount Maximum corpus frequency for terms + * @param minDictionaryCount Minimum dictionary count + * @param maxDictionaryCount Maximum dictionary count + * @param minLength Minimum word length + * @param maxLength Maximum word length + */ + def getRandomWord(hasDictionaryDef: Option[String] = None, includePartOfSpeech: Option[String] = None, excludePartOfSpeech: Option[String] = None, minCorpusCount: Option[Int] = None, maxCorpusCount: Option[Int] = None, minDictionaryCount: Option[Int] = None, maxDictionaryCount: Option[Int] = None, minLength: Option[Int] = None, maxLength: Option[Int] = None): ApiRequest[WordObject] = + ApiRequest[WordObject](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/randomWord", "application/json") + .withQueryParam("hasDictionaryDef", hasDictionaryDef) + .withQueryParam("includePartOfSpeech", includePartOfSpeech) + .withQueryParam("excludePartOfSpeech", excludePartOfSpeech) + .withQueryParam("minCorpusCount", minCorpusCount) + .withQueryParam("maxCorpusCount", maxCorpusCount) + .withQueryParam("minDictionaryCount", minDictionaryCount) + .withQueryParam("maxDictionaryCount", maxDictionaryCount) + .withQueryParam("minLength", minLength) + .withQueryParam("maxLength", maxLength) + .withSuccessResponse[WordObject](200) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : (success) + * code 400 : (Invalid term supplied.) + * code 404 : (No results.) + * + * @param hasDictionaryDef Only return words with dictionary definitions + * @param includePartOfSpeech CSV part-of-speech values to include + * @param excludePartOfSpeech CSV part-of-speech values to exclude + * @param minCorpusCount Minimum corpus frequency for terms + * @param maxCorpusCount Maximum corpus frequency for terms + * @param minDictionaryCount Minimum dictionary count + * @param maxDictionaryCount Maximum dictionary count + * @param minLength Minimum word length + * @param maxLength Maximum word length + * @param sortBy Attribute to sort by + * @param sortOrder Sort direction + * @param limit Maximum number of results to return + */ + def getRandomWords(hasDictionaryDef: Option[String] = None, includePartOfSpeech: Option[String] = None, excludePartOfSpeech: Option[String] = None, minCorpusCount: Option[Int] = None, maxCorpusCount: Option[Int] = None, minDictionaryCount: Option[Int] = None, maxDictionaryCount: Option[Int] = None, minLength: Option[Int] = None, maxLength: Option[Int] = None, sortBy: Option[String] = None, sortOrder: Option[String] = None, limit: Option[Int] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/randomWords", "application/json") + .withQueryParam("hasDictionaryDef", hasDictionaryDef) + .withQueryParam("includePartOfSpeech", includePartOfSpeech) + .withQueryParam("excludePartOfSpeech", excludePartOfSpeech) + .withQueryParam("minCorpusCount", minCorpusCount) + .withQueryParam("maxCorpusCount", maxCorpusCount) + .withQueryParam("minDictionaryCount", minDictionaryCount) + .withQueryParam("maxDictionaryCount", maxDictionaryCount) + .withQueryParam("minLength", minLength) + .withQueryParam("maxLength", maxLength) + .withQueryParam("sortBy", sortBy) + .withQueryParam("sortOrder", sortOrder) + .withQueryParam("limit", limit) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : DefinitionSearchResults (success) + * code 400 : (Invalid term supplied.) + * + * @param query Search term + * @param findSenseForWord Restricts words and finds closest sense + * @param includeSourceDictionaries Only include these comma-delimited source dictionaries + * @param excludeSourceDictionaries Exclude these comma-delimited source dictionaries + * @param includePartOfSpeech Only include these comma-delimited parts of speech + * @param excludePartOfSpeech Exclude these comma-delimited parts of speech + * @param minCorpusCount Minimum corpus frequency for terms + * @param maxCorpusCount Maximum corpus frequency for terms + * @param minLength Minimum word length + * @param maxLength Maximum word length + * @param expandTerms Expand terms + * @param includeTags Return a closed set of XML tags in response + * @param sortBy Attribute to sort by + * @param sortOrder Sort direction + * @param skip Results to skip + * @param limit Maximum number of results to return + */ + def reverseDictionary(query: String, findSenseForWord: Option[String] = None, includeSourceDictionaries: Option[String] = None, excludeSourceDictionaries: Option[String] = None, includePartOfSpeech: Option[String] = None, excludePartOfSpeech: Option[String] = None, minCorpusCount: Option[Int] = None, maxCorpusCount: Option[Int] = None, minLength: Option[Int] = None, maxLength: Option[Int] = None, expandTerms: Option[String] = None, includeTags: Option[String] = None, sortBy: Option[String] = None, sortOrder: Option[String] = None, skip: Option[String] = None, limit: Option[Int] = None): ApiRequest[DefinitionSearchResults] = + ApiRequest[DefinitionSearchResults](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/reverseDictionary", "application/json") + .withQueryParam("query", query) + .withQueryParam("findSenseForWord", findSenseForWord) + .withQueryParam("includeSourceDictionaries", includeSourceDictionaries) + .withQueryParam("excludeSourceDictionaries", excludeSourceDictionaries) + .withQueryParam("includePartOfSpeech", includePartOfSpeech) + .withQueryParam("excludePartOfSpeech", excludePartOfSpeech) + .withQueryParam("minCorpusCount", minCorpusCount) + .withQueryParam("maxCorpusCount", maxCorpusCount) + .withQueryParam("minLength", minLength) + .withQueryParam("maxLength", maxLength) + .withQueryParam("expandTerms", expandTerms) + .withQueryParam("includeTags", includeTags) + .withQueryParam("sortBy", sortBy) + .withQueryParam("sortOrder", sortOrder) + .withQueryParam("skip", skip) + .withQueryParam("limit", limit) + .withSuccessResponse[DefinitionSearchResults](200) + .withErrorResponse[Unit](400) + + /** + * + * + * Expected answers: + * code 200 : WordSearchResults (success) + * code 400 : (Invalid query supplied.) + * + * @param query Search query + * @param caseSensitive Search case sensitive + * @param includePartOfSpeech Only include these comma-delimited parts of speech + * @param excludePartOfSpeech Exclude these comma-delimited parts of speech + * @param minCorpusCount Minimum corpus frequency for terms + * @param maxCorpusCount Maximum corpus frequency for terms + * @param minDictionaryCount Minimum number of dictionary entries for words returned + * @param maxDictionaryCount Maximum dictionary definition count + * @param minLength Minimum word length + * @param maxLength Maximum word length + * @param skip Results to skip + * @param limit Maximum number of results to return + */ + def searchWords(query: String, caseSensitive: Option[String] = None, includePartOfSpeech: Option[String] = None, excludePartOfSpeech: Option[String] = None, minCorpusCount: Option[Int] = None, maxCorpusCount: Option[Int] = None, minDictionaryCount: Option[Int] = None, maxDictionaryCount: Option[Int] = None, minLength: Option[Int] = None, maxLength: Option[Int] = None, skip: Option[Int] = None, limit: Option[Int] = None): ApiRequest[WordSearchResults] = + ApiRequest[WordSearchResults](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/search/{query}", "application/json") + .withQueryParam("caseSensitive", caseSensitive) + .withQueryParam("includePartOfSpeech", includePartOfSpeech) + .withQueryParam("excludePartOfSpeech", excludePartOfSpeech) + .withQueryParam("minCorpusCount", minCorpusCount) + .withQueryParam("maxCorpusCount", maxCorpusCount) + .withQueryParam("minDictionaryCount", minDictionaryCount) + .withQueryParam("maxDictionaryCount", maxDictionaryCount) + .withQueryParam("minLength", minLength) + .withQueryParam("maxLength", maxLength) + .withQueryParam("skip", skip) + .withQueryParam("limit", limit) + .withPathParam("query", query) + .withSuccessResponse[WordSearchResults](200) + .withErrorResponse[Unit](400) + + /** + * + * + * Expected answers: + * code 0 : WordOfTheDay (success) + * + * @param date Fetches by date in yyyy-MM-dd + */ + def getWordOfTheDay(date: Option[String] = None): ApiRequest[WordOfTheDay] = + ApiRequest[WordOfTheDay](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/wordOfTheDay", "application/json") + .withQueryParam("date", date) + .withDefaultSuccessResponse[WordOfTheDay] + + + +} + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala new file mode 100644 index 00000000000..3b11d866017 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala @@ -0,0 +1,323 @@ +package io.swagger.client.core + +import java.io.File +import java.security.cert.X509Certificate +import javax.net.ssl._ + +import akka.actor.ActorSystem +import akka.io.IO +import akka.pattern.ask +import akka.util.Timeout +import org.joda.time.DateTime +import org.joda.time.format.ISODateTimeFormat +import org.json4s.JsonAST.JString +import org.json4s._ +import org.json4s.jackson.JsonMethods._ +import org.json4s.jackson.Serialization +import spray.can.Http +import spray.can.Http.HostConnectorSetup +import spray.client.pipelining +import spray.client.pipelining._ +import spray.http.HttpEncodings._ +import spray.http.HttpHeaders.{RawHeader, `Accept-Encoding`} +import spray.http.Uri.Query +import spray.http._ +import spray.http.parser.HttpParser +import spray.httpx.encoding.{Deflate, Encoder, Gzip} +import spray.httpx.unmarshalling._ +import spray.io.ClientSSLEngineProvider + +import scala.concurrent.{ExecutionContext, Future} +import scala.reflect.ClassTag +import scala.util.control.NonFatal + +object ApiInvoker { + + def apply()(implicit system: ActorSystem): ApiInvoker = + apply(DefaultFormats + DateTimeSerializer) + def apply(serializers: Traversable[Serializer[_]])(implicit system: ActorSystem): ApiInvoker = + apply(DefaultFormats + DateTimeSerializer ++ serializers) + def apply(formats: Formats)(implicit system: ActorSystem): ApiInvoker = new ApiInvoker(formats) + + case class CustomStatusCode(value: Int, reason: String = "Application-defined status code", isSuccess: Boolean = true) + + def addCustomStatusCode(code: CustomStatusCode): Unit = addCustomStatusCode(code.value, code.reason, code.isSuccess) + + def addCustomStatusCode(code: Int, reason: String = "Application defined code", isSuccess: Boolean = true) = { + StatusCodes.getForKey(code) foreach { c => + StatusCodes.registerCustom(code, reason, reason, isSuccess, allowsEntity = true) + } + } + + /** + * Allows request execution without calling apiInvoker.execute(request) + * request.response can be used to get a future of the ApiResponse generated. + * request.result can be used to get a future of the expected ApiResponse content. If content doesn't match, a + * Future will failed with a ClassCastException + * @param request the apiRequest to be executed + */ + implicit class ApiRequestImprovements[T](request: ApiRequest[T]) { + + def response(invoker: ApiInvoker)(implicit ec: ExecutionContext, system: ActorSystem): Future[ApiResponse[T]] = + response(ec, system, invoker) + + def response(implicit ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[ApiResponse[T]] = + invoker.execute(request) + + def result[U <: T](implicit c: ClassTag[U], ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[U] = + invoker.execute(request).map(_.content).mapTo[U] + + } + + /** + * Allows transformation from ApiMethod to spray HttpMethods + * @param method the ApiMethod to be converted + */ + implicit class ApiMethodExtensions(val method: ApiMethod) { + def toSprayMethod: HttpMethod = HttpMethods.getForKey(method.value).getOrElse(HttpMethods.GET) + } + + case object DateTimeSerializer extends CustomSerializer[DateTime](format => ( { + case JString(s) => + ISODateTimeFormat.dateTimeParser().parseDateTime(s) + }, { + case d: DateTime => + JString(ISODateTimeFormat.dateTimeParser().print(d)) + })) +} + +class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends UntrustedSslContext with CustomContentTypes { + + import io.swagger.client.core.ApiInvoker._ + import io.swagger.client.core.ParametersMap._ + + implicit val ec = system.dispatcher + implicit val jsonFormats = formats + + def settings = ApiSettings(system) + + import spray.http.MessagePredicate._ + + val CompressionFilter = MessagePredicate({ _ => settings.compressionEnabled}) && + Encoder.DefaultFilter && + minEntitySize(settings.compressionSizeThreshold) + + settings.customCodes.foreach(addCustomStatusCode) + + private def addAuthentication(credentialsSeq: Seq[Credentials]): pipelining.RequestTransformer = + request => + credentialsSeq.foldLeft(request) { + case (req, BasicCredentials(login, password)) => + req ~> addCredentials(BasicHttpCredentials(login, password)) + case (req, ApiKeyCredentials(keyValue, keyName, ApiKeyLocations.HEADER)) => + req ~> addHeader(RawHeader(keyName, keyValue.value)) + case (req, _) => req + } + + private def addHeaders(headers: Map[String, Any]): pipelining.RequestTransformer = { request => + + val rawHeaders = for { + (name, value) <- headers.asFormattedParams + header = RawHeader(name, String.valueOf(value)) + } yield header + + request.withHeaders(rawHeaders.toList) + } + + private def bodyPart(name: String, value: Any): BodyPart = { + value match { + case f: File => + BodyPart(f, name) + case v: String => + BodyPart(HttpEntity(String.valueOf(v))) + case NumericValue(v) => + BodyPart(HttpEntity(String.valueOf(v))) + case m: ApiModel => + BodyPart(HttpEntity(Serialization.write(m))) + } + } + + private def formDataContent(request: ApiRequest[_]) = { + val params = request.formParams.asFormattedParams + if (params.isEmpty) + None + else + Some( + normalizedContentType(request.contentType).mediaType match { + case MediaTypes.`multipart/form-data` => + MultipartFormData(params.map { case (name, value) => (name, bodyPart(name, value))}) + case MediaTypes.`application/x-www-form-urlencoded` => + FormData(params.mapValues(String.valueOf)) + case m: MediaType => // Default : application/x-www-form-urlencoded. + FormData(params.mapValues(String.valueOf)) + } + ) + } + + private def bodyContent(request: ApiRequest[_]): Option[Any] = { + request.bodyParam.map(Extraction.decompose).map(compact) + } + + private def createRequest(uri: Uri, request: ApiRequest[_]): HttpRequest = { + + val builder = new RequestBuilder(request.method.toSprayMethod) + val httpRequest = request.method.toSprayMethod match { + case HttpMethods.GET | HttpMethods.DELETE => builder.apply(uri) + case HttpMethods.POST | HttpMethods.PUT => + formDataContent(request) orElse bodyContent(request) match { + case Some(c: FormData) => + builder.apply(uri, c) + case Some(c: MultipartFormData) => + builder.apply(uri, c) + case Some(c: String) => + builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), c)) + case _ => + builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), " ")) + } + case _ => builder.apply(uri) + } + + httpRequest ~> + addHeaders(request.headerParams) ~> + addAuthentication(request.credentials) ~> + encode(Gzip(CompressionFilter)) + } + + def makeQuery(r: ApiRequest[_]): Query = { + r.credentials.foldLeft(r.queryParams) { + case (params, ApiKeyCredentials(key, keyName, ApiKeyLocations.QUERY)) => + params + (keyName -> key.value) + case (params, _) => params + }.asFormattedParams + .mapValues(String.valueOf) + .foldRight[Query](Uri.Query.Empty) { + case ((name, value), acc) => acc.+:(name, value) + } + } + + def makeUri(r: ApiRequest[_]): Uri = { + val opPath = r.operationPath.replaceAll("\\{format\\}", "json") + val opPathWithParams = r.pathParams.asFormattedParams + .mapValues(String.valueOf) + .foldLeft(opPath) { + case (path, (name, value)) => path.replaceAll(s"\\{$name\\}", value) + } + val query = makeQuery(r) + + Uri(r.basePath + opPathWithParams).withQuery(query) + } + + def execute[T](r: ApiRequest[T]): Future[ApiResponse[T]] = { + try { + implicit val timeout: Timeout = settings.connectionTimeout + + val uri = makeUri(r) + + val connector = HostConnectorSetup( + uri.authority.host.toString, + uri.effectivePort, + sslEncryption = "https".equals(uri.scheme), + defaultHeaders = settings.defaultHeaders ++ List(`Accept-Encoding`(gzip, deflate))) + + val request = createRequest(uri, r) + + for { + Http.HostConnectorInfo(hostConnector, _) <- IO(Http) ? connector + response <- hostConnector.ask(request).mapTo[HttpResponse] + } yield { + response ~> decode(Deflate) ~> decode(Gzip) ~> unmarshallApiResponse(r) + } + } + catch { + case NonFatal(x) => Future.failed(x) + } + } + + def unmarshallApiResponse[T](request: ApiRequest[T])(response: HttpResponse): ApiResponse[T] = { + request.responseForCode(response.status.intValue) match { + case Some( (manifest: Manifest[T], state: ResponseState) ) => + entityUnmarshaller(manifest)(response.entity) match { + case Right(value) ⇒ + state match { + case ResponseState.Success => + ApiResponse(response.status.intValue, value, response.headers.map(header => (header.name, header.value)).toMap) + case ResponseState.Error => + throw new ApiError(response.status.intValue, "Error response received", + Some(value), + headers = response.headers.map(header => (header.name, header.value)).toMap) + } + + case Left(MalformedContent(error, Some(cause))) ⇒ + throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), cause) + + case Left(MalformedContent(error, None)) ⇒ + throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString)) + + case Left(ContentExpected) ⇒ + throw new ApiError(response.status.intValue, s"Unable to unmarshall empty response to [$manifest]", Some(response.entity.toString)) + } + + case _ => throw new ApiError(response.status.intValue, "Unexpected response code", Some(response.entity.toString)) + } + } + + def entityUnmarshaller[T](implicit mf: Manifest[T]): Unmarshaller[T] = + Unmarshaller[T](MediaTypes.`application/json`) { + case x: HttpEntity.NonEmpty ⇒ + parse(x.asString(defaultCharset = HttpCharsets.`UTF-8`)) + .noNulls + .camelizeKeys + .extract[T] + } + +} + +sealed trait CustomContentTypes { + + def normalizedContentType(original: String): ContentType = + MediaTypes.forExtension(original) map (ContentType(_)) getOrElse parseContentType(original) + + def parseContentType(contentType: String): ContentType = { + val contentTypeAsRawHeader = HttpHeaders.RawHeader("Content-Type", contentType) + val parsedContentTypeHeader = HttpParser.parseHeader(contentTypeAsRawHeader) + (parsedContentTypeHeader: @unchecked) match { + case Right(ct: HttpHeaders.`Content-Type`) => + ct.contentType + case Left(error: ErrorInfo) => + throw new IllegalArgumentException( + s"Error converting '$contentType' to a ContentType header: '${error.summary}'") + } + } +} + +sealed trait UntrustedSslContext { + this: ApiInvoker => + + implicit lazy val trustfulSslContext: SSLContext = { + settings.alwaysTrustCertificates match { + case false => + SSLContext.getDefault + + case true => + class IgnoreX509TrustManager extends X509TrustManager { + def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {} + + def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {} + + def getAcceptedIssuers = null + } + + val context = SSLContext.getInstance("TLS") + context.init(null, Array(new IgnoreX509TrustManager), null) + context + } + } + + implicit val clientSSLEngineProvider = + ClientSSLEngineProvider { + _ => + val engine = trustfulSslContext.createSSLEngine() + engine.setUseClientMode(true) + engine + } +} diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiRequest.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiRequest.scala new file mode 100644 index 00000000000..0588193cfbe --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiRequest.scala @@ -0,0 +1,50 @@ +package io.swagger.client.core + +sealed trait ResponseState +object ResponseState { + case object Success extends ResponseState + case object Error extends ResponseState +} + +case class ApiRequest[U]( + // required fields + method: ApiMethod, + basePath: String, + operationPath: String, + contentType: String, + + // optional fields + responses: Map[Int, (Manifest[_], ResponseState)] = Map.empty, + bodyParam: Option[Any] = None, + formParams: Map[String, Any] = Map.empty, + pathParams: Map[String, Any] = Map.empty, + queryParams: Map[String, Any] = Map.empty, + headerParams: Map[String, Any] = Map.empty, + credentials: Seq[Credentials] = List.empty) { + + def withCredentials(cred: Credentials) = copy[U](credentials = credentials :+ cred) + + def withApiKey(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) = withCredentials(ApiKeyCredentials(key, keyName, location)) + + def withSuccessResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Success))) + + def withErrorResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Error))) + + def withDefaultSuccessResponse[T](implicit m: Manifest[T]) = withSuccessResponse[T](0) + + def withDefaultErrorResponse[T](implicit m: Manifest[T]) = withErrorResponse[T](0) + + def responseForCode(statusCode: Int): Option[(Manifest[_], ResponseState)] = responses.get(statusCode) orElse responses.get(0) + + def withoutBody() = copy[U](bodyParam = None) + + def withBody(body: Any) = copy[U](bodyParam = Some(body)) + + def withFormParam(name: String, value: Any) = copy[U](formParams = formParams + (name -> value)) + + def withPathParam(name: String, value: Any) = copy[U](pathParams = pathParams + (name -> value)) + + def withQueryParam(name: String, value: Any) = copy[U](queryParams = queryParams + (name -> value)) + + def withHeaderParam(name: String, value: Any) = copy[U](headerParams = headerParams + (name -> value)) +} diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiSettings.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiSettings.scala new file mode 100644 index 00000000000..3162fb9f6be --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiSettings.scala @@ -0,0 +1,32 @@ +package io.swagger.client.core + +import java.util.concurrent.TimeUnit + +import akka.actor.{ExtendedActorSystem, Extension, ExtensionKey} +import com.typesafe.config.Config +import io.swagger.client.core.ApiInvoker.CustomStatusCode +import spray.http.HttpHeaders.RawHeader + +import scala.collection.JavaConversions._ +import scala.concurrent.duration.FiniteDuration + +class ApiSettings(config: Config) extends Extension { + def this(system: ExtendedActorSystem) = this(system.settings.config) + + private def cfg = config.getConfig("io.swagger.client.apiRequest") + + val alwaysTrustCertificates = cfg.getBoolean("trust-certificates") + val defaultHeaders = cfg.getConfig("default-headers").entrySet.toList.map(c => RawHeader(c.getKey, c.getValue.render)) + val connectionTimeout = FiniteDuration(cfg.getDuration("connection-timeout", TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS) + val compressionEnabled = cfg.getBoolean("compression.enabled") + val compressionSizeThreshold = cfg.getBytes("compression.size-threshold").toInt + val customCodes = cfg.getConfigList("custom-codes").toList.map { c => CustomStatusCode( + c.getInt("code"), + c.getString("reason"), + c.getBoolean("success")) + } + + +} + +object ApiSettings extends ExtensionKey[ApiSettings] diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/requests.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/requests.scala new file mode 100644 index 00000000000..a096a994ea3 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/requests.scala @@ -0,0 +1,166 @@ +package io.swagger.client.core + +import java.io.File +import java.net.URLEncoder +import scala.util.Try + +sealed trait ApiReturnWithHeaders { + def headers: Map[String, String] + def header(name: String): Option[String] = headers.get(name) + def getStringHeader(name: String) = header(name) + def getIntHeader(name: String) = castedHeader(name, java.lang.Integer.parseInt) + def getLongHeader(name: String) = castedHeader(name, java.lang.Long.parseLong) + def getFloatHeader(name: String) = castedHeader(name, java.lang.Float.parseFloat) + def getDoubleHeader(name: String) = castedHeader(name, java.lang.Double.parseDouble) + def getBooleanHeader(name: String) = castedHeader(name, java.lang.Boolean.parseBoolean) + private def castedHeader[U](name: String, conversion: String => U): Option[U] = { Try { header(name).map( conversion ) }.get } +} + +sealed case class ApiResponse[T](code: Int, content: T, headers: Map[String, String] = Map.empty) + extends ApiReturnWithHeaders + +sealed case class ApiError[T](code: Int, message: String, responseContent: Option[T], cause: Throwable = null, headers: Map[String, String] = Map.empty) + extends Throwable(s"($code) $message.${responseContent.map(s => s" Content : $s").getOrElse("")}", cause) + with ApiReturnWithHeaders + +sealed case class ApiMethod(value: String) + +object ApiMethods { + val CONNECT = ApiMethod("CONNECT") + val DELETE = ApiMethod("DELETE") + val GET = ApiMethod("GET") + val HEAD = ApiMethod("HEAD") + val OPTIONS = ApiMethod("OPTIONS") + val PATCH = ApiMethod("PATCH") + val POST = ApiMethod("POST") + val PUT = ApiMethod("PUT") + val TRACE = ApiMethod("TRACE") +} + +/** + * This trait needs to be added to any model defined by the api. + */ +trait ApiModel + +/** + * Single trait defining a credential that can be transformed to a paramName / paramValue tupple + */ +sealed trait Credentials { + def asQueryParam: Option[(String, String)] = None +} + +sealed case class BasicCredentials(user: String, password: String) extends Credentials + +sealed case class ApiKeyCredentials(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) extends Credentials { + override def asQueryParam: Option[(String, String)] = location match { + case ApiKeyLocations.QUERY => Some((keyName, key.value)) + case _ => None + } +} + +sealed case class ApiKeyValue(value: String) + +sealed trait ApiKeyLocation + +object ApiKeyLocations { + + case object QUERY extends ApiKeyLocation + + case object HEADER extends ApiKeyLocation +} + + +/** + * Case class used to unapply numeric values only in pattern matching + * @param value the string representation of the numeric value + */ +sealed case class NumericValue(value: String) { + override def toString = value +} + +object NumericValue { + def unapply(n: Any): Option[NumericValue] = n match { + case (_: Int | _: Long | _: Float | _: Double | _: Boolean | _: Byte) => Some(NumericValue(String.valueOf(n))) + case _ => None + } +} + +/** + * Used for params being arrays + */ +sealed case class ArrayValues(values: Seq[Any], format: CollectionFormat = CollectionFormats.CSV) + +object ArrayValues { + def apply(values: Option[Seq[Any]], format: CollectionFormat): ArrayValues = + ArrayValues(values.getOrElse(Seq.empty), format) + + def apply(values: Option[Seq[Any]]): ArrayValues = ArrayValues(values, CollectionFormats.CSV) +} + + +/** + * Defines how arrays should be rendered in query strings. + */ +sealed trait CollectionFormat + +trait MergedArrayFormat extends CollectionFormat { + def separator: String +} + +object CollectionFormats { + + case object CSV extends MergedArrayFormat { + override val separator = "," + } + + case object TSV extends MergedArrayFormat { + override val separator = "\t" + } + + case object SSV extends MergedArrayFormat { + override val separator = " " + } + + case object PIPES extends MergedArrayFormat { + override val separator = "|" + } + + case object MULTI extends CollectionFormat + +} + +object ParametersMap { + + /** + * Pimp parameters maps (Map[String, Any]) in order to transform them in a sequence of String -> Any tupples, + * with valid url-encoding, arrays handling, files preservation, ... + */ + implicit class ParametersMapImprovements(val m: Map[String, Any]) { + + def asFormattedParamsList = m.toList.flatMap(formattedParams) + + def asFormattedParams = m.flatMap(formattedParams) + + private def urlEncode(v: Any) = URLEncoder.encode(String.valueOf(v), "utf-8").replaceAll("\\+", "%20") + + private def formattedParams(tuple: (String, Any)): Seq[(String, Any)] = formattedParams(tuple._1, tuple._2) + + private def formattedParams(name: String, value: Any): Seq[(String, Any)] = value match { + case arr: ArrayValues => + arr.format match { + case CollectionFormats.MULTI => arr.values.flatMap(formattedParams(name, _)) + case format: MergedArrayFormat => Seq((name, arr.values.mkString(format.separator))) + } + case None => Seq.empty + case Some(opt) => + formattedParams(name, opt) + case s: Seq[Any] => + formattedParams(name, ArrayValues(s)) + case v: String => Seq((name, urlEncode(v))) + case NumericValue(v) => Seq((name, urlEncode(v))) + case f: File => Seq((name, f)) + case m: ApiModel => Seq((name, m)) + } + + } +} diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ApiTokenStatus.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ApiTokenStatus.scala new file mode 100644 index 00000000000..0887fb0ba76 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ApiTokenStatus.scala @@ -0,0 +1,16 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class ApiTokenStatus ( + valid: Option[Boolean], + token: Option[String], + resetsInMillis: Option[Long], + remainingCalls: Option[Long], + expiresInMillis: Option[Long], + totalRequests: Option[Long]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioFile.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioFile.scala new file mode 100644 index 00000000000..3b3e9186b69 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioFile.scala @@ -0,0 +1,24 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class AudioFile ( + attributionUrl: Option[String], + commentCount: Option[Int], + voteCount: Option[Int], + fileUrl: Option[String], + audioType: Option[String], + id: Option[Long], + duration: Option[Double], + attributionText: Option[String], + createdBy: Option[String], + description: Option[String], + createdAt: Option[DateTime], + voteWeightedAverage: Option[Float], + voteAverage: Option[Float], + word: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioType.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioType.scala new file mode 100644 index 00000000000..be7d0a1d5ef --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioType.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class AudioType ( + id: Option[Int], + name: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AuthenticationToken.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AuthenticationToken.scala new file mode 100644 index 00000000000..981c7340d8e --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AuthenticationToken.scala @@ -0,0 +1,13 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class AuthenticationToken ( + token: Option[String], + userId: Option[Long], + userSignature: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Bigram.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Bigram.scala new file mode 100644 index 00000000000..c0a567c4ff9 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Bigram.scala @@ -0,0 +1,15 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Bigram ( + count: Option[Long], + gram2: Option[String], + gram1: Option[String], + wlmi: Option[Double], + mi: Option[Double]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Category.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Category.scala new file mode 100644 index 00000000000..af66bc14753 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Category.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Category ( + id: Option[Long], + name: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Citation.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Citation.scala new file mode 100644 index 00000000000..16f75961500 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Citation.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Citation ( + cite: Option[String], + source: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ContentProvider.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ContentProvider.scala new file mode 100644 index 00000000000..c7832871f7e --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ContentProvider.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class ContentProvider ( + id: Option[Int], + name: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Definition.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Definition.scala new file mode 100644 index 00000000000..6274df1aa61 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Definition.scala @@ -0,0 +1,26 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Definition ( + extendedText: Option[String], + text: Option[String], + sourceDictionary: Option[String], + citations: Option[Seq[Citation]], + labels: Option[Seq[Label]], + score: Option[Float], + exampleUses: Option[Seq[ExampleUsage]], + attributionUrl: Option[String], + seqString: Option[String], + attributionText: Option[String], + relatedWords: Option[Seq[Related]], + sequence: Option[String], + word: Option[String], + notes: Option[Seq[Note]], + textProns: Option[Seq[TextPron]], + partOfSpeech: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/DefinitionSearchResults.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/DefinitionSearchResults.scala new file mode 100644 index 00000000000..28d7d4e239b --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/DefinitionSearchResults.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class DefinitionSearchResults ( + results: Option[Seq[Definition]], + totalResults: Option[Int]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Example.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Example.scala new file mode 100644 index 00000000000..0d4d52aec98 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Example.scala @@ -0,0 +1,22 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Example ( + id: Option[Long], + exampleId: Option[Long], + title: Option[String], + text: Option[String], + score: Option[ScoredWord], + sentence: Option[Sentence], + word: Option[String], + provider: Option[ContentProvider], + year: Option[Int], + rating: Option[Float], + documentId: Option[Long], + url: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleSearchResults.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleSearchResults.scala new file mode 100644 index 00000000000..bd4494666da --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleSearchResults.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class ExampleSearchResults ( + facets: Option[Seq[Facet]], + examples: Option[Seq[Example]]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleUsage.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleUsage.scala new file mode 100644 index 00000000000..377ee69f27a --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleUsage.scala @@ -0,0 +1,11 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class ExampleUsage ( + text: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Facet.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Facet.scala new file mode 100644 index 00000000000..80d28578b78 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Facet.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Facet ( + facetValues: Option[Seq[FacetValue]], + name: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FacetValue.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FacetValue.scala new file mode 100644 index 00000000000..8a6f5d78cbb --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FacetValue.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class FacetValue ( + count: Option[Long], + value: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Frequency.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Frequency.scala new file mode 100644 index 00000000000..58c29eb0b12 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Frequency.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Frequency ( + count: Option[Long], + year: Option[Int]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FrequencySummary.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FrequencySummary.scala new file mode 100644 index 00000000000..3eacadbde71 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FrequencySummary.scala @@ -0,0 +1,15 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class FrequencySummary ( + unknownYearCount: Option[Int], + totalCount: Option[Long], + frequencyString: Option[String], + word: Option[String], + frequency: Option[Seq[Frequency]]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Label.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Label.scala new file mode 100644 index 00000000000..5adba8e3276 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Label.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Label ( + text: Option[String], + `type`: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Note.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Note.scala new file mode 100644 index 00000000000..ff0d72524ed --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Note.scala @@ -0,0 +1,14 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Note ( + noteType: Option[String], + appliesTo: Option[Seq[String]], + value: Option[String], + pos: Option[Int]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/PartOfSpeech.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/PartOfSpeech.scala new file mode 100644 index 00000000000..182a8974ff6 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/PartOfSpeech.scala @@ -0,0 +1,13 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class PartOfSpeech ( + roots: Option[Seq[Root]], + storageAbbr: Option[Seq[String]], + allCategories: Option[Seq[Category]]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Related.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Related.scala new file mode 100644 index 00000000000..5fdd347cb33 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Related.scala @@ -0,0 +1,17 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Related ( + label1: Option[String], + relationshipType: Option[String], + label2: Option[String], + label3: Option[String], + words: Option[Seq[String]], + gram: Option[String], + label4: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Root.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Root.scala new file mode 100644 index 00000000000..ee134f80340 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Root.scala @@ -0,0 +1,13 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Root ( + id: Option[Long], + name: Option[String], + categories: Option[Seq[Category]]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ScoredWord.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ScoredWord.scala new file mode 100644 index 00000000000..7c7b7e9b5ab --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ScoredWord.scala @@ -0,0 +1,21 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class ScoredWord ( + position: Option[Int], + id: Option[Long], + docTermCount: Option[Int], + lemma: Option[String], + wordType: Option[String], + score: Option[Float], + sentenceId: Option[Long], + word: Option[String], + stopword: Option[Boolean], + baseWordScore: Option[Double], + partOfSpeech: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Sentence.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Sentence.scala new file mode 100644 index 00000000000..99f7f0400af --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Sentence.scala @@ -0,0 +1,16 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Sentence ( + hasScoredWords: Option[Boolean], + id: Option[Long], + scoredWords: Option[Seq[ScoredWord]], + display: Option[String], + rating: Option[Int], + documentMetadataId: Option[Long]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleDefinition.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleDefinition.scala new file mode 100644 index 00000000000..1807123222c --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleDefinition.scala @@ -0,0 +1,14 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class SimpleDefinition ( + text: Option[String], + source: Option[String], + note: Option[String], + partOfSpeech: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleExample.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleExample.scala new file mode 100644 index 00000000000..4548c2ece38 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleExample.scala @@ -0,0 +1,14 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class SimpleExample ( + id: Option[Long], + title: Option[String], + text: Option[String], + url: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/StringValue.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/StringValue.scala new file mode 100644 index 00000000000..bb36fabef8e --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/StringValue.scala @@ -0,0 +1,11 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class StringValue ( + word: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Syllable.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Syllable.scala new file mode 100644 index 00000000000..0db80cb840f --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Syllable.scala @@ -0,0 +1,13 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Syllable ( + text: Option[String], + seq: Option[Int], + `type`: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/TextPron.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/TextPron.scala new file mode 100644 index 00000000000..95d17c14fcf --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/TextPron.scala @@ -0,0 +1,13 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class TextPron ( + raw: Option[String], + seq: Option[Int], + rawType: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/User.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/User.scala new file mode 100644 index 00000000000..421c8f3210b --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/User.scala @@ -0,0 +1,18 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class User ( + id: Option[Long], + username: Option[String], + email: Option[String], + status: Option[Int], + faceBookId: Option[String], + userName: Option[String], + displayName: Option[String], + password: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordList.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordList.scala new file mode 100644 index 00000000000..c46484d5978 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordList.scala @@ -0,0 +1,21 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class WordList ( + id: Option[Long], + permalink: Option[String], + name: Option[String], + createdAt: Option[DateTime], + updatedAt: Option[DateTime], + lastActivityAt: Option[DateTime], + username: Option[String], + userId: Option[Long], + description: Option[String], + numberWordsInList: Option[Long], + `type`: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordListWord.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordListWord.scala new file mode 100644 index 00000000000..062f1fe6a6b --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordListWord.scala @@ -0,0 +1,17 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class WordListWord ( + id: Option[Long], + word: Option[String], + username: Option[String], + userId: Option[Long], + createdAt: Option[DateTime], + numberCommentsOnWord: Option[Long], + numberLists: Option[Long]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordObject.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordObject.scala new file mode 100644 index 00000000000..5f5c1c6a426 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordObject.scala @@ -0,0 +1,16 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class WordObject ( + id: Option[Long], + word: Option[String], + originalWord: Option[String], + suggestions: Option[Seq[String]], + canonicalForm: Option[String], + vulgar: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordOfTheDay.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordOfTheDay.scala new file mode 100644 index 00000000000..6b94e34d211 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordOfTheDay.scala @@ -0,0 +1,22 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class WordOfTheDay ( + id: Option[Long], + parentId: Option[String], + category: Option[String], + createdBy: Option[String], + createdAt: Option[DateTime], + contentProvider: Option[ContentProvider], + htmlExtra: Option[String], + word: Option[String], + definitions: Option[Seq[SimpleDefinition]], + examples: Option[Seq[SimpleExample]], + note: Option[String], + publishDate: Option[DateTime]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResult.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResult.scala new file mode 100644 index 00000000000..771fd35b2e8 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResult.scala @@ -0,0 +1,13 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class WordSearchResult ( + count: Option[Long], + lexicality: Option[Double], + word: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResults.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResults.scala new file mode 100644 index 00000000000..bc2af2a8448 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResults.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class WordSearchResults ( + searchResults: Option[Seq[WordSearchResult]], + totalResults: Option[Int]) + extends ApiModel + + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/ApiInvoker.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/ApiInvoker.scala new file mode 100644 index 00000000000..f4b25de8306 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/ApiInvoker.scala @@ -0,0 +1,195 @@ +package io.swagger.client + +import com.sun.jersey.api.client.Client +import com.sun.jersey.api.client.ClientResponse +import com.sun.jersey.api.client.config.ClientConfig +import com.sun.jersey.api.client.config.DefaultClientConfig +import com.sun.jersey.api.client.filter.LoggingFilter + +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart + +import java.io.File +import java.net.URLEncoder +import javax.ws.rs.core.MediaType + +import scala.collection.JavaConverters._ +import scala.collection.mutable.HashMap + +import com.fasterxml.jackson.module.scala.DefaultScalaModule +import com.fasterxml.jackson.datatype.joda.JodaModule +import com.fasterxml.jackson.core.JsonGenerator.Feature +import com.fasterxml.jackson.databind._ +import com.fasterxml.jackson.annotation._ +import com.fasterxml.jackson.databind.annotation.JsonSerialize + +object ScalaJsonUtil { + def getJsonMapper = { + val mapper = new ObjectMapper() + mapper.registerModule(new DefaultScalaModule()) + mapper.registerModule(new JodaModule()); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT) + mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY) + mapper + } +} + +class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, + httpHeaders: HashMap[String, String] = HashMap(), + hostMap: HashMap[String, Client] = HashMap(), + asyncHttpClient: Boolean = false, + authScheme: String = "", + authPreemptive: Boolean = false) { + + var defaultHeaders: HashMap[String, String] = httpHeaders + + def escape(value: String): String = { + URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20") + } + + def escape(value: Long): String = value.toString + def escape(value: Double): String = value.toString + def escape(value: Float): String = value.toString + + def deserialize(json: String, containerType: String, cls: Class[_]) = { + if (cls == classOf[String]) { + json match { + case s: String => { + if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) s.substring(1, s.length - 2) + else s + } + case _ => null + } + } else { + containerType.toLowerCase match { + case "array" => { + val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls) + val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] + response.asScala.toList + } + case "list" => { + val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls) + val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] + response.asScala.toList + } + case _ => { + json match { + case e: String if ("\"\"" == e) => null + case _ => mapper.readValue(json, cls) + } + } + } + } + } + + def serialize(obj: AnyRef): String = { + if (obj != null) { + obj match { + case e: List[_] => mapper.writeValueAsString(obj.asInstanceOf[List[_]].asJava) + case _ => mapper.writeValueAsString(obj) + } + } else null + } + + def invokeApi(host: String, path: String, method: String, queryParams: Map[String, String], body: AnyRef, headerParams: Map[String, String], contentType: String): String = { + val client = getClient(host) + + val querystring = queryParams.filter(k => k._2 != null).map(k => (escape(k._1) + "=" + escape(k._2))).mkString("?", "&", "") + val builder = client.resource(host + path + querystring).accept(contentType) + headerParams.map(p => builder.header(p._1, p._2)) + defaultHeaders.map(p => { + headerParams.contains(p._1) match { + case true => // override default with supplied header + case false => if (p._2 != null) builder.header(p._1, p._2) + } + }) + + val response: ClientResponse = method match { + case "GET" => { + builder.get(classOf[ClientResponse]).asInstanceOf[ClientResponse] + } + case "POST" => { + if(body != null && body.isInstanceOf[File]) { + val file = body.asInstanceOf[File] + val form = new FormDataMultiPart() + form.field("filename", file.getName()) + form.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE)) + builder.post(classOf[ClientResponse], form) + } + else { + if(body == null) builder.post(classOf[ClientResponse], serialize(body)) + else builder.`type`(contentType).post(classOf[ClientResponse], serialize(body)) + } + } + case "PUT" => { + if(body == null) builder.put(classOf[ClientResponse], null) + else builder.`type`(contentType).put(classOf[ClientResponse], serialize(body)) + } + case "DELETE" => { + builder.delete(classOf[ClientResponse]) + } + case _ => null + } + response.getClientResponseStatus().getStatusCode() match { + case 204 => "" + case code: Int if (Range(200, 299).contains(code)) => { + response.hasEntity() match { + case true => response.getEntity(classOf[String]) + case false => "" + } + } + case _ => { + val entity = response.hasEntity() match { + case true => response.getEntity(classOf[String]) + case false => "no data" + } + throw new ApiException( + response.getClientResponseStatus().getStatusCode(), + entity) + } + } + } + + def getClient(host: String): Client = { + hostMap.contains(host) match { + case true => hostMap(host) + case false => { + val client = newClient(host) + // client.addFilter(new LoggingFilter()) + hostMap += host -> client + client + } + } + } + + def newClient(host: String): Client = asyncHttpClient match { + case true => { + import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig + import org.sonatype.spice.jersey.client.ahc.AhcHttpClient + import com.ning.http.client.Realm + + val config: DefaultAhcConfig = new DefaultAhcConfig() + if (!authScheme.isEmpty) { + val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme) + config.getAsyncHttpClientConfigBuilder + .setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum) + .setUsePreemptiveAuth(authPreemptive).build) + } + AhcHttpClient.create(config) + } + case _ => Client.create() + } +} + +object ApiInvoker extends ApiInvoker(mapper = ScalaJsonUtil.getJsonMapper, + httpHeaders = HashMap(), + hostMap = HashMap(), + asyncHttpClient = false, + authScheme = "", + authPreemptive = false) + +class ApiException(val code: Int, msg: String) extends RuntimeException(msg) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/AccountApi.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/AccountApi.scala new file mode 100644 index 00000000000..3203f846f27 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/AccountApi.scala @@ -0,0 +1,201 @@ +package io.swagger.client.api + +import io.swagger.client.model.ApiTokenStatus +import io.swagger.client.model.AuthenticationToken +import io.swagger.client.model.User +import io.swagger.client.model.WordList +import io.swagger.client.ApiInvoker +import io.swagger.client.ApiException + +import java.io.File +import java.util.Date + +import scala.collection.mutable.HashMap + +class AccountApi(val defBasePath: String = "https://api.wordnik.com/v4", + defApiInvoker: ApiInvoker = ApiInvoker) { + var basePath = defBasePath + var apiInvoker = defApiInvoker + + def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value + + + def getApiTokenStatus (api_key: String) : Option[ApiTokenStatus] = { + // create path and map variables + val path = "/account.json/apiTokenStatus".replaceAll("\\{format\\}","json") + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + headerParams += "api_key" -> api_key + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[ApiTokenStatus]).asInstanceOf[ApiTokenStatus]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def authenticate (username: String, password: String) : Option[AuthenticationToken] = { + // create path and map variables + val path = "/account.json/authenticate/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(password) != "null") queryParams += "password" -> password.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[AuthenticationToken]).asInstanceOf[AuthenticationToken]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def authenticatePost (username: String, body: String) : Option[AuthenticationToken] = { + // create path and map variables + val path = "/account.json/authenticate/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) + + + + + val contentType = { + if(body != null && body.isInstanceOf[File] ) + "multipart/form-data" + else "application/json" + + + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + + + try { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[AuthenticationToken]).asInstanceOf[AuthenticationToken]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getLoggedInUser (auth_token: String) : Option[User] = { + // create path and map variables + val path = "/account.json/user".replaceAll("\\{format\\}","json") + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + headerParams += "auth_token" -> auth_token + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[User]).asInstanceOf[User]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getWordListsForLoggedInUser (auth_token: String, skip: Integer, limit: Integer) : Option[List[WordList]] = { + // create path and map variables + val path = "/account.json/wordLists".replaceAll("\\{format\\}","json") + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(skip) != "null") queryParams += "skip" -> skip.toString + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + + + headerParams += "auth_token" -> auth_token + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "array", classOf[WordList]).asInstanceOf[List[WordList]]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + +} diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordApi.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordApi.scala new file mode 100644 index 00000000000..b6f076a4b43 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordApi.scala @@ -0,0 +1,438 @@ +package io.swagger.client.api + +import io.swagger.client.model.WordObject +import io.swagger.client.model.AudioFile +import io.swagger.client.model.Definition +import io.swagger.client.model.FrequencySummary +import io.swagger.client.model.Bigram +import io.swagger.client.model.Example +import io.swagger.client.ApiInvoker +import io.swagger.client.ApiException + +import java.io.File +import java.util.Date + +import scala.collection.mutable.HashMap + +class WordApi(val defBasePath: String = "https://api.wordnik.com/v4", + defApiInvoker: ApiInvoker = ApiInvoker) { + var basePath = defBasePath + var apiInvoker = defApiInvoker + + def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value + + + def getWord (word: String, useCanonical: String, includeSuggestions: String) : Option[WordObject] = { + // create path and map variables + val path = "/word.json/{word}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + if(String.valueOf(includeSuggestions) != "null") queryParams += "includeSuggestions" -> includeSuggestions.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[WordObject]).asInstanceOf[WordObject]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getAudio (word: String, useCanonical: String, limit: Integer) : Option[List[AudioFile]] = { + // create path and map variables + val path = "/word.json/{word}/audio".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "array", classOf[AudioFile]).asInstanceOf[List[AudioFile]]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getDefinitions (word: String, limit: Integer, partOfSpeech: String, includeRelated: String, sourceDictionaries: List[String], useCanonical: String, includeTags: String) : Option[List[Definition]] = { + // create path and map variables + val path = "/word.json/{word}/definitions".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + if(String.valueOf(partOfSpeech) != "null") queryParams += "partOfSpeech" -> partOfSpeech.toString + if(String.valueOf(includeRelated) != "null") queryParams += "includeRelated" -> includeRelated.toString + if(String.valueOf(sourceDictionaries) != "null") queryParams += "sourceDictionaries" -> sourceDictionaries.toString + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + if(String.valueOf(includeTags) != "null") queryParams += "includeTags" -> includeTags.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "array", classOf[Definition]).asInstanceOf[List[Definition]]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getEtymologies (word: String, useCanonical: String) : Option[List[String]] = { + // create path and map variables + val path = "/word.json/{word}/etymologies".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "array", classOf[String]).asInstanceOf[List[String]]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getExamples (word: String, includeDuplicates: String, useCanonical: String, skip: Integer, limit: Integer) = { + // create path and map variables + val path = "/word.json/{word}/examples".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(includeDuplicates) != "null") queryParams += "includeDuplicates" -> includeDuplicates.toString + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + if(String.valueOf(skip) != "null") queryParams += "skip" -> skip.toString + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getWordFrequency (word: String, useCanonical: String, startYear: Integer, endYear: Integer) : Option[FrequencySummary] = { + // create path and map variables + val path = "/word.json/{word}/frequency".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + if(String.valueOf(startYear) != "null") queryParams += "startYear" -> startYear.toString + if(String.valueOf(endYear) != "null") queryParams += "endYear" -> endYear.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[FrequencySummary]).asInstanceOf[FrequencySummary]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getHyphenation (word: String, useCanonical: String, sourceDictionary: String, limit: Integer) = { + // create path and map variables + val path = "/word.json/{word}/hyphenation".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + if(String.valueOf(sourceDictionary) != "null") queryParams += "sourceDictionary" -> sourceDictionary.toString + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getPhrases (word: String, limit: Integer, wlmi: Integer, useCanonical: String) : Option[List[Bigram]] = { + // create path and map variables + val path = "/word.json/{word}/phrases".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + if(String.valueOf(wlmi) != "null") queryParams += "wlmi" -> wlmi.toString + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "array", classOf[Bigram]).asInstanceOf[List[Bigram]]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getTextPronunciations (word: String, useCanonical: String, sourceDictionary: String, typeFormat: String, limit: Integer) = { + // create path and map variables + val path = "/word.json/{word}/pronunciations".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + if(String.valueOf(sourceDictionary) != "null") queryParams += "sourceDictionary" -> sourceDictionary.toString + if(String.valueOf(typeFormat) != "null") queryParams += "typeFormat" -> typeFormat.toString + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getRelatedWords (word: String, useCanonical: String, relationshipTypes: String, limitPerRelationshipType: Integer) = { + // create path and map variables + val path = "/word.json/{word}/relatedWords".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + if(String.valueOf(relationshipTypes) != "null") queryParams += "relationshipTypes" -> relationshipTypes.toString + if(String.valueOf(limitPerRelationshipType) != "null") queryParams += "limitPerRelationshipType" -> limitPerRelationshipType.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getTopExample (word: String, useCanonical: String) : Option[Example] = { + // create path and map variables + val path = "/word.json/{word}/topExample".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[Example]).asInstanceOf[Example]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + +} diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordListApi.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordListApi.scala new file mode 100644 index 00000000000..958bc234ab3 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordListApi.scala @@ -0,0 +1,245 @@ +package io.swagger.client.api + +import io.swagger.client.model.WordList +import io.swagger.client.model.StringValue +import io.swagger.client.ApiInvoker +import io.swagger.client.ApiException + +import java.io.File +import java.util.Date + +import scala.collection.mutable.HashMap + +class WordListApi(val defBasePath: String = "https://api.wordnik.com/v4", + defApiInvoker: ApiInvoker = ApiInvoker) { + var basePath = defBasePath + var apiInvoker = defApiInvoker + + def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value + + + def getWordListByPermalink (permalink: String, auth_token: String) : Option[WordList] = { + // create path and map variables + val path = "/wordList.json/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escape(permalink)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + headerParams += "auth_token" -> auth_token + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[WordList]).asInstanceOf[WordList]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def updateWordList (permalink: String, body: WordList, auth_token: String) = { + // create path and map variables + val path = "/wordList.json/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escape(permalink)) + + + + + val contentType = { + if(body != null && body.isInstanceOf[File] ) + "multipart/form-data" + else "application/json" + + + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + headerParams += "auth_token" -> auth_token + + + try { + apiInvoker.invokeApi(basePath, path, "PUT", queryParams.toMap, body, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def deleteWordList (permalink: String, auth_token: String) = { + // create path and map variables + val path = "/wordList.json/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escape(permalink)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + headerParams += "auth_token" -> auth_token + + + try { + apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def deleteWordsFromWordList (permalink: String, body: List[StringValue], auth_token: String) = { + // create path and map variables + val path = "/wordList.json/{permalink}/deleteWords".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escape(permalink)) + + + + + val contentType = { + if(body != null && body.isInstanceOf[File] ) + "multipart/form-data" + else "application/json" + + + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + headerParams += "auth_token" -> auth_token + + + try { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getWordListWords (permalink: String, sortBy: String, sortOrder: String, skip: Integer, limit: Integer, auth_token: String) = { + // create path and map variables + val path = "/wordList.json/{permalink}/words".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escape(permalink)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(sortBy) != "null") queryParams += "sortBy" -> sortBy.toString + if(String.valueOf(sortOrder) != "null") queryParams += "sortOrder" -> sortOrder.toString + if(String.valueOf(skip) != "null") queryParams += "skip" -> skip.toString + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + + + headerParams += "auth_token" -> auth_token + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def addWordsToWordList (permalink: String, body: List[StringValue], auth_token: String) = { + // create path and map variables + val path = "/wordList.json/{permalink}/words".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escape(permalink)) + + + + + val contentType = { + if(body != null && body.isInstanceOf[File] ) + "multipart/form-data" + else "application/json" + + + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + headerParams += "auth_token" -> auth_token + + + try { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + +} diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordListsApi.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordListsApi.scala new file mode 100644 index 00000000000..805f62d4be7 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordListsApi.scala @@ -0,0 +1,57 @@ +package io.swagger.client.api + +import io.swagger.client.model.WordList +import io.swagger.client.ApiInvoker +import io.swagger.client.ApiException + +import java.io.File +import java.util.Date + +import scala.collection.mutable.HashMap + +class WordListsApi(val defBasePath: String = "https://api.wordnik.com/v4", + defApiInvoker: ApiInvoker = ApiInvoker) { + var basePath = defBasePath + var apiInvoker = defApiInvoker + + def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value + + + def createWordList (body: WordList, auth_token: String) : Option[WordList] = { + // create path and map variables + val path = "/wordLists.json".replaceAll("\\{format\\}","json") + + + val contentType = { + if(body != null && body.isInstanceOf[File] ) + "multipart/form-data" + else "application/json" + + + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + headerParams += "auth_token" -> auth_token + + + try { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[WordList]).asInstanceOf[WordList]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + +} diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordsApi.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordsApi.scala new file mode 100644 index 00000000000..6613abb7589 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordsApi.scala @@ -0,0 +1,238 @@ +package io.swagger.client.api + +import io.swagger.client.model.WordObject +import io.swagger.client.model.DefinitionSearchResults +import io.swagger.client.model.WordSearchResults +import io.swagger.client.model.WordOfTheDay +import io.swagger.client.ApiInvoker +import io.swagger.client.ApiException + +import java.io.File +import java.util.Date + +import scala.collection.mutable.HashMap + +class WordsApi(val defBasePath: String = "https://api.wordnik.com/v4", + defApiInvoker: ApiInvoker = ApiInvoker) { + var basePath = defBasePath + var apiInvoker = defApiInvoker + + def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value + + + def getRandomWord (hasDictionaryDef: String, includePartOfSpeech: String, excludePartOfSpeech: String, minCorpusCount: Integer, maxCorpusCount: Integer, minDictionaryCount: Integer, maxDictionaryCount: Integer, minLength: Integer, maxLength: Integer) : Option[WordObject] = { + // create path and map variables + val path = "/words.json/randomWord".replaceAll("\\{format\\}","json") + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(hasDictionaryDef) != "null") queryParams += "hasDictionaryDef" -> hasDictionaryDef.toString + if(String.valueOf(includePartOfSpeech) != "null") queryParams += "includePartOfSpeech" -> includePartOfSpeech.toString + if(String.valueOf(excludePartOfSpeech) != "null") queryParams += "excludePartOfSpeech" -> excludePartOfSpeech.toString + if(String.valueOf(minCorpusCount) != "null") queryParams += "minCorpusCount" -> minCorpusCount.toString + if(String.valueOf(maxCorpusCount) != "null") queryParams += "maxCorpusCount" -> maxCorpusCount.toString + if(String.valueOf(minDictionaryCount) != "null") queryParams += "minDictionaryCount" -> minDictionaryCount.toString + if(String.valueOf(maxDictionaryCount) != "null") queryParams += "maxDictionaryCount" -> maxDictionaryCount.toString + if(String.valueOf(minLength) != "null") queryParams += "minLength" -> minLength.toString + if(String.valueOf(maxLength) != "null") queryParams += "maxLength" -> maxLength.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[WordObject]).asInstanceOf[WordObject]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getRandomWords (hasDictionaryDef: String, includePartOfSpeech: String, excludePartOfSpeech: String, minCorpusCount: Integer, maxCorpusCount: Integer, minDictionaryCount: Integer, maxDictionaryCount: Integer, minLength: Integer, maxLength: Integer, sortBy: String, sortOrder: String, limit: Integer) = { + // create path and map variables + val path = "/words.json/randomWords".replaceAll("\\{format\\}","json") + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(hasDictionaryDef) != "null") queryParams += "hasDictionaryDef" -> hasDictionaryDef.toString + if(String.valueOf(includePartOfSpeech) != "null") queryParams += "includePartOfSpeech" -> includePartOfSpeech.toString + if(String.valueOf(excludePartOfSpeech) != "null") queryParams += "excludePartOfSpeech" -> excludePartOfSpeech.toString + if(String.valueOf(minCorpusCount) != "null") queryParams += "minCorpusCount" -> minCorpusCount.toString + if(String.valueOf(maxCorpusCount) != "null") queryParams += "maxCorpusCount" -> maxCorpusCount.toString + if(String.valueOf(minDictionaryCount) != "null") queryParams += "minDictionaryCount" -> minDictionaryCount.toString + if(String.valueOf(maxDictionaryCount) != "null") queryParams += "maxDictionaryCount" -> maxDictionaryCount.toString + if(String.valueOf(minLength) != "null") queryParams += "minLength" -> minLength.toString + if(String.valueOf(maxLength) != "null") queryParams += "maxLength" -> maxLength.toString + if(String.valueOf(sortBy) != "null") queryParams += "sortBy" -> sortBy.toString + if(String.valueOf(sortOrder) != "null") queryParams += "sortOrder" -> sortOrder.toString + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def reverseDictionary (query: String, findSenseForWord: String, includeSourceDictionaries: String, excludeSourceDictionaries: String, includePartOfSpeech: String, excludePartOfSpeech: String, minCorpusCount: Integer, maxCorpusCount: Integer, minLength: Integer, maxLength: Integer, expandTerms: String, includeTags: String, sortBy: String, sortOrder: String, skip: String, limit: Integer) : Option[DefinitionSearchResults] = { + // create path and map variables + val path = "/words.json/reverseDictionary".replaceAll("\\{format\\}","json") + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(query) != "null") queryParams += "query" -> query.toString + if(String.valueOf(findSenseForWord) != "null") queryParams += "findSenseForWord" -> findSenseForWord.toString + if(String.valueOf(includeSourceDictionaries) != "null") queryParams += "includeSourceDictionaries" -> includeSourceDictionaries.toString + if(String.valueOf(excludeSourceDictionaries) != "null") queryParams += "excludeSourceDictionaries" -> excludeSourceDictionaries.toString + if(String.valueOf(includePartOfSpeech) != "null") queryParams += "includePartOfSpeech" -> includePartOfSpeech.toString + if(String.valueOf(excludePartOfSpeech) != "null") queryParams += "excludePartOfSpeech" -> excludePartOfSpeech.toString + if(String.valueOf(minCorpusCount) != "null") queryParams += "minCorpusCount" -> minCorpusCount.toString + if(String.valueOf(maxCorpusCount) != "null") queryParams += "maxCorpusCount" -> maxCorpusCount.toString + if(String.valueOf(minLength) != "null") queryParams += "minLength" -> minLength.toString + if(String.valueOf(maxLength) != "null") queryParams += "maxLength" -> maxLength.toString + if(String.valueOf(expandTerms) != "null") queryParams += "expandTerms" -> expandTerms.toString + if(String.valueOf(includeTags) != "null") queryParams += "includeTags" -> includeTags.toString + if(String.valueOf(sortBy) != "null") queryParams += "sortBy" -> sortBy.toString + if(String.valueOf(sortOrder) != "null") queryParams += "sortOrder" -> sortOrder.toString + if(String.valueOf(skip) != "null") queryParams += "skip" -> skip.toString + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[DefinitionSearchResults]).asInstanceOf[DefinitionSearchResults]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def searchWords (query: String, caseSensitive: String, includePartOfSpeech: String, excludePartOfSpeech: String, minCorpusCount: Integer, maxCorpusCount: Integer, minDictionaryCount: Integer, maxDictionaryCount: Integer, minLength: Integer, maxLength: Integer, skip: Integer, limit: Integer) : Option[WordSearchResults] = { + // create path and map variables + val path = "/words.json/search/{query}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "query" + "\\}",apiInvoker.escape(query)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(caseSensitive) != "null") queryParams += "caseSensitive" -> caseSensitive.toString + if(String.valueOf(includePartOfSpeech) != "null") queryParams += "includePartOfSpeech" -> includePartOfSpeech.toString + if(String.valueOf(excludePartOfSpeech) != "null") queryParams += "excludePartOfSpeech" -> excludePartOfSpeech.toString + if(String.valueOf(minCorpusCount) != "null") queryParams += "minCorpusCount" -> minCorpusCount.toString + if(String.valueOf(maxCorpusCount) != "null") queryParams += "maxCorpusCount" -> maxCorpusCount.toString + if(String.valueOf(minDictionaryCount) != "null") queryParams += "minDictionaryCount" -> minDictionaryCount.toString + if(String.valueOf(maxDictionaryCount) != "null") queryParams += "maxDictionaryCount" -> maxDictionaryCount.toString + if(String.valueOf(minLength) != "null") queryParams += "minLength" -> minLength.toString + if(String.valueOf(maxLength) != "null") queryParams += "maxLength" -> maxLength.toString + if(String.valueOf(skip) != "null") queryParams += "skip" -> skip.toString + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[WordSearchResults]).asInstanceOf[WordSearchResults]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getWordOfTheDay (date: String) : Option[WordOfTheDay] = { + // create path and map variables + val path = "/words.json/wordOfTheDay".replaceAll("\\{format\\}","json") + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(date) != "null") queryParams += "date" -> date.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[WordOfTheDay]).asInstanceOf[WordOfTheDay]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + +} diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ApiTokenStatus.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ApiTokenStatus.scala new file mode 100644 index 00000000000..9ec5f7cec64 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ApiTokenStatus.scala @@ -0,0 +1,13 @@ +package io.swagger.client.model + + + + +case class ApiTokenStatus ( + valid: Boolean, + token: String, + resetsInMillis: Long, + remainingCalls: Long, + expiresInMillis: Long, + totalRequests: Long) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AudioFile.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AudioFile.scala new file mode 100644 index 00000000000..6a8355c2078 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AudioFile.scala @@ -0,0 +1,22 @@ +package io.swagger.client.model + +import org.joda.time.DateTime + + + +case class AudioFile ( + attributionUrl: String, + commentCount: Integer, + voteCount: Integer, + fileUrl: String, + audioType: String, + id: Long, + duration: Double, + attributionText: String, + createdBy: String, + description: String, + createdAt: DateTime, + voteWeightedAverage: Float, + voteAverage: Float, + word: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AudioType.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AudioType.scala new file mode 100644 index 00000000000..1a4e310481a --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AudioType.scala @@ -0,0 +1,9 @@ +package io.swagger.client.model + + + + +case class AudioType ( + id: Integer, + name: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AuthenticationToken.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AuthenticationToken.scala new file mode 100644 index 00000000000..80d13cc41a5 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AuthenticationToken.scala @@ -0,0 +1,10 @@ +package io.swagger.client.model + + + + +case class AuthenticationToken ( + token: String, + userId: Long, + userSignature: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Bigram.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Bigram.scala new file mode 100644 index 00000000000..0ecde0290ef --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Bigram.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + + + + +case class Bigram ( + count: Long, + gram2: String, + gram1: String, + wlmi: Double, + mi: Double) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Category.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Category.scala new file mode 100644 index 00000000000..122411e3ff7 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Category.scala @@ -0,0 +1,9 @@ +package io.swagger.client.model + + + + +case class Category ( + id: Long, + name: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Citation.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Citation.scala new file mode 100644 index 00000000000..a8192a80822 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Citation.scala @@ -0,0 +1,9 @@ +package io.swagger.client.model + + + + +case class Citation ( + cite: String, + source: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ContentProvider.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ContentProvider.scala new file mode 100644 index 00000000000..8638e5ae204 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ContentProvider.scala @@ -0,0 +1,9 @@ +package io.swagger.client.model + + + + +case class ContentProvider ( + id: Integer, + name: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Definition.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Definition.scala new file mode 100644 index 00000000000..a4e323ddb29 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Definition.scala @@ -0,0 +1,29 @@ +package io.swagger.client.model + +import io.swagger.client.model.ExampleUsage +import io.swagger.client.model.Note +import io.swagger.client.model.Label +import io.swagger.client.model.Related +import io.swagger.client.model.Citation +import io.swagger.client.model.TextPron + + + +case class Definition ( + extendedText: String, + text: String, + sourceDictionary: String, + citations: List[Citation], + labels: List[Label], + score: Float, + exampleUses: List[ExampleUsage], + attributionUrl: String, + seqString: String, + attributionText: String, + relatedWords: List[Related], + sequence: String, + word: String, + notes: List[Note], + textProns: List[TextPron], + partOfSpeech: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/DefinitionSearchResults.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/DefinitionSearchResults.scala new file mode 100644 index 00000000000..bf7c430ff10 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/DefinitionSearchResults.scala @@ -0,0 +1,10 @@ +package io.swagger.client.model + +import io.swagger.client.model.Definition + + + +case class DefinitionSearchResults ( + results: List[Definition], + totalResults: Integer) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Example.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Example.scala new file mode 100644 index 00000000000..7f9544ad5b4 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Example.scala @@ -0,0 +1,22 @@ +package io.swagger.client.model + +import io.swagger.client.model.Sentence +import io.swagger.client.model.ContentProvider +import io.swagger.client.model.ScoredWord + + + +case class Example ( + id: Long, + exampleId: Long, + title: String, + text: String, + score: ScoredWord, + sentence: Sentence, + word: String, + provider: ContentProvider, + year: Integer, + rating: Float, + documentId: Long, + url: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ExampleSearchResults.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ExampleSearchResults.scala new file mode 100644 index 00000000000..8d33a90020d --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ExampleSearchResults.scala @@ -0,0 +1,11 @@ +package io.swagger.client.model + +import io.swagger.client.model.Example +import io.swagger.client.model.Facet + + + +case class ExampleSearchResults ( + facets: List[Facet], + examples: List[Example]) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ExampleUsage.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ExampleUsage.scala new file mode 100644 index 00000000000..4e54562515c --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ExampleUsage.scala @@ -0,0 +1,8 @@ +package io.swagger.client.model + + + + +case class ExampleUsage ( + text: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Facet.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Facet.scala new file mode 100644 index 00000000000..4bea80d58ff --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Facet.scala @@ -0,0 +1,10 @@ +package io.swagger.client.model + +import io.swagger.client.model.FacetValue + + + +case class Facet ( + facetValues: List[FacetValue], + name: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/FacetValue.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/FacetValue.scala new file mode 100644 index 00000000000..21ec01a8332 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/FacetValue.scala @@ -0,0 +1,9 @@ +package io.swagger.client.model + + + + +case class FacetValue ( + count: Long, + value: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Frequency.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Frequency.scala new file mode 100644 index 00000000000..ac1d92e4507 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Frequency.scala @@ -0,0 +1,9 @@ +package io.swagger.client.model + + + + +case class Frequency ( + count: Long, + year: Integer) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/FrequencySummary.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/FrequencySummary.scala new file mode 100644 index 00000000000..15c4b15ac12 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/FrequencySummary.scala @@ -0,0 +1,13 @@ +package io.swagger.client.model + +import io.swagger.client.model.Frequency + + + +case class FrequencySummary ( + unknownYearCount: Integer, + totalCount: Long, + frequencyString: String, + word: String, + frequency: List[Frequency]) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Label.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Label.scala new file mode 100644 index 00000000000..73644b338f2 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Label.scala @@ -0,0 +1,9 @@ +package io.swagger.client.model + + + + +case class Label ( + text: String, + _type: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Note.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Note.scala new file mode 100644 index 00000000000..c5424025d3b --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Note.scala @@ -0,0 +1,11 @@ +package io.swagger.client.model + + + + +case class Note ( + noteType: String, + appliesTo: List[String], + value: String, + pos: Integer) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/PartOfSpeech.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/PartOfSpeech.scala new file mode 100644 index 00000000000..74d1fa926d7 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/PartOfSpeech.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.model.Category +import io.swagger.client.model.Root + + + +case class PartOfSpeech ( + roots: List[Root], + storageAbbr: List[String], + allCategories: List[Category]) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Related.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Related.scala new file mode 100644 index 00000000000..0207dc96b16 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Related.scala @@ -0,0 +1,14 @@ +package io.swagger.client.model + + + + +case class Related ( + label1: String, + relationshipType: String, + label2: String, + label3: String, + words: List[String], + gram: String, + label4: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Root.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Root.scala new file mode 100644 index 00000000000..9210af25f4d --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Root.scala @@ -0,0 +1,11 @@ +package io.swagger.client.model + +import io.swagger.client.model.Category + + + +case class Root ( + id: Long, + name: String, + categories: List[Category]) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ScoredWord.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ScoredWord.scala new file mode 100644 index 00000000000..f74fcba41f7 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ScoredWord.scala @@ -0,0 +1,18 @@ +package io.swagger.client.model + + + + +case class ScoredWord ( + position: Integer, + id: Long, + docTermCount: Integer, + lemma: String, + wordType: String, + score: Float, + sentenceId: Long, + word: String, + stopword: Boolean, + baseWordScore: Double, + partOfSpeech: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Sentence.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Sentence.scala new file mode 100644 index 00000000000..04319cd6029 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Sentence.scala @@ -0,0 +1,14 @@ +package io.swagger.client.model + +import io.swagger.client.model.ScoredWord + + + +case class Sentence ( + hasScoredWords: Boolean, + id: Long, + scoredWords: List[ScoredWord], + display: String, + rating: Integer, + documentMetadataId: Long) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/SimpleDefinition.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/SimpleDefinition.scala new file mode 100644 index 00000000000..1071880411c --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/SimpleDefinition.scala @@ -0,0 +1,11 @@ +package io.swagger.client.model + + + + +case class SimpleDefinition ( + text: String, + source: String, + note: String, + partOfSpeech: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/SimpleExample.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/SimpleExample.scala new file mode 100644 index 00000000000..61e9154acfb --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/SimpleExample.scala @@ -0,0 +1,11 @@ +package io.swagger.client.model + + + + +case class SimpleExample ( + id: Long, + title: String, + text: String, + url: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/StringValue.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/StringValue.scala new file mode 100644 index 00000000000..1ff8087c817 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/StringValue.scala @@ -0,0 +1,8 @@ +package io.swagger.client.model + + + + +case class StringValue ( + word: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Syllable.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Syllable.scala new file mode 100644 index 00000000000..04ca0f802ab --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Syllable.scala @@ -0,0 +1,10 @@ +package io.swagger.client.model + + + + +case class Syllable ( + text: String, + seq: Integer, + _type: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/TextPron.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/TextPron.scala new file mode 100644 index 00000000000..582e62b5aa1 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/TextPron.scala @@ -0,0 +1,10 @@ +package io.swagger.client.model + + + + +case class TextPron ( + raw: String, + seq: Integer, + rawType: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/User.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/User.scala new file mode 100644 index 00000000000..4651b6eee71 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/User.scala @@ -0,0 +1,15 @@ +package io.swagger.client.model + + + + +case class User ( + id: Long, + username: String, + email: String, + status: Integer, + faceBookId: String, + userName: String, + displayName: String, + password: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordList.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordList.scala new file mode 100644 index 00000000000..b37ae05661a --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordList.scala @@ -0,0 +1,19 @@ +package io.swagger.client.model + +import org.joda.time.DateTime + + + +case class WordList ( + id: Long, + permalink: String, + name: String, + createdAt: DateTime, + updatedAt: DateTime, + lastActivityAt: DateTime, + username: String, + userId: Long, + description: String, + numberWordsInList: Long, + _type: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordListWord.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordListWord.scala new file mode 100644 index 00000000000..a28fdd0f181 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordListWord.scala @@ -0,0 +1,15 @@ +package io.swagger.client.model + +import org.joda.time.DateTime + + + +case class WordListWord ( + id: Long, + word: String, + username: String, + userId: Long, + createdAt: DateTime, + numberCommentsOnWord: Long, + numberLists: Long) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordObject.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordObject.scala new file mode 100644 index 00000000000..5d3d3a44d7b --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordObject.scala @@ -0,0 +1,13 @@ +package io.swagger.client.model + + + + +case class WordObject ( + id: Long, + word: String, + originalWord: String, + suggestions: List[String], + canonicalForm: String, + vulgar: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordOfTheDay.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordOfTheDay.scala new file mode 100644 index 00000000000..b41e1afc286 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordOfTheDay.scala @@ -0,0 +1,23 @@ +package io.swagger.client.model + +import org.joda.time.DateTime +import io.swagger.client.model.SimpleDefinition +import io.swagger.client.model.ContentProvider +import io.swagger.client.model.SimpleExample + + + +case class WordOfTheDay ( + id: Long, + parentId: String, + category: String, + createdBy: String, + createdAt: DateTime, + contentProvider: ContentProvider, + htmlExtra: String, + word: String, + definitions: List[SimpleDefinition], + examples: List[SimpleExample], + note: String, + publishDate: DateTime) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordSearchResult.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordSearchResult.scala new file mode 100644 index 00000000000..4feb0d31190 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordSearchResult.scala @@ -0,0 +1,10 @@ +package io.swagger.client.model + + + + +case class WordSearchResult ( + count: Long, + lexicality: Double, + word: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordSearchResults.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordSearchResults.scala new file mode 100644 index 00000000000..bf46436eef2 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordSearchResults.scala @@ -0,0 +1,10 @@ +package io.swagger.client.model + +import io.swagger.client.model.WordSearchResult + + + +case class WordSearchResults ( + searchResults: List[WordSearchResult], + totalResults: Integer) + diff --git a/samples/html/index.html b/samples/html/index.html index 1025186dc4b..9d47aa360eb 100644 --- a/samples/html/index.html +++ b/samples/html/index.html @@ -69,7 +69,7 @@
status (optional)
-
Query Parameter — Status values that need to be considered for filter
+
Query Parameter — Status values that need to be considered for filter default: available

Return type

@@ -79,11 +79,29 @@

Example data

Content-Type: application/json
-
[ {\n  "tags" : [ {\n    "id" : 123456789,\n    "name" : "aeiou"\n  } ],\n  "id" : 123456789,\n  "category" : {\n    "id" : 123456789,\n    "name" : "aeiou"\n  },\n  "status" : "aeiou",\n  "name" : "doggie",\n  "photoUrls" : [ "aeiou" ]\n} ]
+
[ {
+  "tags" : [ {
+    "id" : 123456789,
+    "name" : "aeiou"
+  } ],
+  "id" : 123456789,
+  "category" : {
+    "id" : 123456789,
+    "name" : "aeiou"
+  },
+  "status" : "aeiou",
+  "name" : "doggie",
+  "photoUrls" : [ "aeiou" ]
+} ]

Example data

Content-Type: application/xml
-
\n  123456\n  \n    123456\n    string\n  \n  doggie\n  string\n  \n    123456\n    string\n  \n  string\n
+
<Pet>
+  <id>123456</id>
+  <name>doggie</name>
+  <photoUrls>string</photoUrls>
+  <status>string</status>
+</Pet>

@@ -108,11 +126,29 @@

Example data

Content-Type: application/json
-
[ {\n  "tags" : [ {\n    "id" : 123456789,\n    "name" : "aeiou"\n  } ],\n  "id" : 123456789,\n  "category" : {\n    "id" : 123456789,\n    "name" : "aeiou"\n  },\n  "status" : "aeiou",\n  "name" : "doggie",\n  "photoUrls" : [ "aeiou" ]\n} ]
+
[ {
+  "tags" : [ {
+    "id" : 123456789,
+    "name" : "aeiou"
+  } ],
+  "id" : 123456789,
+  "category" : {
+    "id" : 123456789,
+    "name" : "aeiou"
+  },
+  "status" : "aeiou",
+  "name" : "doggie",
+  "photoUrls" : [ "aeiou" ]
+} ]

Example data

Content-Type: application/xml
-
\n  123456\n  \n    123456\n    string\n  \n  doggie\n  string\n  \n    123456\n    string\n  \n  string\n
+
<Pet>
+  <id>123456</id>
+  <name>doggie</name>
+  <photoUrls>string</photoUrls>
+  <status>string</status>
+</Pet>

@@ -137,11 +173,29 @@

Example data

Content-Type: application/json
-
{\n  "tags" : [ {\n    "id" : 123456789,\n    "name" : "aeiou"\n  } ],\n  "id" : 123456789,\n  "category" : {\n    "id" : 123456789,\n    "name" : "aeiou"\n  },\n  "status" : "aeiou",\n  "name" : "doggie",\n  "photoUrls" : [ "aeiou" ]\n}
+
{
+  "tags" : [ {
+    "id" : 123456789,
+    "name" : "aeiou"
+  } ],
+  "id" : 123456789,
+  "category" : {
+    "id" : 123456789,
+    "name" : "aeiou"
+  },
+  "status" : "aeiou",
+  "name" : "doggie",
+  "photoUrls" : [ "aeiou" ]
+}

Example data

Content-Type: application/xml
-
\n  123456\n  \n    123456\n    string\n  \n  doggie\n  string\n  \n    123456\n    string\n  \n  string\n
+
<Pet>
+  <id>123456</id>
+  <name>doggie</name>
+  <photoUrls>string</photoUrls>
+  <status>string</status>
+</Pet>

@@ -241,11 +295,13 @@

Example data

Content-Type: application/json
-
{\n  "key" : 123\n}
+
{
+  "key" : 123
+}

Example data

Content-Type: application/xml
-
not implemented com.wordnik.swagger.models.properties.MapProperty@5076b51c
+
not implemented com.wordnik.swagger.models.properties.MapProperty@3e

@@ -270,11 +326,25 @@

Example data

Content-Type: application/json
-
{\n  "id" : 123456789,\n  "petId" : 123456789,\n  "complete" : true,\n  "status" : "aeiou",\n  "quantity" : 123,\n  "shipDate" : "2015-05-12T09:58:06.953+0000"\n}
+
{
+  "id" : 123456789,
+  "petId" : 123456789,
+  "complete" : true,
+  "status" : "aeiou",
+  "quantity" : 123,
+  "shipDate" : "2015-05-21T05:49:06.118+0000"
+}

Example data

Content-Type: application/xml
-
\n  123456\n  123456\n  0\n  2015-05-12T05:58:06.956Z\n  string\n  true\n
+
<Order>
+  <id>123456</id>
+  <petId>123456</petId>
+  <quantity>0</quantity>
+  <shipDate>2015-05-20T22:49:06.120Z</shipDate>
+  <status>string</status>
+  <complete>true</complete>
+</Order>

@@ -299,11 +369,25 @@

Example data

Content-Type: application/json
-
{\n  "id" : 123456789,\n  "petId" : 123456789,\n  "complete" : true,\n  "status" : "aeiou",\n  "quantity" : 123,\n  "shipDate" : "2015-05-12T09:58:06.957+0000"\n}
+
{
+  "id" : 123456789,
+  "petId" : 123456789,
+  "complete" : true,
+  "status" : "aeiou",
+  "quantity" : 123,
+  "shipDate" : "2015-05-21T05:49:06.121+0000"
+}

Example data

Content-Type: application/xml
-
\n  123456\n  123456\n  0\n  2015-05-12T05:58:06.957Z\n  string\n  true\n
+
<Order>
+  <id>123456</id>
+  <petId>123456</petId>
+  <quantity>0</quantity>
+  <shipDate>2015-05-20T22:49:06.122Z</shipDate>
+  <status>string</status>
+  <complete>true</complete>
+</Order>

@@ -415,7 +499,7 @@

Example data

Content-Type: application/json
-
"aeiou"
+
"aeiou"

Example data

Content-Type: application/xml
@@ -462,11 +546,16 @@

Example data

Content-Type: application/json
-
{\n  "id" : 123456789,\n  "lastName" : "aeiou",\n  "phone" : "aeiou",\n  "username" : "aeiou",\n  "email" : "aeiou",\n  "userStatus" : 123,\n  "firstName" : "aeiou",\n  "password" : "aeiou"\n}
- -

Example data

-
Content-Type: application/xml
-
\n  123456\n  string\n  string\n  string\n  string\n  string\n  string\n  0\n
+
{
+  "id" : 1,
+  "username" : "johnp",
+  "firstName" : "John",
+  "lastName" : "Public",
+  "email" : "johnp@swagger.io",
+  "password" : "-secret-",
+  "phone" : "0123456789",
+  "userStatus" : 0
+}

diff --git a/samples/server/petstore/jaxrs/pom.xml b/samples/server/petstore/jaxrs/pom.xml index c928b341b38..b57a4fd416d 100644 --- a/samples/server/petstore/jaxrs/pom.xml +++ b/samples/server/petstore/jaxrs/pom.xml @@ -129,7 +129,7 @@ - 1.5.2-M2-SNAPSHOT + 1.5.2-M2 9.2.9.v20150224 1.13 1.6.3 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 index 8b3b9d40b06..8abaf768136 100644 --- 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 @@ -21,12 +21,14 @@ 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", }) + @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 = { @@ -45,7 +47,7 @@ public class PetApi { @POST - @Consumes({ "application/json", "application/xml", }) + @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 = { @@ -68,7 +70,7 @@ public class PetApi { @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") @QueryParam("status") List status) + 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(); @@ -113,7 +115,7 @@ public class PetApi { @POST @Path("/{petId}") - @Consumes({ "application/x-www-form-urlencoded", }) + @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 = { @@ -146,7 +148,7 @@ public class PetApi { @POST @Path("/{petId}/uploadImage") - @Consumes({ "multipart/form-data", }) + @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 = { 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 index d2bde7cf35b..660f6317422 100644 --- 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 @@ -21,6 +21,8 @@ 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 { 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 index 3f6da2c5d92..d907b8b579b 100644 --- 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 @@ -21,6 +21,8 @@ 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 { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java index ca48e7b10ff..a39a8e70970 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java @@ -40,9 +40,11 @@ public class PetApi { @ApiResponse(code = 400, message = "Invalid ID supplied") }) @RequestMapping(value = "", produces = { "application/json", "application/xml" }, - consumes = { "application/json", "application/xml", }, + consumes = { "application/json", "application/xml" }, method = RequestMethod.PUT) - public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) + public ResponseEntity updatePet( + +@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -55,9 +57,11 @@ public class PetApi { @ApiResponse(code = 405, message = "Invalid input") }) @RequestMapping(value = "", produces = { "application/json", "application/xml" }, - consumes = { "application/json", "application/xml", }, + consumes = { "application/json", "application/xml" }, method = RequestMethod.POST) - public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) + public ResponseEntity addPet( + +@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -73,7 +77,9 @@ public class PetApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter") @RequestParam(value = "status", required = false) List status) + public ResponseEntity findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", defaultValue = "available") @RequestParam(value = "status", required = false, defaultValue="available") List status + +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -89,7 +95,9 @@ public class PetApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity findPetsByTags(@ApiParam(value = "Tags to filter by") @RequestParam(value = "tags", required = false) List tags) + public ResponseEntity findPetsByTags(@ApiParam(value = "Tags to filter by") @RequestParam(value = "tags", required = false) List tags + +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -106,7 +114,9 @@ public class PetApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity getPetById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("petId") Long petId) + public ResponseEntity getPetById( +@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("petId") Long petId +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -119,13 +129,19 @@ public class PetApi { @ApiResponse(code = 405, message = "Invalid input") }) @RequestMapping(value = "/{petId}", produces = { "application/json", "application/xml" }, - consumes = { "application/x-www-form-urlencoded", }, + consumes = { "application/x-www-form-urlencoded" }, method = RequestMethod.POST) - public ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") String petId, + public ResponseEntity updatePetWithForm( +@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") String petId +, -@ApiParam(value = "Updated name of the pet" )@RequestPart("name") String name, + + +@ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, -@ApiParam(value = "Updated status of the pet" )@RequestPart("status") String status) + + +@ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -140,8 +156,12 @@ public class PetApi { produces = { "application/json", "application/xml" }, method = RequestMethod.DELETE) - public ResponseEntity deletePet(@ApiParam(value = "" )@RequestHeader("apiKey") String apiKey, - @ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId) + public ResponseEntity deletePet( +@ApiParam(value = "" ) @RequestHeader(value="apiKey", required=false) String apiKey +, + +@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -154,12 +174,18 @@ public class PetApi { @ApiResponse(code = 0, message = "successful operation") }) @RequestMapping(value = "/{petId}/uploadImage", produces = { "application/json", "application/xml" }, - consumes = { "multipart/form-data", }, + consumes = { "multipart/form-data" }, method = RequestMethod.POST) - public ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, + public ResponseEntity uploadFile( +@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId +, -@ApiParam(value = "Additional data to pass to server" )@RequestPart("additionalMetadata") String additionalMetadata, - @ApiParam(value = "file detail") @RequestPart("file") MultipartFile fileDetail) + + +@ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, + + +@ApiParam(value = "file detail") @RequestPart("file") MultipartFile fileDetail) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java index 4f3eb963e16..ba6e233ce9c 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java @@ -56,7 +56,9 @@ public class StoreApi { produces = { "application/json", "application/xml" }, method = RequestMethod.POST) - public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ) Order body) + public ResponseEntity placeOrder( + +@ApiParam(value = "order placed for purchasing the pet" ) Order body) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -73,7 +75,9 @@ public class StoreApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") String orderId) + public ResponseEntity getOrderById( +@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") String orderId +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -89,7 +93,9 @@ public class StoreApi { produces = { "application/json", "application/xml" }, method = RequestMethod.DELETE) - public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId) + public ResponseEntity deleteOrder( +@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java index 25671c6168d..15b170e90a7 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java @@ -40,7 +40,9 @@ public class UserApi { produces = { "application/json", "application/xml" }, method = RequestMethod.POST) - public ResponseEntity createUser(@ApiParam(value = "Created user object" ) User body) + public ResponseEntity createUser( + +@ApiParam(value = "Created user object" ) User body) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -55,7 +57,9 @@ public class UserApi { produces = { "application/json", "application/xml" }, method = RequestMethod.POST) - public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ) List body) + public ResponseEntity createUsersWithArrayInput( + +@ApiParam(value = "List of user object" ) List body) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -70,7 +74,9 @@ public class UserApi { produces = { "application/json", "application/xml" }, method = RequestMethod.POST) - public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ) List body) + public ResponseEntity createUsersWithListInput( + +@ApiParam(value = "List of user object" ) List body) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -86,8 +92,12 @@ public class UserApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity loginUser(@ApiParam(value = "The user name for login") @RequestParam(value = "username", required = false) String username, - @ApiParam(value = "The password for login in clear text") @RequestParam(value = "password", required = false) String password) + public ResponseEntity loginUser(@ApiParam(value = "The user name for login") @RequestParam(value = "username", required = false) String username + +, + @ApiParam(value = "The password for login in clear text") @RequestParam(value = "password", required = false) String password + +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -119,7 +129,9 @@ public class UserApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username) + public ResponseEntity getUserByName( +@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -135,8 +147,12 @@ public class UserApi { produces = { "application/json", "application/xml" }, method = RequestMethod.PUT) - public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, - @ApiParam(value = "Updated user object" ) User body) + public ResponseEntity updateUser( +@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username +, + + +@ApiParam(value = "Updated user object" ) User body) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -152,7 +168,9 @@ public class UserApi { produces = { "application/json", "application/xml" }, method = RequestMethod.DELETE) - public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username) + public ResponseEntity deleteUser( +@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK);