diff --git a/README.md b/README.md index fc140685e7f1..2f0b62d89dee 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Check out [Swagger-Spec](https://github.com/swagger-api/swagger-spec) for additi ## Compatability The Swagger Specification has undergone 3 revisions since initial creation in 2010. The swagger-codegen project has the following compatibilies with the swagger specification: -Swagger Codegen Version | Release Date | Swagger Spec compatability | Notes +Swagger Codegen Version | Release Date | Swagger Spec compatibility | Notes ----------------------- | ------------ | -------------------------- | ----- 2.1.3-M1-SNAPSHOT | 2015-02-23 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.0-M1](https://github.com/swagger-api/swagger-codegen) 2.0.17 | 2014-08-22 | 1.1, 1.2 | [tag v2.0.17](https://github.com/swagger-api/swagger-codegen/tree/v2.0.17) @@ -64,9 +64,9 @@ usage: Codegen -i,--input-spec location of the swagger spec, as URL or file -l,--lang client language to generate. Available languages include: - [android, java, jaxrs, nodejs, objc, scalatra, - scala, dynamic-html, html, swagger, tizen, php, - python] + [android, async-scala, java, jaxrs, nodejs, + objc, scalatra, scala, dynamic-html, html, + swagger, tizen, php, ruby, python] -o,--output where to write the generated files -t,--template-dir folder containing the template files ``` diff --git a/bin/nodejs-petstore-server.sh b/bin/nodejs-petstore-server.sh index c8492838ee36..53bedc84b4d3 100755 --- a/bin/nodejs-petstore-server.sh +++ b/bin/nodejs-petstore-server.sh @@ -33,4 +33,4 @@ fi export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l nodejs -o samples/server/petstore/nodejs" -java $JAVA_OPTS -jar $executable $ags +java $JAVA_OPTS -Dservice -jar $executable $ags 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 69db1b9d2da0..86ff0f166500 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 @@ -26,6 +26,7 @@ public interface CodegenConfig { String getTypeDeclaration(Property p); String getTypeDeclaration(String name); void processOpts(); + String generateExamplePath(String path, Operation operation); Set reservedWords(); @@ -35,7 +36,7 @@ public interface CodegenConfig { String getOutputDir(); CodegenModel fromModel(String name, Model model); - CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation); + CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions); List fromSecurity(Map schemes); Set defaultIncludes(); diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java index 12b405edeb46..7f8d390f371e 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java @@ -6,7 +6,8 @@ import java.util.*; public class CodegenOperation { public Boolean hasConsumes, hasProduces, hasParams, returnTypeIsPrimitive, - returnSimpleType, subresourceOperation, isMapContainer, isListContainer; + returnSimpleType, subresourceOperation, isMapContainer, isListContainer, + hasMore = Boolean.TRUE; public String path, operationId, returnType, httpMethod, returnBaseType, returnContainer, summary, notes, baseName, defaultResponse; 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 4480c172c322..04cecabad904 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 @@ -4,6 +4,8 @@ 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 jsonSchema; + /** * Determines whether this parameter is mandatory. If the parameter is in "path", * this property is required and its value MUST be true. Otherwise, the property @@ -31,6 +33,7 @@ public class CodegenParameter { output.isCookieParam = this.isCookieParam; output.isBodyParam = this.isBodyParam; output.required = this.required; + output.jsonSchema = this.jsonSchema; return output; } 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 c5ea8a0da4d3..b00c962ba6b0 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 @@ -15,6 +15,7 @@ public class CodegenProperty { /** A free-form property to include an example of an instance for this schema. */ public String example; + public String jsonSchema; public Double minimum, maximum, exclusiveMinimum, exclusiveMaximum; public Boolean hasMore = null, required = null, secondaryParam = null; public Boolean isPrimitiveType, isContainer, isNotContainer; 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 d940e4922eb1..15931c9fd271 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 @@ -6,10 +6,12 @@ public class CodegenResponse { public String code, message; public Boolean hasMore; public List> examples; + public final List headers = new ArrayList(); public String dataType, baseType, containerType; public Boolean simpleType; public Boolean primitiveType; public Boolean isMapContainer; public Boolean isListContainer; - Object schema; + public Object schema; + public String jsonSchema; } \ No newline at end of file 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 33dd02286918..a51f7c4f2ec0 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,5 +1,6 @@ package com.wordnik.swagger.codegen; +import com.wordnik.swagger.codegen.examples.ExampleGenerator; import com.wordnik.swagger.models.*; import com.wordnik.swagger.models.auth.ApiKeyAuthDefinition; import com.wordnik.swagger.models.auth.BasicAuthDefinition; @@ -8,7 +9,9 @@ import com.wordnik.swagger.models.auth.SecuritySchemeDefinition; import com.wordnik.swagger.models.parameters.*; import com.wordnik.swagger.models.properties.*; import com.wordnik.swagger.util.Json; + import org.apache.commons.lang.StringUtils; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -141,7 +144,7 @@ public class DefaultCodegen { } public String toModelFilename(String name) { - return name; + return initialCaps(name); } public String toOperationId(String operationId) { return operationId; } @@ -233,6 +236,55 @@ public class DefaultCodegen { importMapping.put("LocalTime", "org.joda.time.*"); } + + public String generateExamplePath(String path, Operation operation) { + StringBuilder sb = new StringBuilder(); + sb.append(path); + + if(operation.getParameters() != null) { + int count = 0; + + for(Parameter param : operation.getParameters()) { + if(param instanceof QueryParameter) { + StringBuilder paramPart = new StringBuilder(); + QueryParameter qp = (QueryParameter) param; + + if(count == 0) + paramPart.append("?"); + else + paramPart.append(","); + count += 1; + if(!param.getRequired()) + paramPart.append("["); + paramPart.append(param.getName()).append("="); + paramPart.append("{"); + if(qp.getCollectionFormat() != null) { + paramPart.append(param.getName() + "1"); + if("csv".equals(qp.getCollectionFormat())) + paramPart.append(","); + else if("pipes".equals(qp.getCollectionFormat())) + paramPart.append("|"); + else if("tsv".equals(qp.getCollectionFormat())) + paramPart.append("\t"); + else if("multi".equals(qp.getCollectionFormat())) { + paramPart.append("&").append(param.getName()).append("="); + paramPart.append(param.getName() + "2"); + } + } + else { + paramPart.append(param.getName()); + } + paramPart.append("}"); + if(!param.getRequired()) + paramPart.append("]"); + sb.append(paramPart.toString()); + } + } + } + + return sb.toString(); + } + public String toInstantiationType(Property p) { if (p instanceof MapProperty) { MapProperty ap = (MapProperty) p; @@ -317,7 +369,7 @@ public class DefaultCodegen { } public String snakeCase(String name) { - return Character.toLowerCase(name.charAt(0)) + name.substring(1); + return (name.length() > 0) ? (Character.toLowerCase(name.charAt(0)) + name.substring(1)) : ""; } public String initialCaps(String name) { @@ -479,9 +531,9 @@ public class DefaultCodegen { property.setter = "set" + getterAndSetterCapitalize(name); property.example = p.getExample(); property.defaultValue = toDefaultValue(p); + property.jsonSchema = Json.pretty(p); String type = getSwaggerType(p); - if(p instanceof AbstractNumericProperty) { AbstractNumericProperty np = (AbstractNumericProperty) p; property.minimum = np.getMinimum(); @@ -554,14 +606,18 @@ public class DefaultCodegen { property.isPrimitiveType = true; } else { - property.isNotContainer = true; + setNonArrayMapProperty(property, type); + } + return property; + } + + protected void setNonArrayMapProperty(CodegenProperty property, String type) { + property.isNotContainer = true; if(languageSpecificPrimitives().contains(type)) property.isPrimitiveType = true; else property.complexType = property.baseType; } - return property; - } private Response findMethodResponse(Map responses) { @@ -578,7 +634,7 @@ public class DefaultCodegen { return responses.get(code); } - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation){ + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION); Set imports = new HashSet(); @@ -621,6 +677,8 @@ public class DefaultCodegen { count += 1; if (count < operation.getConsumes().size()) mediaType.put("hasMore", "true"); + else + mediaType.put("hasMore", null); c.add(mediaType); } op.consumes = c; @@ -636,6 +694,8 @@ public class DefaultCodegen { count += 1; if (count < operation.getProduces().size()) mediaType.put("hasMore", "true"); + else + mediaType.put("hasMore", null); c.add(mediaType); } op.produces = c; @@ -643,7 +703,6 @@ public class DefaultCodegen { } if (operation.getResponses() != null && !operation.getResponses().isEmpty()) { - Response methodResponse = findMethodResponse(operation.getResponses()); CodegenResponse methodCodegenResponse = null; @@ -662,24 +721,40 @@ public class DefaultCodegen { } op.responses.get(op.responses.size() - 1).hasMore = false; - if (methodResponse != null) { - op.returnType = methodCodegenResponse.dataType; - op.returnBaseType = methodCodegenResponse.baseType; - op.returnSimpleType = methodCodegenResponse.simpleType; - op.returnTypeIsPrimitive = methodCodegenResponse.primitiveType; - op.returnContainer = methodCodegenResponse.containerType; - op.isListContainer = methodCodegenResponse.isListContainer; - op.isMapContainer = methodCodegenResponse.isMapContainer; - if (methodResponse.getSchema() != null) { - Property responseProperty = methodResponse.getSchema(); - responseProperty.setRequired(true); - CodegenProperty cm = fromProperty("response", responseProperty); - op.examples = toExamples(methodResponse.getExamples()); - op.defaultResponse = toDefaultValue(responseProperty); - addHeaders(methodResponse, op.responseHeaders); - } + if(methodResponse != null) { + if (methodResponse.getSchema() != null) { + CodegenProperty cm = fromProperty("response", methodResponse.getSchema()); + Property responseProperty = methodResponse.getSchema(); + + if(responseProperty instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) responseProperty; + CodegenProperty innerProperty = fromProperty("response", ap.getItems()); + op.returnBaseType = innerProperty.baseType; + } + else { + if(cm.complexType != null) + op.returnBaseType = cm.complexType; + else + op.returnBaseType = cm.baseType; + } + op.examples = new ExampleGenerator(definitions).generate(methodResponse.getExamples(), operation.getProduces(), responseProperty); + op.defaultResponse = toDefaultValue(responseProperty); + op.returnType = cm.datatype; + if(cm.isContainer != null) { + op.returnContainer = cm.containerType; + if("map".equals(cm.containerType)) + op.isMapContainer = Boolean.TRUE; + else if ("list".equalsIgnoreCase(cm.containerType)) + op.isListContainer = Boolean.TRUE; + } + else + op.returnSimpleType = true; + if (languageSpecificPrimitives().contains(op.returnBaseType) || op.returnBaseType == null) + op.returnTypeIsPrimitive = true; } + addHeaders(methodResponse, op.responseHeaders); + } } List parameters = operation.getParameters(); @@ -761,6 +836,8 @@ public class DefaultCodegen { r.message = response.getDescription(); r.schema = response.getSchema(); r.examples = toExamples(response.getExamples()); + r.jsonSchema = Json.pretty(response); + addHeaders(response, r.headers); if (r.schema != null) { Property responseProperty = response.getSchema(); @@ -803,6 +880,7 @@ public class DefaultCodegen { p.baseName = param.getName(); p.description = param.getDescription(); p.required = param.getRequired(); + p.jsonSchema = Json.pretty(param); if(param instanceof SerializableParameter) { SerializableParameter qp = (SerializableParameter) param; 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 01fb25423a48..f8523163e57c 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 @@ -56,6 +56,9 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { if(license.getUrl() != null) config.additionalProperties().put("licenseUrl", license.getUrl()); } + if(info.getVersion() != null) { + config.additionalProperties().put("version", info.getVersion()); + } } StringBuilder hostBuilder = new StringBuilder(); @@ -65,8 +68,15 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } else hostBuilder.append("https://"); - hostBuilder.append(swagger.getHost()).append(swagger.getBasePath()); - String contextPath = swagger.getBasePath(); + if(swagger.getHost() != null) + hostBuilder.append(swagger.getHost()); + else + hostBuilder.append("localhost"); + if(swagger.getBasePath() != null) + hostBuilder.append(swagger.getBasePath()); + else + hostBuilder.append("/"); + String contextPath = swagger.getBasePath() == null ? "/" : swagger.getBasePath(); String basePath = hostBuilder.toString(); @@ -119,7 +129,14 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { operation.putAll(config.additionalProperties()); operation.put("classname", config.toApiName(tag)); operation.put("classVarName", config.toApiVarName(tag)); - allOperations.add(operation); + + allOperations.add(new HashMap(operation)); + for(int i = 0; i < allOperations.size(); i++) { + Map oo = (Map) allOperations.get(i); + if(i < (allOperations.size() -1)) + oo.put("hasMore", "true"); + } + for(String templateName : config.apiTemplateFiles().keySet()) { String suffix = config.apiTemplateFiles().get(templateName); String filename = config.apiFileFolder() + @@ -153,9 +170,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { Map apis = new HashMap(); apis.put("apis", allOperations); - if(swagger.getBasePath() != null) { - bundle.put("basePath", basePath); + if(swagger.getHost() != null) { + bundle.put("host", swagger.getHost()); } + bundle.put("basePath", basePath); + bundle.put("contextPath", contextPath); bundle.put("apiInfo", apis); bundle.put("models", allModels); bundle.put("apiFolder", config.apiPackage().replace('.', File.separatorChar)); @@ -252,7 +271,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } for (String tag : tags) { - CodegenOperation co = config.fromOperation(resourcePath, httpMethod, operation); + CodegenOperation co = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions()); co.tags = new ArrayList(); co.tags.add(sanitizeTag(tag)); config.addOperationToGroup(sanitizeTag(tag), resourcePath, operation, co, operations); @@ -319,6 +338,14 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { operations.put("imports", imports); config.postProcessOperations(operations); + if(objs.size() > 0) { + List os = (List) objs.get("operation"); + + if(os != null && os.size() > 0) { + CodegenOperation op = os.get(os.size() - 1); + op.hasMore = null; + } + } return operations; } 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 new file mode 100644 index 000000000000..c03f15a1466b --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/ExampleGenerator.java @@ -0,0 +1,157 @@ +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.*; + +public class ExampleGenerator { + protected Map examples; + + public ExampleGenerator(Map examples) { + this.examples = examples; + } + + public List> generate(Map examples, List mediaTypes, Property property) { + List> output = new ArrayList>(); + if(examples == null ) { + if(mediaTypes == null) { + // assume application/json for this + mediaTypes = Arrays.asList("application/json"); + } + for(String mediaType : mediaTypes) { + Map kv = new HashMap(); + kv.put("contentType", mediaType); + if(property != null && mediaType.startsWith("application/json")) { + String example = Json.pretty(resolvePropertyToExample(mediaType, property)); + + if(example != null) { + example = example.replaceAll("\n", "\\\\n"); + kv.put("example", example); + output.add(kv); + } + } + 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); + } + } + } + } + else { + for(String key: examples.keySet()) { + String value = examples.get(key); + + Map kv = new HashMap(); + kv.put("contentType", key); + kv.put("example", value); + output.add(kv); + } + } + if(output.size() == 0) { + Map kv = new HashMap(); + kv.put("output", "none"); + output.add(kv); + } + return output; + } + + protected Object resolvePropertyToExample(String mediaType, Property property) { + if(property.getExample() != null) { + return property.getExample(); + } + else if(property instanceof StringProperty) { + return "aeiou"; + } + else if(property instanceof BooleanProperty) { + return Boolean.TRUE; + } + else if(property instanceof ArrayProperty) { + Property innerType = ((ArrayProperty)property).getItems(); + if(innerType != null) { + Object[] output = new Object[]{ + resolvePropertyToExample(mediaType, innerType) + }; + return output; + } + } + else if(property instanceof DateProperty) { + return new java.util.Date(System.currentTimeMillis()); + } + else if(property instanceof DateTimeProperty) { + return new java.util.Date(System.currentTimeMillis()); + } + else if(property instanceof DecimalProperty) { + return new BigDecimal(1.3579); + } + else if(property instanceof DoubleProperty) { + return new Double(3.149); + } + else if(property instanceof FileProperty) { + return ""; // TODO + } + else if(property instanceof FloatProperty) { + return new Float(1.23); + } + else if(property instanceof IntegerProperty) { + return new Integer(123); + } + else if(property instanceof LongProperty) { + return new Long(123456789); + } + else if(property instanceof MapProperty) { + Map mp = new HashMap(); + if(property.getName() != null) { + mp.put(property.getName(), + resolvePropertyToExample(mediaType, ((MapProperty)property).getAdditionalProperties())); + } + else { + mp.put("key", + resolvePropertyToExample(mediaType, ((MapProperty)property).getAdditionalProperties())); + } + return mp; + } + else if(property instanceof ObjectProperty) { + return "{}"; + } + else if(property instanceof RefProperty) { + Model model = examples.get(((RefProperty)property).getSimpleRef()); + if(model != null) + return resolveModelToExample(mediaType, model); + } + else if(property instanceof UUIDProperty) { + return "046b6c7f-0b8a-43b9-b35d-6489e6daee91"; + } + + return ""; + } + + public Object resolveModelToExample(String mediaType, Model model) { + if(model instanceof ModelImpl) { + ModelImpl impl = (ModelImpl) model; + Map values = new HashMap(); + + for(String name : impl.getProperties().keySet()) { + Property property = impl.getProperties().get(name); + values.put(name, resolvePropertyToExample(mediaType, property)); + } + + return values; + } + + return ""; + } +} \ No newline at end of file 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 new file mode 100644 index 000000000000..40df89507e39 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/XmlExampleGenerator.java @@ -0,0 +1,188 @@ +package com.wordnik.swagger.codegen.examples; + + +import com.wordnik.swagger.util.Json; +import com.wordnik.swagger.models.*; +import com.wordnik.swagger.models.properties.*; + +import java.text.SimpleDateFormat; +import java.util.*; + +public class XmlExampleGenerator { + public static String NEWLINE = "\n"; + public static String TAG_START = "<"; + public static String CLOSE_TAG = ">"; + public static String TAG_END = " 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'"); + + public XmlExampleGenerator(Map examples) { + this.examples = examples; + if(examples == null) + examples = new HashMap(); + } + + public String toXml(Property property) { + return toXml(null, property, 0); + } + + protected String toXml(Model model, int indent) { + if(model instanceof RefModel) { + RefModel ref = (RefModel) model; + Model actualModel = examples.get(ref.getSimpleRef()); + if(actualModel instanceof ModelImpl) + return modelImplToXml((ModelImpl)actualModel, indent); + } + else if(model instanceof ModelImpl) { + return modelImplToXml((ModelImpl)model, indent); + } + return null; + } + + protected String modelImplToXml(ModelImpl model, int indent) { + StringBuilder sb = new StringBuilder(); + // attributes + Map attributes = new LinkedHashMap(); + Map elements = new LinkedHashMap(); + + String name = model.getName(); + String namespace; + String prefix; + Boolean wrapped; + + Xml xml = model.getXml(); + if(xml != null) { + if(xml.getName() != null) + name = xml.getName(); + } + for(String pName : model.getProperties().keySet()) { + Property p = model.getProperties().get(pName); + if(p != null && p.getXml() != null && p.getXml().getAttribute() != null && p.getXml().getAttribute()) + attributes.put(pName, p); + else + elements.put(pName, p); + } + sb.append(indent(indent)).append(TAG_START); + 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(CLOSE_TAG); + sb.append(NEWLINE); + for(String pName : elements.keySet()) { + Property p = elements.get(pName); + sb.append(toXml(pName, p, indent + 1)); + sb.append(NEWLINE); + } + sb.append(indent(indent)).append(TAG_END).append(name).append(CLOSE_TAG); + + return sb.toString(); + } + + protected String quote(String string) { + return "\"" + string + "\""; + } + + protected String toXml(String name, Property property, int indent) { + if(property == null) { + return ""; + } + StringBuilder sb = new StringBuilder(); + + if(property instanceof ArrayProperty) { + ArrayProperty p = (ArrayProperty) property; + Property inner = p.getItems(); + boolean wrapped = false; + if(property.getXml() != null && property.getXml().getWrapped()) + wrapped = true; + if(wrapped) { + if(name != null) { + sb.append(indent(indent)); + sb.append(openTag(name)); + sb.append(NEWLINE); + } + sb.append(toXml(name, inner, indent + 1)); + if(name != null) { + sb.append(NEWLINE); + sb.append(indent(indent)); + sb.append(closeTag(name)); + } + } + else + sb.append(toXml(name, inner, indent)); + } + else if(property instanceof RefProperty) { + RefProperty ref = (RefProperty) property; + Model actualModel = examples.get(ref.getSimpleRef()); + sb.append(toXml(actualModel, indent)); + } + else { + if(name != null) { + sb.append(indent(indent)); + sb.append(openTag(name)); + } + sb.append(getExample(property)); + if(name != null) + sb.append(closeTag(name)); + } + return sb.toString(); + } + + protected String getExample(Property property) { + if(property instanceof DateTimeProperty) { + if(property.getExample() != null) + return property.getExample(); + else + return dtFormat.format(new Date()); + } + else if(property instanceof StringProperty) { + if(property.getExample() != null) + return property.getExample(); + else + return "string"; + } + else if(property instanceof DateProperty) { + if(property.getExample() != null) + return property.getExample(); + else + return dateFormat.format(new Date()); + } + else if(property instanceof IntegerProperty) { + if(property.getExample() != null) + return property.getExample(); + else + return "0"; + } + else if(property instanceof BooleanProperty) { + if(property.getExample() != null) + return property.getExample(); + else + return "true"; + } + else if(property instanceof LongProperty) { + if(property.getExample() != null) + return property.getExample(); + else + return "123456"; + } + return "not implemented " + property; + } + + protected String openTag(String name) { + return "<" + name + ">"; + } + + protected String closeTag(String name) { + return ""; + } + + protected String indent(int indent) { + StringBuffer sb = new StringBuffer(); + for(int i = 0; i < indent; i++) { + sb.append(" "); + } + return sb.toString(); + } +} \ 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 74632b622fc3..0c6e6067607a 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,110 +1,192 @@ package com.wordnik.swagger.codegen.languages; import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.Model; -import com.wordnik.swagger.models.properties.*; import com.wordnik.swagger.util.Json; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.*; +import com.wordnik.swagger.models.properties.*; import java.util.*; import java.io.File; public class NodeJSServerCodegen 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 apiVersion = "1.0.0"; + protected int serverPort = 8080; + protected String projectName = "swagger-server"; + public String apiPackage() { + return "controllers"; + } + + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see com.wordnik.swagger.codegen.CodegenType + */ public CodegenType getTag() { return CodegenType.SERVER; } + /** + * Configures a friendly name for the generator. This will be used by the generator + * to select the library with the -l flag. + * + * @return the friendly name for the generator + */ public String getName() { return "nodejs"; } + /** + * Returns human-friendly help for the generator. Provide the consumer with help + * tips, parameters here + * + * @return A string value for the help message + */ public String getHelp() { - return "Generates a node.js server application compatible with the 1.2 swagger specification."; + return "Generates a nodejs server library using the swagger-tools project. By default, " + + "it will also generate service classes--which you can disable with the `-Dnoservice` environment variable."; } public NodeJSServerCodegen() { super(); + + // set the output folder here outputFolder = "generated-code/nodejs"; - apiTemplateFiles.put("api.mustache", ".js"); + + /** + * Models. You can write model files using the modelTemplateFiles map. + * if you want to create one template for file, you can do so here. + * for multiple files for model, just put another entry in the `modelTemplateFiles` with + * a different extension + */ + modelTemplateFiles.clear(); + + /** + * Api classes. You can write classes for each Api file with the apiTemplateFiles map. + * as with models, add multiple entries with different extensions for multiple files per + * class + */ + apiTemplateFiles.put( + "controller.mustache", // the template to use + ".js"); // the extension for each file to write + + /** + * Template Location. This is the location which templates will be read from. The generator + * will use the resource stream to attempt to read the templates. + */ templateDir = "nodejs"; - apiPackage = "app.apis"; - modelPackage = "app"; - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); - - supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); - supportingFiles.add(new SupportingFile("models.mustache", modelPackage, "models.js")); - supportingFiles.add(new SupportingFile("main.mustache", "", "main.js")); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - - languageSpecificPrimitives = new HashSet( + /** + * Reserved words. Override this with reserved words specific to your language + */ + reservedWords = new HashSet ( Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float") - ); - typeMapping.put("array", "array"); + "break", "case", "class", "catch", "const", "continue", "debugger", + "default", "delete", "do", "else", "export", "extends", "finally", + "for", "function", "if", "import", "in", "instanceof", "let", "new", + "return", "super", "switch", "this", "throw", "try", "typeof", "var", + "void", "while", "with", "yield") + ); + + /** + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ + additionalProperties.put("apiVersion", apiVersion); + additionalProperties.put("serverPort", serverPort); + + /** + * Supporting Files. You can write single files for the generator with the + * entire object tree available. If the input file has a suffix of `.mustache + * it will be processed by the template engine. Otherwise, it will be copied + */ + // supportingFiles.add(new SupportingFile("controller.mustache", + // "controllers", + // "controller.js") + // ); + supportingFiles.add(new SupportingFile("swagger.mustache", + "api", + "swagger.json") + ); + supportingFiles.add(new SupportingFile("index.mustache", + "", + "index.js") + ); + supportingFiles.add(new SupportingFile("package.mustache", + "", + "package.json") + ); + if(System.getProperty("noservice") == null) { + apiTemplateFiles.put( + "service.mustache", // the template to use + "Service.js"); // the extension for each file to write + } } + @Override + public String toApiName(String name) { + if(name.length() == 0) + return "DefaultController"; + return initialCaps(name); + } + + @Override + public String toApiFilename(String name) { + return toApiName(name); + } + /** + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping + * those terms here. This logic is only called if a variable matches the reseved words + * + * @return the escaped term + */ @Override public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public Map postProcessSupportingFileData(Map objs) { - List> o = (List>)objs.get("models"); - - for(Map modelMap : o) { - try { - CodegenModel m = (CodegenModel) modelMap.get("model"); - ObjectNode on = (ObjectNode) Json.mapper().readTree(m.modelJson); - // inject the id field - on.put("id", m.name); - - // remove the definitions qualifier with this nasty hack - m.modelJson = Json.pretty(on).replaceAll("\"#/definitions/", "\""); - } - catch (Exception e) { - e.printStackTrace(); - // skip conversion - } - } - return objs; + return "_" + name; // add an underscore to the name } + /** + * Location to write api files. You can use the apiPackage() as defined when the class is + * instantiated + */ @Override public String apiFileFolder() { return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); } - public String modelFileFolder() { - return outputFolder + File.separator + modelPackage().replace('.', File.separatorChar); - } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if(typeMapping.containsKey(swaggerType)) { - return typeMapping.get(swaggerType); + public Map postProcessOperations(Map objs) { + Map objectMap = (Map)objs.get("operations"); + List operations = (List)objectMap.get("operation"); + for(CodegenOperation operation : operations) { + operation.httpMethod = operation.httpMethod.toLowerCase(); + List params = operation.allParams; + if(params != null && params.size() == 0) + operation.allParams = null; + List responses = operation.responses; + if(responses != null) { + for(CodegenResponse resp : responses) { + if("0".equals(resp.code)) + 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); + } + } + else + examples.remove(i); + } + } } - else - type = swaggerType; - return toModelName(type); + return objs; } } \ No newline at end of file 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 f82e863d9944..62f22ee2f44a 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 @@ -168,7 +168,18 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { } } - @Override + @Override + protected void setNonArrayMapProperty(CodegenProperty property, String type) { + super.setNonArrayMapProperty(property, type); + if("NSDictionary".equals(type)) { + property.setter = "initWithDictionary"; + } + else { + property.setter = "initWithValues"; + } + } + + @Override public String toModelImport(String name) { if("".equals(modelPackage())) return name; diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ScalaClientCodegen.java index 85eeee98b9e8..ffef50b76e44 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ScalaClientCodegen.java @@ -11,7 +11,7 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig protected String groupId = "com.wordnik"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/java"; + protected String sourceFolder = "src/main/scala"; protected String authScheme = ""; protected boolean authPreemptive = false; protected boolean asyncHttpClient = !authScheme.isEmpty(); diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwaggerGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwaggerGenerator.java index 8ad75ae3e211..c0560e2a1bc5 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwaggerGenerator.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwaggerGenerator.java @@ -23,7 +23,10 @@ public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig { public SwaggerGenerator() { super(); + templateDir = "swagger"; outputFolder = "generated-code/swagger"; + + supportingFiles.add(new SupportingFile("README.md", "", "README.md")); } @Override diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwaggerYamlGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwaggerYamlGenerator.java new file mode 100644 index 000000000000..7c65168546f9 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwaggerYamlGenerator.java @@ -0,0 +1,44 @@ +package com.wordnik.swagger.codegen.languages; + +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.util.*; +import com.wordnik.swagger.models.Swagger; + +import org.apache.commons.io.FileUtils; + +import java.io.File; + +public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfig { + public CodegenType getTag() { + return CodegenType.DOCUMENTATION; + } + + public String getName() { + return "swagger-yaml"; + } + + public String getHelp() { + return "Creates a static swagger.yaml file."; + } + + public SwaggerYamlGenerator() { + super(); + templateDir = "swagger"; + outputFolder = "generated-code/swagger"; + + supportingFiles.add(new SupportingFile("README.md", "", "README.md")); + } + + @Override + public void processSwagger(Swagger swagger) { + try{ + String swaggerString = Yaml.mapper().writeValueAsString(swagger); + String outputFile = outputFolder + File.separator + "swagger.yaml"; + FileUtils.writeStringToFile(new File(outputFile), swaggerString); + System.out.println("wrote file to " + outputFile); + } + catch(Exception e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 4a1ab1dc77b1..ad26268d7156 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -59,9 +59,9 @@ public class {{classname}} { Map formParams = new HashMap(); {{#queryParams}}if ({{paramName}} != null) - queryParams.put("{{baseName}}", String.valueOf({{paramName}})); + queryParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}})); {{/queryParams}} - {{#headerParams}}headerParams.put("{{baseName}}", {{paramName}}); + {{#headerParams}}headerParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}})); {{/headerParams}} String[] contentTypes = { {{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}} @@ -74,7 +74,7 @@ public class {{classname}} { FormDataMultiPart mp = new FormDataMultiPart(); {{#formParams}}{{#notFile}} hasFields = true; - mp.field("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE); + mp.field("{{baseName}}", ApiInvoker.parameterToString({{paramName}}), MediaType.MULTIPART_FORM_DATA_TYPE); {{/notFile}}{{#isFile}} hasFields = true; mp.field("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -83,7 +83,7 @@ public class {{classname}} { postBody = mp; } else { - {{#formParams}}{{#notFile}}formParams.put("{{baseName}}", {{paramName}});{{/notFile}} + {{#formParams}}{{#notFile}}formParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));{{/notFile}} {{/formParams}} } diff --git a/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache index 26379c601058..cc77f01a9a6e 100644 --- a/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache @@ -19,16 +19,75 @@ import javax.ws.rs.core.MediaType; import java.util.Map; import java.util.HashMap; import java.util.List; -import java.io.IOException; +import java.util.Date; +import java.util.TimeZone; + import java.net.URLEncoder; + +import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.text.SimpleDateFormat; +import java.text.ParseException; + public class ApiInvoker { private static ApiInvoker INSTANCE = new ApiInvoker(); private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); private boolean isDebug = false; + /** + * ISO 8601 date time format. + * @see https://en.wikipedia.org/wiki/ISO_8601 + */ + public static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + + /** + * ISO 8601 date format. + * @see https://en.wikipedia.org/wiki/ISO_8601 + */ + public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); + + static { + // Use UTC as the default time zone. + DATE_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); + DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); + } + + public static Date parseDateTime(String str) { + try { + return DATE_TIME_FORMAT.parse(str); + } catch (java.text.ParseException e) { + throw new RuntimeException(e); + } + } + + public static Date parseDate(String str) { + try { + return DATE_FORMAT.parse(str); + } catch (java.text.ParseException e) { + throw new RuntimeException(e); + } + } + + public static String formatDateTime(Date datetime) { + return DATE_TIME_FORMAT.format(datetime); + } + + public static String formatDate(Date date) { + return DATE_FORMAT.format(date); + } + + public static String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDateTime((Date) param); + } else { + return String.valueOf(param); + } + } + public void enableDebug() { isDebug = true; } @@ -106,12 +165,12 @@ public class ApiInvoker { Builder builder = client.resource(host + path + querystring).accept("application/json"); for(String key : headerParams.keySet()) { - builder.header(key, headerParams.get(key)); + builder = builder.header(key, headerParams.get(key)); } for(String key : defaultHeaderMap.keySet()) { if(!headerParams.containsKey(key)) { - builder.header(key, defaultHeaderMap.get(key)); + builder = builder.header(key, defaultHeaderMap.get(key)); } } ClientResponse response = null; 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 64298e10a6fc..8303425734df 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 @@ -10,6 +10,7 @@ com.wordnik.swagger.codegen.languages.ScalaClientCodegen com.wordnik.swagger.codegen.languages.StaticDocCodegen com.wordnik.swagger.codegen.languages.StaticHtmlGenerator com.wordnik.swagger.codegen.languages.SwaggerGenerator +com.wordnik.swagger.codegen.languages.SwaggerYamlGenerator com.wordnik.swagger.codegen.languages.TizenClientCodegen com.wordnik.swagger.codegen.languages.PhpClientCodegen com.wordnik.swagger.codegen.languages.RubyClientCodegen diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache index ccd35c8723dc..dd2a573d751a 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache @@ -9,6 +9,7 @@
{{{appDescription}}} for {{partner}}
{{#infoUrl}}
More information: {{{infoUrl}}}
{{/infoUrl}} {{#infoEmail}}
Contact Info: {{{infoEmail}}}
{{/infoEmail}} + {{#version}}
Version: {{{version}}}
{{/version}}
{{{licenseInfo}}}
{{{licenseUrl}}}

Access

diff --git a/modules/swagger-codegen/src/main/resources/nodejs/README.mustache b/modules/swagger-codegen/src/main/resources/nodejs/README.mustache index ac6dc37d3dc0..a8da1d0a9ea3 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/README.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/README.mustache @@ -5,4 +5,20 @@ This server was generated by the [swagger-codegen](https://github.com/swagger-ap This example uses the [expressjs](http://expressjs.com/) framework. To see how to make this your own, look here: -[README](https://github.com/wordnik/swagger-codegen/README.md) \ No newline at end of file +[README](https://github.com/wordnik/swagger-codegen/README.md) + +### Running the server +To run the server, follow these simple steps: + +``` +npm install +node . +``` + +To view the Swagger UI interface: + +``` +open http://localhost:8080/docs +``` + +This project leverages the mega-awesome [swagger-tools](https://github.com/apigee-127/swagger-tools) middleware which does most all the work. \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/nodejs/api.mustache b/modules/swagger-codegen/src/main/resources/nodejs/api.mustache deleted file mode 100644 index e2f94f7a5566..000000000000 --- a/modules/swagger-codegen/src/main/resources/nodejs/api.mustache +++ /dev/null @@ -1,62 +0,0 @@ -var swagger = require("swagger-node-express"); -var url = require("url"); -var errors = swagger.errors; -var params = swagger.params; - -/* add model includes */ - -function writeResponse (response, data) { - response.header('Access-Control-Allow-Origin', "*"); - response.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); - response.header("Access-Control-Allow-Headers", "Content-Type"); - response.header("Content-Type", "application/json; charset=utf-8"); - response.send(JSON.stringify(data)); -} - -exports.models = models = require("../models.js"); - -{{#operations}} -{{#operation}} -exports.{{nickname}} = { - 'spec': { - "description" : "the {{baseName}} API", - "path" : "{{path}}", - "notes" : "{{{notes}}}", - "summary" : "{{{summary}}}", - "method": "{{httpMethod}}", - "params" : [{{#queryParams}} - params.query("{{paramName}}", "{{description}}", "{{swaggerDataType}}", {{#required}}true{{/required}}{{^required}}false{{/required}}, {{#allowMultiple}}true{{/allowMultiple}}{{^allowMultiple}}false{{/allowMultiple}}, "{{{allowableValues}}}"{{#defaultValue}}, {{{defaultValue}}}{{/defaultValue}}){{#hasMore}},{{/hasMore}} - {{/queryParams}}].concat([{{#pathParams}} - params.path("{{paramName}}", "{{description}}"){{#hasMore}},{{/hasMore}} - {{/pathParams}}]).concat([{{#headerParams}} - params.header("{{paramName}}", "{{description}}"){{#hasMore}},{{/hasMore}} - {{/headerParams}}]).concat([{{#bodyParams}} - params.body("body", "{{swaggerDataType}}", "{{description}}", {{#required}}{{required}}{{/required}}{{^required}}false{{/required}}) - {{/bodyParams}}]), - {{#returnContainer}} - "type": "{{returnType}}", - "items": { - {{#returnTypeIsPrimitive}}"type": "{{returnContainer}}"{{/returnTypeIsPrimitive}} - {{^returnTypeIsPrimitive}}"$ref": "{{returnContainer}}"{{/returnTypeIsPrimitive}} - }, - // container - {{/returnContainer}} - {{^returnContainer}} - "type" : "{{returnType}}", - {{/returnContainer}} - "responseMessages" : [errors.invalid('id'), errors.notFound('{{returnType}}')], - "nickname" : "{{nickname}}" - }, - 'action': function (req,res) { - {{#requiredParamCount}} - {{#requiredParams}} - if (!req.params.{{baseName}}) { - throw errors.invalid('{{baseName}}'); - } - {{/requiredParams}} - {{/requiredParamCount}} - writeResponse(res, {message: "how about implementing {{nickname}} as a {{httpMethod}} method?"}); - } -}; -{{/operation}} -{{/operations}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/nodejs/controller.mustache b/modules/swagger-codegen/src/main/resources/nodejs/controller.mustache new file mode 100644 index 000000000000..85d1f3211a13 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/nodejs/controller.mustache @@ -0,0 +1,25 @@ +'use strict'; + +var url = require('url'); + +{{#operations}} + +var {{classname}} = require('./{{classname}}Service'); + +{{#operation}} + +module.exports.{{nickname}} = function {{nickname}} (req, res, next) { + {{#allParams}}var {{paramName}} = req.swagger.params['{{baseName}}'].value; + {{/allParams}} + + var result = {{classname}}.{{nickname}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; +{{/operation}} +{{/operations}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/nodejs/index.mustache b/modules/swagger-codegen/src/main/resources/nodejs/index.mustache new file mode 100644 index 000000000000..0562c2f0c376 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/nodejs/index.mustache @@ -0,0 +1,38 @@ +'use strict'; + +var app = require('connect')(); +var http = require('http'); +var swaggerTools = require('swagger-tools'); + +var serverPort = {{serverPort}}; + +// swaggerRouter configuration +var options = { + swaggerUi: '/swagger.json', + controllers: './controllers', + useStubs: process.env.NODE_ENV === 'development' ? true : false // Conditionally turn on stubs (mock mode) +}; + +// The Swagger document (require it, build it programmatically, fetch it from a URL, ...) +var swaggerDoc = require('./api/swagger.json'); + +// Initialize the Swagger middleware +swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) { + // Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain + app.use(middleware.swaggerMetadata()); + + // Validate Swagger requests + app.use(middleware.swaggerValidator()); + + // Route validated requests to appropriate controller + app.use(middleware.swaggerRouter(options)); + + // Serve the Swagger documents and Swagger UI + app.use(middleware.swaggerUi()); + + // Start the server + http.createServer(app).listen({{serverPort}}, function () { + console.log('Your server is listening on port %d (http://localhost:%d)', {{serverPort}}, {{serverPort}}); + console.log('Swagger-ui is available on http://localhost:%d/docs', {{serverPort}}); + }); +}); \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/nodejs/main.mustache b/modules/swagger-codegen/src/main/resources/nodejs/main.mustache deleted file mode 100644 index 7f4ef645982a..000000000000 --- a/modules/swagger-codegen/src/main/resources/nodejs/main.mustache +++ /dev/null @@ -1,53 +0,0 @@ -var express = require("express") - , url = require("url") - , cors = require("cors") - , app = express() - , swagger = require("swagger-node-express") - , db = false - - -var corsOptions = { - credentials: true, - origin: function(origin,callback) { - if(origin===undefined) { - callback(null,false); - } else { - callback(null,true); - } - } -}; - -app.use(express.json()); -app.use(express.urlencoded()); -app.use(cors(corsOptions)); - -{{#basePath}} -var subpath = express(); - -app.use("{{{basePath}}}", subpath); - -swagger.setAppHandler(subpath); -{{/basePath}} -{{^basePath}} -swagger.setAppHandler(app); -{{/basePath}} - -swagger.configureSwaggerPaths("", "api-docs", "") - -var models = require("./app/models.js"); - -{{#apiInfo}} -{{#apis}} -var {{classname}} = require("./{{apiFolder}}/{{classname}}.js"); -{{/apis}} -{{/apiInfo}} - -swagger.addModels(models) - {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}.add{{httpMethod}}({{classname}}.{{nickname}}) - {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}; - -// configures the app -swagger.configure("http://localhost:8002{{basePath}}", "0.1"); - -// start the server -app.listen(8002); diff --git a/modules/swagger-codegen/src/main/resources/nodejs/models.mustache b/modules/swagger-codegen/src/main/resources/nodejs/models.mustache deleted file mode 100644 index 133fe7c15159..000000000000 --- a/modules/swagger-codegen/src/main/resources/nodejs/models.mustache +++ /dev/null @@ -1,3 +0,0 @@ -exports.models = { - {{#models}}{{#model}}"{{classVarName}}": {{{modelJson}}}{{#hasMoreModels}},{{/hasMoreModels}}{{/model}}{{/models}} -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/nodejs/package.mustache b/modules/swagger-codegen/src/main/resources/nodejs/package.mustache old mode 100755 new mode 100644 index bfd94cb0649b..7add6e813fed --- a/modules/swagger-codegen/src/main/resources/nodejs/package.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/package.mustache @@ -1,16 +1,15 @@ { - "name": "{{{artifactId}}}", - "description": "Wordnik node.js server generator", - "version": "{{{artifactVersion}}}", - "homepage": "{{{homepage}}}", - "main": "./main.js", - "engines": { - "node": ">= 0.8.x" - }, + "name": "{{projectName}}", + "version": "{{appVersion}}", + "description": "{{appDescription}}", + "main": "index.js", + "keywords": [ + "swagger" + ], + "license": "MIT", + "private": true, "dependencies": { - "swagger-node-express": ">= 2.0.x", - "connect": ">= 1.8.x", - "cors": "2.1.1", - "express": "3.x" + "connect": "^3.2.0", + "swagger-tools": "0.8.*" } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/nodejs/service.mustache b/modules/swagger-codegen/src/main/resources/nodejs/service.mustache new file mode 100644 index 000000000000..d7c2ade5079c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/nodejs/service.mustache @@ -0,0 +1,18 @@ +'use strict'; + +{{#operations}} +{{#operation}} +exports.{{nickname}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + + var examples = {}; + {{#examples}} + examples['{{contentType}}'] = {{{example}}}; + {{/examples}} + + {{#returnType}} + if(Object.keys(examples).length > 0) + return examples[Object.keys(examples)[0]]; + {{/returnType}} +} +{{/operation}} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache b/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache new file mode 100644 index 000000000000..8b4c8d33bdcc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache @@ -0,0 +1,42 @@ +{ + "swagger": "2.0", + "info": { + "title": "{{appName}}", + "description": "{{appDescription}}", + "version": "{{apiVersion}}" + }, +{{#apiInfo}} + "produces": ["application/json"], + "host": "localhost:{{serverPort}}", + "basePath": "{{contextPath}}", + "paths": { +{{#apis}} +{{#operations}} + {{#operation}} + "{{{path}}}": { + "{{httpMethod}}": { + "x-swagger-router-controller": "{{classname}}", + "tags": ["{{baseName}}"], + "operationId": "{{operationId}}",{{#hasParams}} + "parameters": [ + {{#allParams}} + {{{jsonSchema}}}{{#hasMore}},{{/hasMore}} + {{/allParams}} + ],{{/hasParams}} + "responses": { + {{#responses}} + "{{code}}": {{{jsonSchema}}} + {{#hasMore}},{{/hasMore}} + {{/responses}} + } + } + } {{#hasMore}},{{/hasMore}} + {{/operation}} + {{#hasMore}},{{/hasMore}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + }, "definitions": { + {{#models}}{{#model}}"{{classVarName}}": {{{modelJson}}}{{#hasMoreModels}},{{/hasMoreModels}}{{/model}}{{/models}} + } +} diff --git a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache index 942a53f88785..17d2ec808363 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache @@ -39,7 +39,7 @@ } {{/isContainer}}{{#isNotContainer}} if({{name}}_dict != nil) - _{{name}} = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{complexType}}} {{/instantiationType}} alloc]initWithValues:{{name}}_dict]; + _{{name}} = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{complexType}}} {{/instantiationType}} alloc]{{setter}}:{{name}}_dict]; {{/isNotContainer}} {{/complexType}} {{/vars}}{{newline}} diff --git a/modules/swagger-codegen/src/main/resources/php/Swagger.mustache b/modules/swagger-codegen/src/main/resources/php/Swagger.mustache index 0f92ac8a0c07..3d6b77d819e8 100644 --- a/modules/swagger-codegen/src/main/resources/php/Swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/php/Swagger.mustache @@ -182,7 +182,7 @@ class APIClient { } else if (is_object($data)) { $values = array(); foreach (array_keys($data::$swaggerTypes) as $property) { - $values[$property] = $this->sanitizeForSerialization($data->$property); + $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$property); } $sanitized = $values; } else { @@ -295,7 +295,8 @@ class APIClient { $instance = new $class(); foreach ($instance::$swaggerTypes as $property => $type) { if (isset($data->$property)) { - $instance->$property = self::deserialize($data->$property, $type); + $original_property_name = $instance::$attributeMap[$property]; + $instance->$property = self::deserialize($data->$original_property_name, $type); } } $deserialized = $instance; diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index f11a15471694..4540f973633f 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -28,7 +28,12 @@ class {{classname}} implements ArrayAccess { static $swaggerTypes = array( {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, {{/hasMore}}{{/vars}} - ); + ); + + static $attributeMap = array( + {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} + ); {{#vars}}{{#description}} /** diff --git a/modules/swagger-codegen/src/main/resources/python/swagger.mustache b/modules/swagger-codegen/src/main/resources/python/swagger.mustache index 8d9053025d12..5a5a7058bdf3 100644 --- a/modules/swagger-codegen/src/main/resources/python/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/python/swagger.mustache @@ -226,7 +226,7 @@ class ApiClient: subValues.append(self.deserialize(subValue, subClass)) setattr(instance, attr, subValues) else: - setattr(instance, attr, self.deserialize(value, objClass)) + setattr(instance, attr, self.deserialize(value, attrType)) return instance diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 1448e52bdf2d..c045a46f69cd 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -23,10 +23,8 @@ class {{classname}} # set default values and merge with input options = { - {{#allParams}} - :{{paramName}} => {{paramName}}{{#hasMore}}, - {{/hasMore}} - {{/allParams}} + {{#allParams}}:'{{paramName}}' => {{paramName}}{{#hasMore}},{{/hasMore}} + {{/allParams}} }.merge(opts) #resource path @@ -38,12 +36,10 @@ class {{classname}} query_param_keys.include? key end - {{#headerParams}}headers = { - {{{paramName}}}: {{{paramName}}}, - } - {{/headerParams}} - {{^headerParams}}headers = nil - {{/headerParams}} + # header parameters, if any + headers = {} + {{#headerParams}}{{#optional}}headers[:'{{{baseName}}}'] = options[:'{{{paramName}}}'] if options[:'{{{paramName}}}']{{/optional}}{{/headerParams}} + {{#headerParams}}{{^optional}}headers[:'{{{baseName}}}'] = {{{paramName}}}{{/optional}}{{/headerParams}} # http body (model) post_body = nil diff --git a/modules/swagger-codegen/src/main/resources/ruby/model.mustache b/modules/swagger-codegen/src/main/resources/ruby/model.mustache index ef3b2fe48f93..397a64f6471f 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/model.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/model.mustache @@ -6,8 +6,7 @@ class {{classname}} # :internal => :external def self.attribute_map { - {{#vars}} - :{{{name}}} => :{{{baseName}}}{{#hasMore}},{{/hasMore}} + {{#vars}}:{{{name}}} => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}} {{/vars}} } end @@ -17,13 +16,9 @@ class {{classname}} # Morph attribute keys into undescored rubyish style {{#vars}} if self.class.attribute_map[:"{{{name}}}"] - {{#isContainer}} - if (value = attributes["{{{baseName}}}"]).is_a?(Array) - @{{{name}}} = value{{#complexType}}.map{ |v| {{complexType}}.new(v) }{{/complexType}}{{newline}} - end - {{/isContainer}}{{^isContainer}} - @{{{name}}} = attributes["{{{baseName}}}"] - {{/isContainer}} + {{#isContainer}}if (value = attributes["{{{baseName}}}"]).is_a?(Array) + @{{{name}}} = value{{#complexType}}.map{ |v| {{complexType}}.new(v) }{{/complexType}} + end{{/isContainer}}{{^isContainer}}@{{{name}}} = attributes["{{{baseName}}}"]{{/isContainer}} end {{/vars}} 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 c0b3c46268c3..1cf6e0dfa0e0 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache @@ -3,7 +3,7 @@ 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 + 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 @@ -11,7 +11,7 @@ module Swagger @scheme = 'http' @host = 'api.wordnik.com' @base_path = '/v4' - @user_agent = "ruby-#{Swagger::VERSION}" + @user_agent = "ruby-swagger-#{Swagger::VERSION}" @inject_format = true @force_ending_format = false @camelize_params = true @@ -19,4 +19,4 @@ module Swagger end -end \ No newline at end of file +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 92b5cba810a2..344018279825 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache @@ -19,7 +19,8 @@ module Swagger # Set default headers default_headers = { 'Content-Type' => "application/#{attributes[:format].downcase}", - :api_key => Swagger.configuration.api_key + :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 diff --git a/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache index 186be3640143..c8bd04196587 100644 --- a/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache @@ -17,6 +17,7 @@ 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._ @@ -26,6 +27,7 @@ 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) diff --git a/modules/swagger-codegen/src/main/resources/swagger/README.md b/modules/swagger-codegen/src/main/resources/swagger/README.md new file mode 100644 index 000000000000..0c2b69a24dbd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swagger/README.md @@ -0,0 +1,2 @@ +# Swagger JSON +This is a swagger JSON built by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. \ 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 91f0c5dba2ca..3c31c87b25d6 100644 --- a/modules/swagger-codegen/src/test/scala/CodegenTest.scala +++ b/modules/swagger-codegen/src/test/scala/CodegenTest.scala @@ -22,7 +22,7 @@ class CodegenTest extends FlatSpec with Matchers { val codegen = new DefaultCodegen() val path = "/pet/{petId}/uploadImage" val p = model.getPaths().get(path).getPost() - val op = codegen.fromOperation(path, "post", p) + val op = codegen.fromOperation(path, "post", p, model.getDefinitions()) op.operationId should be ("uploadFile") op.httpMethod should be ("POST") @@ -52,7 +52,7 @@ class CodegenTest extends FlatSpec with Matchers { val codegen = new DefaultCodegen() val path = "/pet/{petId}" val p = model.getPaths().get(path).getPost() - val op = codegen.fromOperation(path, "post", p) + val op = codegen.fromOperation(path, "post", p, model.getDefinitions()) op.operationId should be ("updatePetWithForm") op.httpMethod should be ("POST") @@ -103,7 +103,7 @@ class CodegenTest extends FlatSpec with Matchers { val path = "/tests/withTwoHundredAndDefault" val p = model.getPaths().get(path).getGet() - val op = codegen.fromOperation(path, "get", p) + val op = codegen.fromOperation(path, "get", p, model.getDefinitions()) op.returnType should be("String") } @@ -116,9 +116,7 @@ class CodegenTest extends FlatSpec with Matchers { val path = "/tests/withoutTwoHundredButDefault" val p = model.getPaths().get(path).getGet() - val op = codegen.fromOperation(path, "get", p) + val op = codegen.fromOperation(path, "get", p, model.getDefinitions()) op.returnType should be("String") - } - } \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala b/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala index 1cfed711c8d8..e0de2110ddc2 100644 --- a/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala +++ b/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala @@ -248,14 +248,14 @@ class ObjcModelTest extends FlatSpec with Matchers { val animalPaths = model.getPaths() val animalOps = animalPaths.get("/animals") animalOps.getPost() should not be (null) - val animalCo = codegen.fromOperation("/animals", "POST", animalOps.getPost()) + val animalCo = codegen.fromOperation("/animals", "POST", animalOps.getPost(), model.getDefinitions()) animalCo.imports.size should be (1) animalCo.imports.contains("SWGAnimal") should equal (true) val insectPaths = model.getPaths() val insectOps = insectPaths.get("/insects") insectOps.getPost() should not be (null) - val insectCo = codegen.fromOperation("/insects", "POST", insectOps.getPost()) + val insectCo = codegen.fromOperation("/insects", "POST", insectOps.getPost(), model.getDefinitions()) insectCo.imports.size should be (1) insectCo.imports.contains("SWGInsect") should equal (true) } diff --git a/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala b/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala index 5e5034e5efc4..92a69ff3d2de 100644 --- a/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala +++ b/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala @@ -245,14 +245,14 @@ class PhpModelTest extends FlatSpec with Matchers { val animalPaths = model.getPaths() val animalOps = animalPaths.get("/animals") animalOps.getPost() should not be (null) - val animalCo = codegen.fromOperation("/animals", "POST", animalOps.getPost()) + val animalCo = codegen.fromOperation("/animals", "POST", animalOps.getPost(), model.getDefinitions()) animalCo.imports.size should be (1) animalCo.imports.contains("Animal") should equal (true) val insectPaths = model.getPaths() val insectOps = insectPaths.get("/insects") insectOps.getPost() should not be (null) - val insectCo = codegen.fromOperation("/insects", "POST", insectOps.getPost()) + val insectCo = codegen.fromOperation("/insects", "POST", insectOps.getPost(), model.getDefinitions()) insectCo.imports.size should be (1) insectCo.imports.contains("Insect") should equal (true) } diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/online/Generator.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/online/Generator.java index 6bbbfec4f7b1..996a724bb6d3 100644 --- a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/online/Generator.java +++ b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/online/Generator.java @@ -66,6 +66,7 @@ public class Generator { List files = new Codegen().opts(clientOptInput).generate(); if(files.size() > 0) { List filesToAdd = new ArrayList(); + System.out.println("adding to " + outputFolder); filesToAdd.add(new File(outputFolder)); ZipUtil zip = new ZipUtil(); zip.compressFiles(filesToAdd, outputFilename); diff --git a/pom.xml b/pom.xml index 3f3458c3f252..13cfee6ca660 100644 --- a/pom.xml +++ b/pom.xml @@ -347,7 +347,7 @@ - 1.0.3-SNAPSHOT + 1.0.3 2.11.1 2.3.4 1.5.3-M1-SNAPSHOT diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java index 966a141c03de..abe51bb71061 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java @@ -19,16 +19,75 @@ import javax.ws.rs.core.MediaType; import java.util.Map; import java.util.HashMap; import java.util.List; -import java.io.IOException; +import java.util.Date; +import java.util.TimeZone; + import java.net.URLEncoder; + +import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.text.SimpleDateFormat; +import java.text.ParseException; + public class ApiInvoker { private static ApiInvoker INSTANCE = new ApiInvoker(); private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); private boolean isDebug = false; + /** + * ISO 8601 date time format. + * @see https://en.wikipedia.org/wiki/ISO_8601 + */ + public static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + + /** + * ISO 8601 date format. + * @see https://en.wikipedia.org/wiki/ISO_8601 + */ + public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); + + static { + // Use UTC as the default time zone. + DATE_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); + DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); + } + + public static Date parseDateTime(String str) { + try { + return DATE_TIME_FORMAT.parse(str); + } catch (java.text.ParseException e) { + throw new RuntimeException(e); + } + } + + public static Date parseDate(String str) { + try { + return DATE_FORMAT.parse(str); + } catch (java.text.ParseException e) { + throw new RuntimeException(e); + } + } + + public static String formatDateTime(Date datetime) { + return DATE_TIME_FORMAT.format(datetime); + } + + public static String formatDate(Date date) { + return DATE_FORMAT.format(date); + } + + public static String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDateTime((Date) param); + } else { + return String.valueOf(param); + } + } + public void enableDebug() { isDebug = true; } 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 53c1d55fb680..686deae12ead 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 @@ -148,8 +148,8 @@ public class PetApi { Map headerParams = new HashMap(); Map formParams = new HashMap(); - if(!"null".equals(String.valueOf(status))) - queryParams.put("status", String.valueOf(status)); + if (status != null) + queryParams.put("status", ApiInvoker.parameterToString(status)); String[] contentTypes = { @@ -200,8 +200,8 @@ public class PetApi { Map headerParams = new HashMap(); Map formParams = new HashMap(); - if(!"null".equals(String.valueOf(tags))) - queryParams.put("tags", String.valueOf(tags)); + if (tags != null) + queryParams.put("tags", ApiInvoker.parameterToString(tags)); String[] contentTypes = { @@ -317,17 +317,17 @@ public class PetApi { FormDataMultiPart mp = new FormDataMultiPart(); hasFields = true; - mp.field("name", name, MediaType.MULTIPART_FORM_DATA_TYPE); + mp.field("name", ApiInvoker.parameterToString(name), MediaType.MULTIPART_FORM_DATA_TYPE); hasFields = true; - mp.field("status", status, MediaType.MULTIPART_FORM_DATA_TYPE); + mp.field("status", ApiInvoker.parameterToString(status), MediaType.MULTIPART_FORM_DATA_TYPE); if(hasFields) postBody = mp; } else { - formParams.put("name", name); - formParams.put("status", status); + formParams.put("name", ApiInvoker.parameterToString(name)); + formParams.put("status", ApiInvoker.parameterToString(status)); } @@ -364,7 +364,7 @@ public class PetApi { Map formParams = new HashMap(); - headerParams.put("api_key", api_key); + headerParams.put("api_key", ApiInvoker.parameterToString(api_key)); String[] contentTypes = { @@ -428,7 +428,7 @@ public class PetApi { FormDataMultiPart mp = new FormDataMultiPart(); hasFields = true; - mp.field("additionalMetadata", additionalMetadata, MediaType.MULTIPART_FORM_DATA_TYPE); + mp.field("additionalMetadata", ApiInvoker.parameterToString(additionalMetadata), MediaType.MULTIPART_FORM_DATA_TYPE); hasFields = true; mp.field("file", file, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -437,7 +437,7 @@ public class PetApi { postBody = mp; } else { - formParams.put("additionalMetadata", additionalMetadata); + formParams.put("additionalMetadata", ApiInvoker.parameterToString(additionalMetadata)); } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java index 2da4c6ae32e4..7b8b2cad83a5 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java @@ -198,10 +198,10 @@ public class UserApi { Map headerParams = new HashMap(); Map formParams = new HashMap(); - if(!"null".equals(String.valueOf(username))) - queryParams.put("username", String.valueOf(username)); - if(!"null".equals(String.valueOf(password))) - queryParams.put("password", String.valueOf(password)); + if (username != null) + queryParams.put("username", ApiInvoker.parameterToString(username)); + if (password != null) + queryParams.put("password", ApiInvoker.parameterToString(password)); String[] contentTypes = { diff --git a/samples/client/petstore/objc/client/SWGPetApi.m b/samples/client/petstore/objc/client/SWGPetApi.m index bf968a2776a0..1305f552c8df 100644 --- a/samples/client/petstore/objc/client/SWGPetApi.m +++ b/samples/client/petstore/objc/client/SWGPetApi.m @@ -110,28 +110,6 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - // primitive response type - - - // no return base type - return [client stringWithCompletionBlock: requestUrl - method: @"PUT" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - - - } -(NSNumber*) addPetWithCompletionBlock: (SWGPet*) body @@ -193,28 +171,6 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - // primitive response type - - - // no return base type - return [client stringWithCompletionBlock: requestUrl - method: @"POST" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - - - } -(NSNumber*) findPetsByStatusWithCompletionBlock: (NSArray*) status @@ -443,28 +399,6 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - // primitive response type - - - // no return base type - return [client stringWithCompletionBlock: requestUrl - method: @"POST" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - - - } -(NSNumber*) deletePetWithCompletionBlock: (NSString*) api_key @@ -509,28 +443,6 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - // primitive response type - - - // no return base type - return [client stringWithCompletionBlock: requestUrl - method: @"DELETE" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - - - } -(NSNumber*) uploadFileWithCompletionBlock: (NSNumber*) petId diff --git a/samples/client/petstore/objc/client/SWGStoreApi.m b/samples/client/petstore/objc/client/SWGStoreApi.m index b81d127eb51e..b0c42e7d982f 100644 --- a/samples/client/petstore/objc/client/SWGStoreApi.m +++ b/samples/client/petstore/objc/client/SWGStoreApi.m @@ -303,28 +303,6 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - // primitive response type - - - // no return base type - return [client stringWithCompletionBlock: requestUrl - method: @"DELETE" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - - - } diff --git a/samples/client/petstore/objc/client/SWGUserApi.m b/samples/client/petstore/objc/client/SWGUserApi.m index 4c69415620b6..fbaafa76fa52 100644 --- a/samples/client/petstore/objc/client/SWGUserApi.m +++ b/samples/client/petstore/objc/client/SWGUserApi.m @@ -554,28 +554,6 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - // primitive response type - - - // no return base type - return [client stringWithCompletionBlock: requestUrl - method: @"PUT" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - - - } -(NSNumber*) deleteUserWithCompletionBlock: (NSString*) username @@ -617,28 +595,6 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - // primitive response type - - - // no return base type - return [client stringWithCompletionBlock: requestUrl - method: @"DELETE" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - - - } diff --git a/samples/client/petstore/php/Swagger.php b/samples/client/petstore/php/Swagger.php index 0f92ac8a0c07..3d6b77d819e8 100644 --- a/samples/client/petstore/php/Swagger.php +++ b/samples/client/petstore/php/Swagger.php @@ -182,7 +182,7 @@ class APIClient { } else if (is_object($data)) { $values = array(); foreach (array_keys($data::$swaggerTypes) as $property) { - $values[$property] = $this->sanitizeForSerialization($data->$property); + $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$property); } $sanitized = $values; } else { @@ -295,7 +295,8 @@ class APIClient { $instance = new $class(); foreach ($instance::$swaggerTypes as $property => $type) { if (isset($data->$property)) { - $instance->$property = self::deserialize($data->$property, $type); + $original_property_name = $instance::$attributeMap[$property]; + $instance->$property = self::deserialize($data->$original_property_name, $type); } } $deserialized = $instance; diff --git a/samples/client/petstore/php/models/Category.php b/samples/client/petstore/php/models/Category.php index 867cacf771af..98e7ba24800d 100644 --- a/samples/client/petstore/php/models/Category.php +++ b/samples/client/petstore/php/models/Category.php @@ -22,13 +22,39 @@ * */ -class Category { +class Category implements ArrayAccess { static $swaggerTypes = array( 'id' => 'int', 'name' => 'string' - ); + ); + + static $attributeMap = array( + 'id' => 'id', + 'name' => 'name' + ); public $id; /* int */ public $name; /* string */ + + public function __construct(array $data) { + $this->id = $data["id"]; + $this->name = $data["name"]; + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } } diff --git a/samples/client/petstore/php/models/Order.php b/samples/client/petstore/php/models/Order.php index d5e10a59404c..519e44bf217e 100644 --- a/samples/client/petstore/php/models/Order.php +++ b/samples/client/petstore/php/models/Order.php @@ -22,7 +22,7 @@ * */ -class Order { +class Order implements ArrayAccess { static $swaggerTypes = array( 'id' => 'int', 'petId' => 'int', @@ -30,7 +30,16 @@ class Order { 'shipDate' => 'DateTime', 'status' => 'string', 'complete' => 'boolean' - ); + ); + + static $attributeMap = array( + 'id' => 'id', + 'petId' => 'petId', + 'quantity' => 'quantity', + 'shipDate' => 'shipDate', + 'status' => 'status', + 'complete' => 'complete' + ); public $id; /* int */ @@ -42,4 +51,29 @@ class Order { */ public $status; /* string */ public $complete; /* boolean */ + + public function __construct(array $data) { + $this->id = $data["id"]; + $this->petId = $data["petId"]; + $this->quantity = $data["quantity"]; + $this->shipDate = $data["shipDate"]; + $this->status = $data["status"]; + $this->complete = $data["complete"]; + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } } diff --git a/samples/client/petstore/php/models/Pet.php b/samples/client/petstore/php/models/Pet.php index d3231bdc8af1..ad427e91a872 100644 --- a/samples/client/petstore/php/models/Pet.php +++ b/samples/client/petstore/php/models/Pet.php @@ -22,7 +22,7 @@ * */ -class Pet { +class Pet implements ArrayAccess { static $swaggerTypes = array( 'id' => 'int', 'category' => 'Category', @@ -30,7 +30,16 @@ class Pet { 'photoUrls' => 'array[string]', 'tags' => 'array[Tag]', 'status' => 'string' - ); + ); + + static $attributeMap = array( + 'id' => 'id', + 'category' => 'category', + 'name' => 'name', + 'photoUrls' => 'photoUrls', + 'tags' => 'tags', + 'status' => 'status' + ); public $id; /* int */ @@ -42,4 +51,29 @@ class Pet { * pet status in the store */ public $status; /* string */ + + public function __construct(array $data) { + $this->id = $data["id"]; + $this->category = $data["category"]; + $this->name = $data["name"]; + $this->photoUrls = $data["photoUrls"]; + $this->tags = $data["tags"]; + $this->status = $data["status"]; + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } } diff --git a/samples/client/petstore/php/models/Tag.php b/samples/client/petstore/php/models/Tag.php index 238d768e682d..f8efc998df66 100644 --- a/samples/client/petstore/php/models/Tag.php +++ b/samples/client/petstore/php/models/Tag.php @@ -22,13 +22,39 @@ * */ -class Tag { +class Tag implements ArrayAccess { static $swaggerTypes = array( 'id' => 'int', 'name' => 'string' - ); + ); + + static $attributeMap = array( + 'id' => 'id', + 'name' => 'name' + ); public $id; /* int */ public $name; /* string */ + + public function __construct(array $data) { + $this->id = $data["id"]; + $this->name = $data["name"]; + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } } diff --git a/samples/client/petstore/php/models/User.php b/samples/client/petstore/php/models/User.php index 6178042052bb..6799a001558e 100644 --- a/samples/client/petstore/php/models/User.php +++ b/samples/client/petstore/php/models/User.php @@ -22,7 +22,7 @@ * */ -class User { +class User implements ArrayAccess { static $swaggerTypes = array( 'id' => 'int', 'username' => 'string', @@ -32,7 +32,18 @@ class User { 'password' => 'string', 'phone' => 'string', 'userStatus' => 'int' - ); + ); + + static $attributeMap = array( + 'id' => 'id', + 'username' => 'username', + 'firstName' => 'firstName', + 'lastName' => 'lastName', + 'email' => 'email', + 'password' => 'password', + 'phone' => 'phone', + 'userStatus' => 'userStatus' + ); public $id; /* int */ @@ -46,4 +57,31 @@ class User { * User Status */ public $userStatus; /* int */ + + public function __construct(array $data) { + $this->id = $data["id"]; + $this->username = $data["username"]; + $this->firstName = $data["firstName"]; + $this->lastName = $data["lastName"]; + $this->email = $data["email"]; + $this->password = $data["password"]; + $this->phone = $data["phone"]; + $this->userStatus = $data["userStatus"]; + } + + public function offsetExists($offset) { + return isset($this->$offset); + } + + public function offsetGet($offset) { + return $this->$offset; + } + + public function offsetSet($offset, $value) { + $this->$offset = $value; + } + + public function offsetUnset($offset) { + unset($this->$offset); + } } diff --git a/samples/client/petstore/ruby/lib/PetApi.rb b/samples/client/petstore/ruby/lib/PetApi.rb index d7d55a7c3230..d80009a53805 100644 --- a/samples/client/petstore/ruby/lib/PetApi.rb +++ b/samples/client/petstore/ruby/lib/PetApi.rb @@ -16,9 +16,8 @@ class PetApi # set default values and merge with input options = { - - :body => body - + :'body' => body + }.merge(opts) #resource path @@ -29,8 +28,9 @@ class PetApi query_param_keys.include? key end + # header parameters, if any + headers = {} - headers = nil # http body (model) @@ -77,9 +77,8 @@ class PetApi # set default values and merge with input options = { - - :body => body - + :'body' => body + }.merge(opts) #resource path @@ -90,8 +89,9 @@ class PetApi query_param_keys.include? key end + # header parameters, if any + headers = {} - headers = nil # http body (model) @@ -138,9 +138,8 @@ class PetApi # set default values and merge with input options = { - - :status => status - + :'status' => status + }.merge(opts) #resource path @@ -151,8 +150,9 @@ class PetApi query_param_keys.include? key end + # header parameters, if any + headers = {} - headers = nil # http body (model) @@ -180,9 +180,8 @@ class PetApi # set default values and merge with input options = { - - :tags => tags - + :'tags' => tags + }.merge(opts) #resource path @@ -193,8 +192,9 @@ class PetApi query_param_keys.include? key end + # header parameters, if any + headers = {} - headers = nil # http body (model) @@ -222,9 +222,8 @@ class PetApi # set default values and merge with input options = { - - :petId => petId - + :'petId' => petId + }.merge(opts) #resource path @@ -236,8 +235,9 @@ class PetApi query_param_keys.include? key end + # header parameters, if any + headers = {} - headers = nil # http body (model) @@ -264,15 +264,10 @@ class PetApi # set default values and merge with input options = { - - :petId => petId, + :'petId' => petId, + :'name' => name, + :'status' => status - - :name => name, - - - :status => status - }.merge(opts) #resource path @@ -284,8 +279,9 @@ class PetApi query_param_keys.include? key end + # header parameters, if any + headers = {} - headers = nil # http body (model) @@ -313,12 +309,9 @@ class PetApi # set default values and merge with input options = { - - :api_key => api_key, + :'api_key' => api_key, + :'petId' => petId - - :petId => petId - }.merge(opts) #resource path @@ -330,11 +323,10 @@ class PetApi query_param_keys.include? key end - headers = { - api_key: api_key, - } - + # header parameters, if any + headers = {} + headers[:'api_key'] = api_key # http body (model) post_body = nil @@ -359,15 +351,10 @@ class PetApi # set default values and merge with input options = { - - :petId => petId, + :'petId' => petId, + :'additionalMetadata' => additionalMetadata, + :'file' => file - - :additionalMetadata => additionalMetadata, - - - :file => file - }.merge(opts) #resource path @@ -379,8 +366,9 @@ class PetApi query_param_keys.include? key end + # header parameters, if any + headers = {} - headers = nil # http body (model) diff --git a/samples/client/petstore/ruby/lib/StoreApi.rb b/samples/client/petstore/ruby/lib/StoreApi.rb index 31513cc832b2..2e9f8fe7ea9c 100644 --- a/samples/client/petstore/ruby/lib/StoreApi.rb +++ b/samples/client/petstore/ruby/lib/StoreApi.rb @@ -16,7 +16,7 @@ class StoreApi # set default values and merge with input options = { - + }.merge(opts) #resource path @@ -27,8 +27,9 @@ class StoreApi query_param_keys.include? key end + # header parameters, if any + headers = {} - headers = nil # http body (model) @@ -56,9 +57,8 @@ class StoreApi # set default values and merge with input options = { - - :body => body - + :'body' => body + }.merge(opts) #resource path @@ -69,8 +69,9 @@ class StoreApi query_param_keys.include? key end + # header parameters, if any + headers = {} - headers = nil # http body (model) @@ -118,9 +119,8 @@ class StoreApi # set default values and merge with input options = { - - :orderId => orderId - + :'orderId' => orderId + }.merge(opts) #resource path @@ -132,8 +132,9 @@ class StoreApi query_param_keys.include? key end + # header parameters, if any + headers = {} - headers = nil # http body (model) @@ -160,9 +161,8 @@ class StoreApi # set default values and merge with input options = { - - :orderId => orderId - + :'orderId' => orderId + }.merge(opts) #resource path @@ -174,8 +174,9 @@ class StoreApi query_param_keys.include? key end + # header parameters, if any + headers = {} - headers = nil # http body (model) diff --git a/samples/client/petstore/ruby/lib/UserApi.rb b/samples/client/petstore/ruby/lib/UserApi.rb index 4b24bf1f487f..6738cddb5f93 100644 --- a/samples/client/petstore/ruby/lib/UserApi.rb +++ b/samples/client/petstore/ruby/lib/UserApi.rb @@ -16,9 +16,8 @@ class UserApi # set default values and merge with input options = { - - :body => body - + :'body' => body + }.merge(opts) #resource path @@ -29,8 +28,9 @@ class UserApi query_param_keys.include? key end + # header parameters, if any + headers = {} - headers = nil # http body (model) @@ -77,9 +77,8 @@ class UserApi # set default values and merge with input options = { - - :body => body - + :'body' => body + }.merge(opts) #resource path @@ -90,8 +89,9 @@ class UserApi query_param_keys.include? key end + # header parameters, if any + headers = {} - headers = nil # http body (model) @@ -138,9 +138,8 @@ class UserApi # set default values and merge with input options = { - - :body => body - + :'body' => body + }.merge(opts) #resource path @@ -151,8 +150,9 @@ class UserApi query_param_keys.include? key end + # header parameters, if any + headers = {} - headers = nil # http body (model) @@ -199,12 +199,9 @@ class UserApi # set default values and merge with input options = { - - :username => username, + :'username' => username, + :'password' => password - - :password => password - }.merge(opts) #resource path @@ -215,8 +212,9 @@ class UserApi query_param_keys.include? key end + # header parameters, if any + headers = {} - headers = nil # http body (model) @@ -243,7 +241,7 @@ class UserApi # set default values and merge with input options = { - + }.merge(opts) #resource path @@ -254,8 +252,9 @@ class UserApi query_param_keys.include? key end + # header parameters, if any + headers = {} - headers = nil # http body (model) @@ -281,9 +280,8 @@ class UserApi # set default values and merge with input options = { - - :username => username - + :'username' => username + }.merge(opts) #resource path @@ -295,8 +293,9 @@ class UserApi query_param_keys.include? key end + # header parameters, if any + headers = {} - headers = nil # http body (model) @@ -323,12 +322,9 @@ class UserApi # set default values and merge with input options = { - - :username => username, + :'username' => username, + :'body' => body - - :body => body - }.merge(opts) #resource path @@ -340,8 +336,9 @@ class UserApi query_param_keys.include? key end + # header parameters, if any + headers = {} - headers = nil # http body (model) @@ -388,9 +385,8 @@ class UserApi # set default values and merge with input options = { - - :username => username - + :'username' => username + }.merge(opts) #resource path @@ -402,8 +398,9 @@ class UserApi query_param_keys.include? key end + # header parameters, if any + headers = {} - headers = nil # http body (model) diff --git a/samples/client/petstore/ruby/lib/swagger/configuration.rb b/samples/client/petstore/ruby/lib/swagger/configuration.rb index c0b3c46268c3..1cf6e0dfa0e0 100644 --- a/samples/client/petstore/ruby/lib/swagger/configuration.rb +++ b/samples/client/petstore/ruby/lib/swagger/configuration.rb @@ -3,7 +3,7 @@ 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 + 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 @@ -11,7 +11,7 @@ module Swagger @scheme = 'http' @host = 'api.wordnik.com' @base_path = '/v4' - @user_agent = "ruby-#{Swagger::VERSION}" + @user_agent = "ruby-swagger-#{Swagger::VERSION}" @inject_format = true @force_ending_format = false @camelize_params = true @@ -19,4 +19,4 @@ module Swagger end -end \ No newline at end of file +end diff --git a/samples/client/petstore/ruby/lib/swagger/request.rb b/samples/client/petstore/ruby/lib/swagger/request.rb index 92b5cba810a2..344018279825 100644 --- a/samples/client/petstore/ruby/lib/swagger/request.rb +++ b/samples/client/petstore/ruby/lib/swagger/request.rb @@ -19,7 +19,8 @@ module Swagger # Set default headers default_headers = { 'Content-Type' => "application/#{attributes[:format].downcase}", - :api_key => Swagger.configuration.api_key + :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 diff --git a/samples/client/petstore/ruby/models/Category.rb b/samples/client/petstore/ruby/models/Category.rb index 0f15c43a70a9..64ca857e17e6 100644 --- a/samples/client/petstore/ruby/models/Category.rb +++ b/samples/client/petstore/ruby/models/Category.rb @@ -4,10 +4,8 @@ class Category # :internal => :external def self.attribute_map { - - :id => :id, - - :name => :name + :id => :'id', + :name => :'name' } end @@ -17,15 +15,11 @@ class Category # Morph attribute keys into undescored rubyish style if self.class.attribute_map[:"id"] - @id = attributes["id"] - end if self.class.attribute_map[:"name"] - @name = attributes["name"] - end end diff --git a/samples/client/petstore/ruby/models/Order.rb b/samples/client/petstore/ruby/models/Order.rb index 45a0864cfcc0..e7db88e16c9a 100644 --- a/samples/client/petstore/ruby/models/Order.rb +++ b/samples/client/petstore/ruby/models/Order.rb @@ -4,18 +4,12 @@ class Order # :internal => :external def self.attribute_map { - - :id => :id, - - :petId => :petId, - - :quantity => :quantity, - - :shipDate => :shipDate, - - :status => :status, - - :complete => :complete + :id => :'id', + :petId => :'petId', + :quantity => :'quantity', + :shipDate => :'shipDate', + :status => :'status', + :complete => :'complete' } end @@ -25,39 +19,27 @@ class Order # Morph attribute keys into undescored rubyish style if self.class.attribute_map[:"id"] - @id = attributes["id"] - end if self.class.attribute_map[:"petId"] - @petId = attributes["petId"] - end if self.class.attribute_map[:"quantity"] - @quantity = attributes["quantity"] - end if self.class.attribute_map[:"shipDate"] - @shipDate = attributes["shipDate"] - end if self.class.attribute_map[:"status"] - @status = attributes["status"] - end if self.class.attribute_map[:"complete"] - @complete = attributes["complete"] - end end diff --git a/samples/client/petstore/ruby/models/Pet.rb b/samples/client/petstore/ruby/models/Pet.rb index f67067e6f915..b279ad5eb3e7 100644 --- a/samples/client/petstore/ruby/models/Pet.rb +++ b/samples/client/petstore/ruby/models/Pet.rb @@ -4,18 +4,12 @@ class Pet # :internal => :external def self.attribute_map { - - :id => :id, - - :category => :category, - - :name => :name, - - :photoUrls => :photoUrls, - - :tags => :tags, - - :status => :status + :id => :'id', + :category => :'category', + :name => :'name', + :photoUrls => :'photoUrls', + :tags => :'tags', + :status => :'status' } end @@ -25,43 +19,31 @@ class Pet # Morph attribute keys into undescored rubyish style if self.class.attribute_map[:"id"] - @id = attributes["id"] - end if self.class.attribute_map[:"category"] - @category = attributes["category"] - end if self.class.attribute_map[:"name"] - @name = attributes["name"] - end if self.class.attribute_map[:"photoUrls"] - if (value = attributes["photoUrls"]).is_a?(Array) @photoUrls = value end - end if self.class.attribute_map[:"tags"] - if (value = attributes["tags"]).is_a?(Array) @tags = value.map{ |v| Tag.new(v) } end - end if self.class.attribute_map[:"status"] - @status = attributes["status"] - end end diff --git a/samples/client/petstore/ruby/models/Tag.rb b/samples/client/petstore/ruby/models/Tag.rb index 9a9193b8e823..24e3d1d0706e 100644 --- a/samples/client/petstore/ruby/models/Tag.rb +++ b/samples/client/petstore/ruby/models/Tag.rb @@ -4,10 +4,8 @@ class Tag # :internal => :external def self.attribute_map { - - :id => :id, - - :name => :name + :id => :'id', + :name => :'name' } end @@ -17,15 +15,11 @@ class Tag # Morph attribute keys into undescored rubyish style if self.class.attribute_map[:"id"] - @id = attributes["id"] - end if self.class.attribute_map[:"name"] - @name = attributes["name"] - end end diff --git a/samples/client/petstore/ruby/models/User.rb b/samples/client/petstore/ruby/models/User.rb index b7981a2bc410..f70f6794ebe8 100644 --- a/samples/client/petstore/ruby/models/User.rb +++ b/samples/client/petstore/ruby/models/User.rb @@ -4,22 +4,14 @@ class User # :internal => :external def self.attribute_map { - - :id => :id, - - :username => :username, - - :firstName => :firstName, - - :lastName => :lastName, - - :email => :email, - - :password => :password, - - :phone => :phone, - - :userStatus => :userStatus + :id => :'id', + :username => :'username', + :firstName => :'firstName', + :lastName => :'lastName', + :email => :'email', + :password => :'password', + :phone => :'phone', + :userStatus => :'userStatus' } end @@ -29,51 +21,35 @@ class User # Morph attribute keys into undescored rubyish style if self.class.attribute_map[:"id"] - @id = attributes["id"] - end if self.class.attribute_map[:"username"] - @username = attributes["username"] - end if self.class.attribute_map[:"firstName"] - @firstName = attributes["firstName"] - end if self.class.attribute_map[:"lastName"] - @lastName = attributes["lastName"] - end if self.class.attribute_map[:"email"] - @email = attributes["email"] - end if self.class.attribute_map[:"password"] - @password = attributes["password"] - end if self.class.attribute_map[:"phone"] - @phone = attributes["phone"] - end if self.class.attribute_map[:"userStatus"] - @userStatus = attributes["userStatus"] - end end diff --git a/samples/client/petstore/scala/src/main/java/io/swagger/client/ApiInvoker.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/ApiInvoker.scala similarity index 100% rename from samples/client/petstore/scala/src/main/java/io/swagger/client/ApiInvoker.scala rename to samples/client/petstore/scala/src/main/scala/io/swagger/client/ApiInvoker.scala diff --git a/samples/client/petstore/scala/src/main/java/io/swagger/client/api/PetApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala similarity index 100% rename from samples/client/petstore/scala/src/main/java/io/swagger/client/api/PetApi.scala rename to samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala diff --git a/samples/client/petstore/scala/src/main/java/io/swagger/client/api/StoreApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala similarity index 100% rename from samples/client/petstore/scala/src/main/java/io/swagger/client/api/StoreApi.scala rename to samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala diff --git a/samples/client/petstore/scala/src/main/java/io/swagger/client/api/UserApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala similarity index 100% rename from samples/client/petstore/scala/src/main/java/io/swagger/client/api/UserApi.scala rename to samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala diff --git a/samples/client/petstore/scala/src/main/java/io/swagger/client/model/Category.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Category.scala similarity index 100% rename from samples/client/petstore/scala/src/main/java/io/swagger/client/model/Category.scala rename to samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Category.scala diff --git a/samples/client/petstore/scala/src/main/java/io/swagger/client/model/Order.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Order.scala similarity index 100% rename from samples/client/petstore/scala/src/main/java/io/swagger/client/model/Order.scala rename to samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Order.scala diff --git a/samples/client/petstore/scala/src/main/java/io/swagger/client/model/Pet.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Pet.scala similarity index 100% rename from samples/client/petstore/scala/src/main/java/io/swagger/client/model/Pet.scala rename to samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Pet.scala diff --git a/samples/client/petstore/scala/src/main/java/io/swagger/client/model/Tag.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Tag.scala similarity index 100% rename from samples/client/petstore/scala/src/main/java/io/swagger/client/model/Tag.scala rename to samples/client/petstore/scala/src/main/scala/io/swagger/client/model/Tag.scala diff --git a/samples/client/petstore/scala/src/main/java/io/swagger/client/model/User.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/model/User.scala similarity index 100% rename from samples/client/petstore/scala/src/main/java/io/swagger/client/model/User.scala rename to samples/client/petstore/scala/src/main/scala/io/swagger/client/model/User.scala diff --git a/samples/client/petstore/scala/src/test/scala/PetApiTest.scala b/samples/client/petstore/scala/src/test/scala/PetApiTest.scala index c06a2072998a..24ce4826fcb4 100644 --- a/samples/client/petstore/scala/src/test/scala/PetApiTest.scala +++ b/samples/client/petstore/scala/src/test/scala/PetApiTest.scala @@ -1,5 +1,6 @@ -import com.wordnik.petstore.api._ -import com.wordnik.petstore.model._ +import io.swagger.client._ +import io.swagger.client.api._ +import io.swagger.client.model._ import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner @@ -30,7 +31,7 @@ class PetApiTest extends FlatSpec with Matchers { Category(1, "sold"), "dragon", (for (i <- (1 to 10)) yield "http://foo.com/photo/" + i).toList, - (for (i <- (1 to 5)) yield com.wordnik.petstore.model.Tag(i, "tag-" + i)).toList, + (for (i <- (1 to 5)) yield io.swagger.client.model.Tag(i, "tag-" + i)).toList, "lost" ) @@ -55,7 +56,7 @@ class PetApiTest extends FlatSpec with Matchers { Category(1, "sold"), "programmer", (for (i <- (1 to 10)) yield "http://foo.com/photo/" + i).toList, - (for (i <- (1 to 5)) yield com.wordnik.petstore.model.Tag(i, "tag-" + i)).toList, + (for (i <- (1 to 5)) yield io.swagger.client.model.Tag(i, "tag-" + i)).toList, "confused" ) @@ -80,7 +81,7 @@ class PetApiTest extends FlatSpec with Matchers { } it should "find pets by status" in { - api.findPetsByStatus("available") match { + api.findPetsByStatus(List("available")) match { case Some(pets) => { pets.foreach(pet => pet.status should be("available")) } @@ -90,7 +91,7 @@ class PetApiTest extends FlatSpec with Matchers { it should "find pets by tag" in { println("finding by tags") - api.findPetsByTags("tag1,tag2") match { + api.findPetsByTags(List("tag1", "tag2")) match { case Some(pets) => { pets.foreach(pet => { val tags = (for (tag <- pet.tags) yield tag.name).toSet diff --git a/samples/client/petstore/scala/src/test/scala/StoreApiTest.scala b/samples/client/petstore/scala/src/test/scala/StoreApiTest.scala index 2d453ab2255a..053dffd055d2 100644 --- a/samples/client/petstore/scala/src/test/scala/StoreApiTest.scala +++ b/samples/client/petstore/scala/src/test/scala/StoreApiTest.scala @@ -1,6 +1,6 @@ -import com.wordnik.client._ -import com.wordnik.petstore.api._ -import com.wordnik.petstore.model._ +import io.swagger.client._ +import io.swagger.client.api._ +import io.swagger.client.model._ import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner @@ -30,13 +30,14 @@ class StoreApiTest extends FlatSpec with Matchers { } it should "place an order" in { - val now = new java.util.Date + val now = new org.joda.time.DateTime val order = Order ( - 10, - 1000, - 101, - "pending", - now) + petId = 10, + id = 1000, + quantity = 101, + status = "pending", + shipDate = now, + complete = true) api.placeOrder(order) @@ -45,20 +46,21 @@ class StoreApiTest extends FlatSpec with Matchers { order.id should be(1000) order.petId should be(10) order.quantity should be(101) - order.shipDate should be (now) + order.shipDate.equals(now) should be (true) } case None => } } it should "delete an order" in { - val now = new java.util.Date + val now = new org.joda.time.DateTime val order = Order( - 1001, - 10, - 101, - "pending", - now) + id = 1001, + petId = 10, + quantity = 101, + status = "pending", + shipDate = now, + complete = true) api.placeOrder(order) @@ -67,7 +69,7 @@ class StoreApiTest extends FlatSpec with Matchers { order.id should be(1001) order.petId should be(10) order.quantity should be(101) - order.shipDate should be (now) + order.shipDate.equals(now) should be (true) } case None => } diff --git a/samples/client/petstore/scala/src/test/scala/UserApiTest.scala b/samples/client/petstore/scala/src/test/scala/UserApiTest.scala index 73f90342ad66..37b80815c87f 100644 --- a/samples/client/petstore/scala/src/test/scala/UserApiTest.scala +++ b/samples/client/petstore/scala/src/test/scala/UserApiTest.scala @@ -1,5 +1,6 @@ -import com.wordnik.petstore.api._ -import com.wordnik.petstore.model._ +import io.swagger.client._ +import io.swagger.client.api._ +import io.swagger.client.model._ import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner diff --git a/samples/client/petstore/tizen/client/SamiCategory.cpp b/samples/client/petstore/tizen/client/SamiCategory.cpp index 0e79da7bebd4..def45c657882 100644 --- a/samples/client/petstore/tizen/client/SamiCategory.cpp +++ b/samples/client/petstore/tizen/client/SamiCategory.cpp @@ -148,31 +148,31 @@ SamiCategory::asJsonObject() { JsonString *pIdKey = new JsonString(L"id"); - pJsonObject->Add(pIdKey, toJson(getId(), "Long", "")); + pJsonObject->Add(pIdKey, toJson(getpId(), "Long", "")); JsonString *pNameKey = new JsonString(L"name"); - pJsonObject->Add(pNameKey, toJson(getName(), "String", "")); + pJsonObject->Add(pNameKey, toJson(getpName(), "String", "")); return pJsonObject; } Long* -SamiCategory::getId() { +SamiCategory::getpId() { return pId; } void -SamiCategory::setId(Long* pId) { +SamiCategory::setpId(Long* pId) { this->pId = pId; } String* -SamiCategory::getName() { +SamiCategory::getpName() { return pName; } void -SamiCategory::setName(String* pName) { +SamiCategory::setpName(String* pName) { this->pName = pName; } diff --git a/samples/client/petstore/tizen/client/SamiCategory.h b/samples/client/petstore/tizen/client/SamiCategory.h index 6cb056535827..17fb5370943a 100644 --- a/samples/client/petstore/tizen/client/SamiCategory.h +++ b/samples/client/petstore/tizen/client/SamiCategory.h @@ -42,11 +42,11 @@ public: SamiCategory* fromJson(String* obj); - Long* getId(); - void setId(Long* pId); + Long* getpId(); + void setpId(Long* pId); - String* getName(); - void setName(String* pName); + String* getpName(); + void setpName(String* pName); private: diff --git a/samples/client/petstore/tizen/client/SamiOrder.cpp b/samples/client/petstore/tizen/client/SamiOrder.cpp index 35da0ca6de35..b029b2aeefe1 100644 --- a/samples/client/petstore/tizen/client/SamiOrder.cpp +++ b/samples/client/petstore/tizen/client/SamiOrder.cpp @@ -208,83 +208,83 @@ SamiOrder::asJsonObject() { JsonString *pIdKey = new JsonString(L"id"); - pJsonObject->Add(pIdKey, toJson(getId(), "Long", "")); + pJsonObject->Add(pIdKey, toJson(getpId(), "Long", "")); JsonString *pPetIdKey = new JsonString(L"petId"); - pJsonObject->Add(pPetIdKey, toJson(getPetId(), "Long", "")); + pJsonObject->Add(pPetIdKey, toJson(getpPetId(), "Long", "")); JsonString *pQuantityKey = new JsonString(L"quantity"); - pJsonObject->Add(pQuantityKey, toJson(getQuantity(), "Integer", "")); + pJsonObject->Add(pQuantityKey, toJson(getpQuantity(), "Integer", "")); JsonString *pShipDateKey = new JsonString(L"shipDate"); - pJsonObject->Add(pShipDateKey, toJson(getShipDate(), "DateTime", "")); + pJsonObject->Add(pShipDateKey, toJson(getpShipDate(), "DateTime", "")); JsonString *pStatusKey = new JsonString(L"status"); - pJsonObject->Add(pStatusKey, toJson(getStatus(), "String", "")); + pJsonObject->Add(pStatusKey, toJson(getpStatus(), "String", "")); JsonString *pCompleteKey = new JsonString(L"complete"); - pJsonObject->Add(pCompleteKey, toJson(getComplete(), "Boolean", "")); + pJsonObject->Add(pCompleteKey, toJson(getpComplete(), "Boolean", "")); return pJsonObject; } Long* -SamiOrder::getId() { +SamiOrder::getpId() { return pId; } void -SamiOrder::setId(Long* pId) { +SamiOrder::setpId(Long* pId) { this->pId = pId; } Long* -SamiOrder::getPetId() { +SamiOrder::getpPetId() { return pPetId; } void -SamiOrder::setPetId(Long* pPetId) { +SamiOrder::setpPetId(Long* pPetId) { this->pPetId = pPetId; } Integer* -SamiOrder::getQuantity() { +SamiOrder::getpQuantity() { return pQuantity; } void -SamiOrder::setQuantity(Integer* pQuantity) { +SamiOrder::setpQuantity(Integer* pQuantity) { this->pQuantity = pQuantity; } DateTime* -SamiOrder::getShipDate() { +SamiOrder::getpShipDate() { return pShipDate; } void -SamiOrder::setShipDate(DateTime* pShipDate) { +SamiOrder::setpShipDate(DateTime* pShipDate) { this->pShipDate = pShipDate; } String* -SamiOrder::getStatus() { +SamiOrder::getpStatus() { return pStatus; } void -SamiOrder::setStatus(String* pStatus) { +SamiOrder::setpStatus(String* pStatus) { this->pStatus = pStatus; } Boolean* -SamiOrder::getComplete() { +SamiOrder::getpComplete() { return pComplete; } void -SamiOrder::setComplete(Boolean* pComplete) { +SamiOrder::setpComplete(Boolean* pComplete) { this->pComplete = pComplete; } diff --git a/samples/client/petstore/tizen/client/SamiOrder.h b/samples/client/petstore/tizen/client/SamiOrder.h index 88dcda673953..bc1cf4af226c 100644 --- a/samples/client/petstore/tizen/client/SamiOrder.h +++ b/samples/client/petstore/tizen/client/SamiOrder.h @@ -45,23 +45,23 @@ public: SamiOrder* fromJson(String* obj); - Long* getId(); - void setId(Long* pId); + Long* getpId(); + void setpId(Long* pId); - Long* getPetId(); - void setPetId(Long* pPetId); + Long* getpPetId(); + void setpPetId(Long* pPetId); - Integer* getQuantity(); - void setQuantity(Integer* pQuantity); + Integer* getpQuantity(); + void setpQuantity(Integer* pQuantity); - DateTime* getShipDate(); - void setShipDate(DateTime* pShipDate); + DateTime* getpShipDate(); + void setpShipDate(DateTime* pShipDate); - String* getStatus(); - void setStatus(String* pStatus); + String* getpStatus(); + void setpStatus(String* pStatus); - Boolean* getComplete(); - void setComplete(Boolean* pComplete); + Boolean* getpComplete(); + void setpComplete(Boolean* pComplete); private: diff --git a/samples/client/petstore/tizen/client/SamiPet.cpp b/samples/client/petstore/tizen/client/SamiPet.cpp index c45c850e35d7..6c5d101db434 100644 --- a/samples/client/petstore/tizen/client/SamiPet.cpp +++ b/samples/client/petstore/tizen/client/SamiPet.cpp @@ -208,83 +208,83 @@ SamiPet::asJsonObject() { JsonString *pIdKey = new JsonString(L"id"); - pJsonObject->Add(pIdKey, toJson(getId(), "Long", "")); + pJsonObject->Add(pIdKey, toJson(getpId(), "Long", "")); JsonString *pCategoryKey = new JsonString(L"category"); - pJsonObject->Add(pCategoryKey, toJson(getCategory(), "SamiCategory", "")); + pJsonObject->Add(pCategoryKey, toJson(getpCategory(), "SamiCategory", "")); JsonString *pNameKey = new JsonString(L"name"); - pJsonObject->Add(pNameKey, toJson(getName(), "String", "")); + pJsonObject->Add(pNameKey, toJson(getpName(), "String", "")); JsonString *pPhotoUrlsKey = new JsonString(L"photoUrls"); - pJsonObject->Add(pPhotoUrlsKey, toJson(getPhotoUrls(), "String", "array")); + pJsonObject->Add(pPhotoUrlsKey, toJson(getpPhotoUrls(), "String", "array")); JsonString *pTagsKey = new JsonString(L"tags"); - pJsonObject->Add(pTagsKey, toJson(getTags(), "SamiTag", "array")); + pJsonObject->Add(pTagsKey, toJson(getpTags(), "SamiTag", "array")); JsonString *pStatusKey = new JsonString(L"status"); - pJsonObject->Add(pStatusKey, toJson(getStatus(), "String", "")); + pJsonObject->Add(pStatusKey, toJson(getpStatus(), "String", "")); return pJsonObject; } Long* -SamiPet::getId() { +SamiPet::getpId() { return pId; } void -SamiPet::setId(Long* pId) { +SamiPet::setpId(Long* pId) { this->pId = pId; } SamiCategory* -SamiPet::getCategory() { +SamiPet::getpCategory() { return pCategory; } void -SamiPet::setCategory(SamiCategory* pCategory) { +SamiPet::setpCategory(SamiCategory* pCategory) { this->pCategory = pCategory; } String* -SamiPet::getName() { +SamiPet::getpName() { return pName; } void -SamiPet::setName(String* pName) { +SamiPet::setpName(String* pName) { this->pName = pName; } IList* -SamiPet::getPhotoUrls() { +SamiPet::getpPhotoUrls() { return pPhotoUrls; } void -SamiPet::setPhotoUrls(IList* pPhotoUrls) { +SamiPet::setpPhotoUrls(IList* pPhotoUrls) { this->pPhotoUrls = pPhotoUrls; } IList* -SamiPet::getTags() { +SamiPet::getpTags() { return pTags; } void -SamiPet::setTags(IList* pTags) { +SamiPet::setpTags(IList* pTags) { this->pTags = pTags; } String* -SamiPet::getStatus() { +SamiPet::getpStatus() { return pStatus; } void -SamiPet::setStatus(String* pStatus) { +SamiPet::setpStatus(String* pStatus) { this->pStatus = pStatus; } diff --git a/samples/client/petstore/tizen/client/SamiPet.h b/samples/client/petstore/tizen/client/SamiPet.h index 9e3ab43bdc7b..30ae88729491 100644 --- a/samples/client/petstore/tizen/client/SamiPet.h +++ b/samples/client/petstore/tizen/client/SamiPet.h @@ -45,23 +45,23 @@ public: SamiPet* fromJson(String* obj); - Long* getId(); - void setId(Long* pId); + Long* getpId(); + void setpId(Long* pId); - SamiCategory* getCategory(); - void setCategory(SamiCategory* pCategory); + SamiCategory* getpCategory(); + void setpCategory(SamiCategory* pCategory); - String* getName(); - void setName(String* pName); + String* getpName(); + void setpName(String* pName); - IList* getPhotoUrls(); - void setPhotoUrls(IList* pPhotoUrls); + IList* getpPhotoUrls(); + void setpPhotoUrls(IList* pPhotoUrls); - IList* getTags(); - void setTags(IList* pTags); + IList* getpTags(); + void setpTags(IList* pTags); - String* getStatus(); - void setStatus(String* pStatus); + String* getpStatus(); + void setpStatus(String* pStatus); private: diff --git a/samples/client/petstore/tizen/client/SamiTag.cpp b/samples/client/petstore/tizen/client/SamiTag.cpp index 61cc00f35fe5..3e6b947c6040 100644 --- a/samples/client/petstore/tizen/client/SamiTag.cpp +++ b/samples/client/petstore/tizen/client/SamiTag.cpp @@ -148,31 +148,31 @@ SamiTag::asJsonObject() { JsonString *pIdKey = new JsonString(L"id"); - pJsonObject->Add(pIdKey, toJson(getId(), "Long", "")); + pJsonObject->Add(pIdKey, toJson(getpId(), "Long", "")); JsonString *pNameKey = new JsonString(L"name"); - pJsonObject->Add(pNameKey, toJson(getName(), "String", "")); + pJsonObject->Add(pNameKey, toJson(getpName(), "String", "")); return pJsonObject; } Long* -SamiTag::getId() { +SamiTag::getpId() { return pId; } void -SamiTag::setId(Long* pId) { +SamiTag::setpId(Long* pId) { this->pId = pId; } String* -SamiTag::getName() { +SamiTag::getpName() { return pName; } void -SamiTag::setName(String* pName) { +SamiTag::setpName(String* pName) { this->pName = pName; } diff --git a/samples/client/petstore/tizen/client/SamiTag.h b/samples/client/petstore/tizen/client/SamiTag.h index 53a4134a51d8..af77f48ec48c 100644 --- a/samples/client/petstore/tizen/client/SamiTag.h +++ b/samples/client/petstore/tizen/client/SamiTag.h @@ -42,11 +42,11 @@ public: SamiTag* fromJson(String* obj); - Long* getId(); - void setId(Long* pId); + Long* getpId(); + void setpId(Long* pId); - String* getName(); - void setName(String* pName); + String* getpName(); + void setpName(String* pName); private: diff --git a/samples/client/petstore/tizen/client/SamiUser.cpp b/samples/client/petstore/tizen/client/SamiUser.cpp index 9701a45f28c5..48c615e008d5 100644 --- a/samples/client/petstore/tizen/client/SamiUser.cpp +++ b/samples/client/petstore/tizen/client/SamiUser.cpp @@ -238,109 +238,109 @@ SamiUser::asJsonObject() { JsonString *pIdKey = new JsonString(L"id"); - pJsonObject->Add(pIdKey, toJson(getId(), "Long", "")); + pJsonObject->Add(pIdKey, toJson(getpId(), "Long", "")); JsonString *pUsernameKey = new JsonString(L"username"); - pJsonObject->Add(pUsernameKey, toJson(getUsername(), "String", "")); + pJsonObject->Add(pUsernameKey, toJson(getpUsername(), "String", "")); JsonString *pFirstNameKey = new JsonString(L"firstName"); - pJsonObject->Add(pFirstNameKey, toJson(getFirstName(), "String", "")); + pJsonObject->Add(pFirstNameKey, toJson(getpFirstName(), "String", "")); JsonString *pLastNameKey = new JsonString(L"lastName"); - pJsonObject->Add(pLastNameKey, toJson(getLastName(), "String", "")); + pJsonObject->Add(pLastNameKey, toJson(getpLastName(), "String", "")); JsonString *pEmailKey = new JsonString(L"email"); - pJsonObject->Add(pEmailKey, toJson(getEmail(), "String", "")); + pJsonObject->Add(pEmailKey, toJson(getpEmail(), "String", "")); JsonString *pPasswordKey = new JsonString(L"password"); - pJsonObject->Add(pPasswordKey, toJson(getPassword(), "String", "")); + pJsonObject->Add(pPasswordKey, toJson(getpPassword(), "String", "")); JsonString *pPhoneKey = new JsonString(L"phone"); - pJsonObject->Add(pPhoneKey, toJson(getPhone(), "String", "")); + pJsonObject->Add(pPhoneKey, toJson(getpPhone(), "String", "")); JsonString *pUserStatusKey = new JsonString(L"userStatus"); - pJsonObject->Add(pUserStatusKey, toJson(getUserStatus(), "Integer", "")); + pJsonObject->Add(pUserStatusKey, toJson(getpUserStatus(), "Integer", "")); return pJsonObject; } Long* -SamiUser::getId() { +SamiUser::getpId() { return pId; } void -SamiUser::setId(Long* pId) { +SamiUser::setpId(Long* pId) { this->pId = pId; } String* -SamiUser::getUsername() { +SamiUser::getpUsername() { return pUsername; } void -SamiUser::setUsername(String* pUsername) { +SamiUser::setpUsername(String* pUsername) { this->pUsername = pUsername; } String* -SamiUser::getFirstName() { +SamiUser::getpFirstName() { return pFirstName; } void -SamiUser::setFirstName(String* pFirstName) { +SamiUser::setpFirstName(String* pFirstName) { this->pFirstName = pFirstName; } String* -SamiUser::getLastName() { +SamiUser::getpLastName() { return pLastName; } void -SamiUser::setLastName(String* pLastName) { +SamiUser::setpLastName(String* pLastName) { this->pLastName = pLastName; } String* -SamiUser::getEmail() { +SamiUser::getpEmail() { return pEmail; } void -SamiUser::setEmail(String* pEmail) { +SamiUser::setpEmail(String* pEmail) { this->pEmail = pEmail; } String* -SamiUser::getPassword() { +SamiUser::getpPassword() { return pPassword; } void -SamiUser::setPassword(String* pPassword) { +SamiUser::setpPassword(String* pPassword) { this->pPassword = pPassword; } String* -SamiUser::getPhone() { +SamiUser::getpPhone() { return pPhone; } void -SamiUser::setPhone(String* pPhone) { +SamiUser::setpPhone(String* pPhone) { this->pPhone = pPhone; } Integer* -SamiUser::getUserStatus() { +SamiUser::getpUserStatus() { return pUserStatus; } void -SamiUser::setUserStatus(Integer* pUserStatus) { +SamiUser::setpUserStatus(Integer* pUserStatus) { this->pUserStatus = pUserStatus; } diff --git a/samples/client/petstore/tizen/client/SamiUser.h b/samples/client/petstore/tizen/client/SamiUser.h index dd24429dbab1..24cc7b55638e 100644 --- a/samples/client/petstore/tizen/client/SamiUser.h +++ b/samples/client/petstore/tizen/client/SamiUser.h @@ -43,29 +43,29 @@ public: SamiUser* fromJson(String* obj); - Long* getId(); - void setId(Long* pId); + Long* getpId(); + void setpId(Long* pId); - String* getUsername(); - void setUsername(String* pUsername); + String* getpUsername(); + void setpUsername(String* pUsername); - String* getFirstName(); - void setFirstName(String* pFirstName); + String* getpFirstName(); + void setpFirstName(String* pFirstName); - String* getLastName(); - void setLastName(String* pLastName); + String* getpLastName(); + void setpLastName(String* pLastName); - String* getEmail(); - void setEmail(String* pEmail); + String* getpEmail(); + void setpEmail(String* pEmail); - String* getPassword(); - void setPassword(String* pPassword); + String* getpPassword(); + void setpPassword(String* pPassword); - String* getPhone(); - void setPhone(String* pPhone); + String* getpPhone(); + void setpPhone(String* pPhone); - Integer* getUserStatus(); - void setUserStatus(Integer* pUserStatus); + Integer* getpUserStatus(); + void setpUserStatus(Integer* pUserStatus); private: diff --git a/samples/server/petstore/jaxrs/pom.xml b/samples/server/petstore/jaxrs/pom.xml index fa94509ad550..0a7f0f935c76 100644 --- a/samples/server/petstore/jaxrs/pom.xml +++ b/samples/server/petstore/jaxrs/pom.xml @@ -123,8 +123,17 @@ ${servlet-api-version} + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + - 1.5.1-M1 + 1.5.3-M1-SNAPSHOT 8.1.11.v20130520 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 bdf4ecec3d69..d3a57a3ad00b 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 @@ -64,6 +64,8 @@ public class PetApi { @Produces({ "application/json", "application/xml" }) @com.wordnik.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", response = Pet.class, responseContainer = "List") @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value") }) public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter") @QueryParam("status") List status) @@ -79,6 +81,8 @@ public class PetApi { @Produces({ "application/json", "application/xml" }) @com.wordnik.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List") @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value") }) public Response findPetsByTags(@ApiParam(value = "Tags to filter by") @QueryParam("tags") List tags) @@ -96,6 +100,8 @@ public class PetApi { @com.wordnik.swagger.annotations.ApiResponses(value = { @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "Pet not found"), + @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) public Response getPetById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathParam("petId") Long petId) @@ -143,7 +149,8 @@ public class PetApi { @Consumes({ "multipart/form-data" }) @Produces({ "application/json", "application/xml" }) @com.wordnik.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { }) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathParam("petId") Long petId, @ApiParam(value = "Additional data to pass to server" )@FormParam("additionalMetadata") String additionalMetadata, 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 a61879188c12..d2bde7cf35b1 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 @@ -29,7 +29,8 @@ public class StoreApi { @Produces({ "application/json", "application/xml" }) @com.wordnik.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "map") - @com.wordnik.swagger.annotations.ApiResponses(value = { }) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation") }) public Response getInventory() throws NotFoundException { @@ -44,6 +45,8 @@ public class StoreApi { @Produces({ "application/json", "application/xml" }) @com.wordnik.swagger.annotations.ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class) @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order") }) public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ) Order body) @@ -61,6 +64,8 @@ public class StoreApi { @com.wordnik.swagger.annotations.ApiResponses(value = { @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "Order not found"), + @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied") }) public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathParam("orderId") String orderId) 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 2bccc374bf9c..3f6da2c5d920 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 @@ -29,7 +29,8 @@ public class UserApi { @Produces({ "application/json", "application/xml" }) @com.wordnik.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { }) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) public Response createUser(@ApiParam(value = "Created user object" ) User body) throws NotFoundException { @@ -43,7 +44,8 @@ public class UserApi { @Produces({ "application/json", "application/xml" }) @com.wordnik.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { }) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ) List body) throws NotFoundException { @@ -57,7 +59,8 @@ public class UserApi { @Produces({ "application/json", "application/xml" }) @com.wordnik.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { }) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) public Response createUsersWithListInput(@ApiParam(value = "List of user object" ) List body) throws NotFoundException { @@ -72,6 +75,8 @@ public class UserApi { @Produces({ "application/json", "application/xml" }) @com.wordnik.swagger.annotations.ApiOperation(value = "Logs user into the system", notes = "", response = String.class) @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied") }) public Response loginUser(@ApiParam(value = "The user name for login") @QueryParam("username") String username, @@ -87,7 +92,8 @@ public class UserApi { @Produces({ "application/json", "application/xml" }) @com.wordnik.swagger.annotations.ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) - @com.wordnik.swagger.annotations.ApiResponses(value = { }) + @com.wordnik.swagger.annotations.ApiResponses(value = { + @com.wordnik.swagger.annotations.ApiResponse(code = 0, message = "successful operation") }) public Response logoutUser() throws NotFoundException { @@ -104,6 +110,8 @@ public class UserApi { @com.wordnik.swagger.annotations.ApiResponses(value = { @com.wordnik.swagger.annotations.ApiResponse(code = 404, message = "User not found"), + @com.wordnik.swagger.annotations.ApiResponse(code = 200, message = "successful operation"), + @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied") }) public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathParam("username") String username) diff --git a/samples/server/petstore/nodejs/README.md b/samples/server/petstore/nodejs/README.md deleted file mode 100644 index ac6dc37d3dc0..000000000000 --- a/samples/server/petstore/nodejs/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# Swagger generated server - -## Overview -This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-spec) from a remote server, you can easily generate a server stub. This is an example of building a node.js server. - -This example uses the [expressjs](http://expressjs.com/) framework. To see how to make this your own, look here: - -[README](https://github.com/wordnik/swagger-codegen/README.md) \ No newline at end of file diff --git a/samples/server/petstore/nodejs/api/swagger.json b/samples/server/petstore/nodejs/api/swagger.json new file mode 100644 index 000000000000..6880eb186846 --- /dev/null +++ b/samples/server/petstore/nodejs/api/swagger.json @@ -0,0 +1,559 @@ +{ + "swagger": "2.0", + "info": { + "title": "Swagger Petstore", + "description": "This is a sample server Petstore server. You can find out more about Swagger at <a href="http://swagger.io">http://swagger.io</a> 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" + }, + "produces": [ + "application/json" + ], + "host": "localhost:8080", + "basePath": "/v2", + "paths": { + "/user": { + "post": { + "x-swagger-router-controller": "User", + "tags": [ + "User" + ], + "operationId": "createUser", + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Created user object", + "required": false, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/createWithArray": { + "post": { + "x-swagger-router-controller": "User", + "tags": [ + "User" + ], + "operationId": "createUsersWithArrayInput", + "parameters": [ + { + "in": "body", + "name": "body", + "description": "List of user object", + "required": false, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/User" + } + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/createWithList": { + "post": { + "x-swagger-router-controller": "User", + "tags": [ + "User" + ], + "operationId": "createUsersWithListInput", + "parameters": [ + { + "in": "body", + "name": "body", + "description": "List of user object", + "required": false, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/User" + } + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/login": { + "get": { + "x-swagger-router-controller": "User", + "tags": [ + "User" + ], + "operationId": "loginUser", + "parameters": [ + { + "name": "username", + "in": "query", + "description": "The user name for login", + "required": false, + "type": "string" + }, + { + "name": "password", + "in": "query", + "description": "The password for login in clear text", + "required": false, + "type": "string" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "string" + } + }, + "400": { + "description": "Invalid username/password supplied" + } + } + } + }, + "/user/logout": { + "get": { + "x-swagger-router-controller": "User", + "tags": [ + "User" + ], + "operationId": "logoutUser", + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/{username}": { + "delete": { + "x-swagger-router-controller": "User", + "tags": [ + "User" + ], + "operationId": "deleteUser", + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be deleted", + "required": true, + "type": "string" + } + ], + "responses": { + "404": { + "description": "User not found" + }, + "400": { + "description": "Invalid username supplied" + } + } + } + }, + "/pet": { + "post": { + "x-swagger-router-controller": "Pet", + "tags": [ + "Pet" + ], + "operationId": "addPet", + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Pet object that needs to be added to the store", + "required": false, + "schema": { + "$ref": "#/definitions/Pet" + } + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + } + } + }, + "/pet/findByStatus": { + "get": { + "x-swagger-router-controller": "Pet", + "tags": [ + "Pet" + ], + "operationId": "findPetsByStatus", + "parameters": [ + { + "name": "status", + "in": "query", + "description": "Status values that need to be considered for filter", + "required": false, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "multi", + "default": "available" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "400": { + "description": "Invalid status value" + } + } + } + }, + "/pet/findByTags": { + "get": { + "x-swagger-router-controller": "Pet", + "tags": [ + "Pet" + ], + "operationId": "findPetsByTags", + "parameters": [ + { + "name": "tags", + "in": "query", + "description": "Tags to filter by", + "required": false, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "multi" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "400": { + "description": "Invalid tag value" + } + } + } + }, + "/pet/{petId}": { + "delete": { + "x-swagger-router-controller": "Pet", + "tags": [ + "Pet" + ], + "operationId": "deletePet", + "parameters": [ + { + "name": "api_key", + "in": "header", + "description": "", + "required": false, + "type": "string" + }, + { + "name": "petId", + "in": "path", + "description": "Pet id to delete", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "400": { + "description": "Invalid pet value" + } + } + } + }, + "/pet/{petId}/uploadImage": { + "post": { + "x-swagger-router-controller": "Pet", + "tags": [ + "Pet" + ], + "operationId": "uploadFile", + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet to update", + "required": true, + "type": "integer", + "format": "int64" + }, + { + "name": "additionalMetadata", + "in": "formData", + "description": "Additional data to pass to server", + "required": false, + "type": "string" + }, + { + "name": "file", + "in": "formData", + "description": "file to upload", + "required": false, + "type": "file" + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/store/inventory": { + "get": { + "x-swagger-router-controller": "Store", + "tags": [ + "Store" + ], + "operationId": "getInventory", + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "object", + "additionalProperties": { + "type": "integer", + "format": "int32" + } + } + } + } + } + }, + "/store/order": { + "post": { + "x-swagger-router-controller": "Store", + "tags": [ + "Store" + ], + "operationId": "placeOrder", + "parameters": [ + { + "in": "body", + "name": "body", + "description": "order placed for purchasing the pet", + "required": false, + "schema": { + "$ref": "#/definitions/Order" + } + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Order" + } + }, + "400": { + "description": "Invalid Order" + } + } + } + }, + "/store/order/{orderId}": { + "delete": { + "x-swagger-router-controller": "Store", + "tags": [ + "Store" + ], + "operationId": "deleteOrder", + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of the order that needs to be deleted", + "required": true, + "type": "string" + } + ], + "responses": { + "404": { + "description": "Order not found" + }, + "400": { + "description": "Invalid ID supplied" + } + } + } + } + }, + "definitions": { + "User": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "username": { + "type": "string" + }, + "firstName": { + "type": "string" + }, + "lastName": { + "type": "string" + }, + "email": { + "type": "string" + }, + "password": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "userStatus": { + "type": "integer", + "format": "int32", + "description": "User Status" + } + }, + "xml": { + "name": "User" + } + }, + "Category": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Category" + } + }, + "Pet": { + "required": [ + "name", + "photoUrls" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "category": { + "$ref": "#/definitions/Category" + }, + "name": { + "type": "string", + "example": "doggie" + }, + "photoUrls": { + "type": "array", + "items": { + "type": "string" + } + }, + "tags": { + "type": "array", + "items": { + "$ref": "#/definitions/Tag" + } + }, + "status": { + "type": "string", + "description": "pet status in the store", + "enum": [ + "available", + "pending", + "sold" + ] + } + }, + "xml": { + "name": "Pet" + } + }, + "Tag": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Tag" + } + }, + "Order": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "petId": { + "type": "integer", + "format": "int64" + }, + "quantity": { + "type": "integer", + "format": "int32" + }, + "shipDate": { + "type": "string", + "format": "date-time" + }, + "status": { + "type": "string", + "description": "Order Status", + "enum": [ + "placed", + "approved", + "delivered" + ] + }, + "complete": { + "type": "boolean" + } + }, + "xml": { + "name": "Order" + } + } + } +} \ No newline at end of file diff --git a/samples/server/petstore/nodejs/app/apis/PetApi.js b/samples/server/petstore/nodejs/app/apis/PetApi.js deleted file mode 100644 index 630b32359562..000000000000 --- a/samples/server/petstore/nodejs/app/apis/PetApi.js +++ /dev/null @@ -1,203 +0,0 @@ -var swagger = require("swagger-node-express"); -var url = require("url"); -var errors = swagger.errors; -var params = swagger.params; - -/* add model includes */ - -function writeResponse (response, data) { - response.header('Access-Control-Allow-Origin', "*"); - response.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); - response.header("Access-Control-Allow-Headers", "Content-Type"); - response.header("Content-Type", "application/json; charset=utf-8"); - response.send(JSON.stringify(data)); -} - -exports.models = models = require("../models.js"); - -exports.updatePet = { - 'spec': { - "description" : "Operations about pets", - "path" : "/pet", - "notes" : "", - "summary" : "Update an existing pet", - "method": "PUT", - "params" : [].concat([]).concat([]).concat([ - params.body("body", "", "Pet object that needs to be added to the store", false) - ]), - - - "type" : "", - - "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "updatePet" - }, - 'action': function (req,res) { - - writeResponse(res, {message: "how about implementing updatePet as a PUT method?"}); - } -}; -exports.addPet = { - 'spec': { - "description" : "Operations about pets", - "path" : "/pet", - "notes" : "", - "summary" : "Add a new pet to the store", - "method": "POST", - "params" : [].concat([]).concat([]).concat([ - params.body("body", "", "Pet object that needs to be added to the store", false) - ]), - - - "type" : "", - - "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "addPet" - }, - 'action': function (req,res) { - - writeResponse(res, {message: "how about implementing addPet as a POST method?"}); - } -}; -exports.findPetsByStatus = { - 'spec': { - "description" : "Operations about pets", - "path" : "/pet/findByStatus", - "notes" : "Multiple status values can be provided with comma seperated strings", - "summary" : "Finds Pets by status", - "method": "GET", - "params" : [ - params.query("status", "Status values that need to be considered for filter", "", false, false, "") - ].concat([]).concat([]).concat([]), - - "type": "array", - "items": { - - "$ref": "array" - }, - // container - - - "responseMessages" : [errors.invalid('id'), errors.notFound('array')], - "nickname" : "findPetsByStatus" - }, - 'action': function (req,res) { - - writeResponse(res, {message: "how about implementing findPetsByStatus as a GET method?"}); - } -}; -exports.findPetsByTags = { - 'spec': { - "description" : "Operations about pets", - "path" : "/pet/findByTags", - "notes" : "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", - "summary" : "Finds Pets by tags", - "method": "GET", - "params" : [ - params.query("tags", "Tags to filter by", "", false, false, "") - ].concat([]).concat([]).concat([]), - - "type": "array", - "items": { - - "$ref": "array" - }, - // container - - - "responseMessages" : [errors.invalid('id'), errors.notFound('array')], - "nickname" : "findPetsByTags" - }, - 'action': function (req,res) { - - writeResponse(res, {message: "how about implementing findPetsByTags as a GET method?"}); - } -}; -exports.getPetById = { - 'spec': { - "description" : "Operations about pets", - "path" : "/pet/{petId}", - "notes" : "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", - "summary" : "Find pet by ID", - "method": "GET", - "params" : [].concat([ - params.path("petId", "ID of pet that needs to be fetched") - ]).concat([]).concat([]), - - - "type" : "Pet", - - "responseMessages" : [errors.invalid('id'), errors.notFound('Pet')], - "nickname" : "getPetById" - }, - 'action': function (req,res) { - - writeResponse(res, {message: "how about implementing getPetById as a GET method?"}); - } -}; -exports.updatePetWithForm = { - 'spec': { - "description" : "Operations about pets", - "path" : "/pet/{petId}", - "notes" : "", - "summary" : "Updates a pet in the store with form data", - "method": "POST", - "params" : [].concat([ - params.path("petId", "ID of pet that needs to be updated") - ]).concat([]).concat([]), - - - "type" : "", - - "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "updatePetWithForm" - }, - 'action': function (req,res) { - - writeResponse(res, {message: "how about implementing updatePetWithForm as a POST method?"}); - } -}; -exports.deletePet = { - 'spec': { - "description" : "Operations about pets", - "path" : "/pet/{petId}", - "notes" : "", - "summary" : "Deletes a pet", - "method": "DELETE", - "params" : [].concat([ - params.path("petId", "Pet id to delete") - ]).concat([ - params.header("api_key", "") - ]).concat([]), - - - "type" : "", - - "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "deletePet" - }, - 'action': function (req,res) { - - writeResponse(res, {message: "how about implementing deletePet as a DELETE method?"}); - } -}; -exports.uploadFile = { - 'spec': { - "description" : "Operations about pets", - "path" : "/pet/{petId}/uploadImage", - "notes" : "", - "summary" : "uploads an image", - "method": "POST", - "params" : [].concat([]).concat([]).concat([]), - - - "type" : "", - - "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "uploadFile" - }, - 'action': function (req,res) { - - writeResponse(res, {message: "how about implementing uploadFile as a POST method?"}); - } -}; diff --git a/samples/server/petstore/nodejs/app/apis/StoreApi.js b/samples/server/petstore/nodejs/app/apis/StoreApi.js deleted file mode 100644 index bbe929bd492c..000000000000 --- a/samples/server/petstore/nodejs/app/apis/StoreApi.js +++ /dev/null @@ -1,108 +0,0 @@ -var swagger = require("swagger-node-express"); -var url = require("url"); -var errors = swagger.errors; -var params = swagger.params; - -/* add model includes */ - -function writeResponse (response, data) { - response.header('Access-Control-Allow-Origin', "*"); - response.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); - response.header("Access-Control-Allow-Headers", "Content-Type"); - response.header("Content-Type", "application/json; charset=utf-8"); - response.send(JSON.stringify(data)); -} - -exports.models = models = require("../models.js"); - -exports.getInventory = { - 'spec': { - "description" : "Operations about pets", - "path" : "/store/inventory", - "notes" : "Returns a map of status codes to quantities", - "summary" : "Returns pet inventories by status", - "method": "GET", - "params" : [].concat([]).concat([]).concat([]), - - "type": "Map", - "items": { - - "$ref": "map" - }, - // container - - - "responseMessages" : [errors.invalid('id'), errors.notFound('Map')], - "nickname" : "getInventory" - }, - 'action': function (req,res) { - - writeResponse(res, {message: "how about implementing getInventory as a GET method?"}); - } -}; -exports.placeOrder = { - 'spec': { - "description" : "Operations about pets", - "path" : "/store/order", - "notes" : "", - "summary" : "Place an order for a pet", - "method": "POST", - "params" : [].concat([]).concat([]).concat([ - params.body("body", "", "order placed for purchasing the pet", false) - ]), - - - "type" : "Order", - - "responseMessages" : [errors.invalid('id'), errors.notFound('Order')], - "nickname" : "placeOrder" - }, - 'action': function (req,res) { - - writeResponse(res, {message: "how about implementing placeOrder as a POST method?"}); - } -}; -exports.getOrderById = { - 'spec': { - "description" : "Operations about pets", - "path" : "/store/order/{orderId}", - "notes" : "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", - "summary" : "Find purchase order by ID", - "method": "GET", - "params" : [].concat([ - params.path("orderId", "ID of pet that needs to be fetched") - ]).concat([]).concat([]), - - - "type" : "Order", - - "responseMessages" : [errors.invalid('id'), errors.notFound('Order')], - "nickname" : "getOrderById" - }, - 'action': function (req,res) { - - writeResponse(res, {message: "how about implementing getOrderById as a GET method?"}); - } -}; -exports.deleteOrder = { - 'spec': { - "description" : "Operations about pets", - "path" : "/store/order/{orderId}", - "notes" : "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", - "summary" : "Delete purchase order by ID", - "method": "DELETE", - "params" : [].concat([ - params.path("orderId", "ID of the order that needs to be deleted") - ]).concat([]).concat([]), - - - "type" : "", - - "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "deleteOrder" - }, - 'action': function (req,res) { - - writeResponse(res, {message: "how about implementing deleteOrder as a DELETE method?"}); - } -}; diff --git a/samples/server/petstore/nodejs/app/apis/UserApi.js b/samples/server/petstore/nodejs/app/apis/UserApi.js deleted file mode 100644 index 02a17bff0870..000000000000 --- a/samples/server/petstore/nodejs/app/apis/UserApi.js +++ /dev/null @@ -1,195 +0,0 @@ -var swagger = require("swagger-node-express"); -var url = require("url"); -var errors = swagger.errors; -var params = swagger.params; - -/* add model includes */ - -function writeResponse (response, data) { - response.header('Access-Control-Allow-Origin', "*"); - response.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); - response.header("Access-Control-Allow-Headers", "Content-Type"); - response.header("Content-Type", "application/json; charset=utf-8"); - response.send(JSON.stringify(data)); -} - -exports.models = models = require("../models.js"); - -exports.createUser = { - 'spec': { - "description" : "Operations about pets", - "path" : "/user", - "notes" : "This can only be done by the logged in user.", - "summary" : "Create user", - "method": "POST", - "params" : [].concat([]).concat([]).concat([ - params.body("body", "", "Created user object", false) - ]), - - - "type" : "", - - "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "createUser" - }, - 'action': function (req,res) { - - writeResponse(res, {message: "how about implementing createUser as a POST method?"}); - } -}; -exports.createUsersWithArrayInput = { - 'spec': { - "description" : "Operations about pets", - "path" : "/user/createWithArray", - "notes" : "", - "summary" : "Creates list of users with given input array", - "method": "POST", - "params" : [].concat([]).concat([]).concat([ - params.body("body", "", "List of user object", false) - ]), - - - "type" : "", - - "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "createUsersWithArrayInput" - }, - 'action': function (req,res) { - - writeResponse(res, {message: "how about implementing createUsersWithArrayInput as a POST method?"}); - } -}; -exports.createUsersWithListInput = { - 'spec': { - "description" : "Operations about pets", - "path" : "/user/createWithList", - "notes" : "", - "summary" : "Creates list of users with given input array", - "method": "POST", - "params" : [].concat([]).concat([]).concat([ - params.body("body", "", "List of user object", false) - ]), - - - "type" : "", - - "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "createUsersWithListInput" - }, - 'action': function (req,res) { - - writeResponse(res, {message: "how about implementing createUsersWithListInput as a POST method?"}); - } -}; -exports.loginUser = { - 'spec': { - "description" : "Operations about pets", - "path" : "/user/login", - "notes" : "", - "summary" : "Logs user into the system", - "method": "GET", - "params" : [ - params.query("username", "The user name for login", "", false, false, ""), - - params.query("password", "The password for login in clear text", "", false, false, "") - ].concat([]).concat([]).concat([]), - - - "type" : "String", - - "responseMessages" : [errors.invalid('id'), errors.notFound('String')], - "nickname" : "loginUser" - }, - 'action': function (req,res) { - - writeResponse(res, {message: "how about implementing loginUser as a GET method?"}); - } -}; -exports.logoutUser = { - 'spec': { - "description" : "Operations about pets", - "path" : "/user/logout", - "notes" : "", - "summary" : "Logs out current logged in user session", - "method": "GET", - "params" : [].concat([]).concat([]).concat([]), - - - "type" : "", - - "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "logoutUser" - }, - 'action': function (req,res) { - - writeResponse(res, {message: "how about implementing logoutUser as a GET method?"}); - } -}; -exports.getUserByName = { - 'spec': { - "description" : "Operations about pets", - "path" : "/user/{username}", - "notes" : "", - "summary" : "Get user by user name", - "method": "GET", - "params" : [].concat([ - params.path("username", "The name that needs to be fetched. Use user1 for testing. ") - ]).concat([]).concat([]), - - - "type" : "User", - - "responseMessages" : [errors.invalid('id'), errors.notFound('User')], - "nickname" : "getUserByName" - }, - 'action': function (req,res) { - - writeResponse(res, {message: "how about implementing getUserByName as a GET method?"}); - } -}; -exports.updateUser = { - 'spec': { - "description" : "Operations about pets", - "path" : "/user/{username}", - "notes" : "This can only be done by the logged in user.", - "summary" : "Updated user", - "method": "PUT", - "params" : [].concat([ - params.path("username", "name that need to be deleted") - ]).concat([]).concat([ - params.body("body", "", "Updated user object", false) - ]), - - - "type" : "", - - "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "updateUser" - }, - 'action': function (req,res) { - - writeResponse(res, {message: "how about implementing updateUser as a PUT method?"}); - } -}; -exports.deleteUser = { - 'spec': { - "description" : "Operations about pets", - "path" : "/user/{username}", - "notes" : "This can only be done by the logged in user.", - "summary" : "Delete user", - "method": "DELETE", - "params" : [].concat([ - params.path("username", "The name that needs to be deleted") - ]).concat([]).concat([]), - - - "type" : "", - - "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "deleteUser" - }, - 'action': function (req,res) { - - writeResponse(res, {message: "how about implementing deleteUser as a DELETE method?"}); - } -}; diff --git a/samples/server/petstore/nodejs/app/models.js b/samples/server/petstore/nodejs/app/models.js deleted file mode 100644 index f54703af71d4..000000000000 --- a/samples/server/petstore/nodejs/app/models.js +++ /dev/null @@ -1,132 +0,0 @@ -exports.models = { - "User": { - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "username" : { - "type" : "string" - }, - "firstName" : { - "type" : "string" - }, - "lastName" : { - "type" : "string" - }, - "email" : { - "type" : "string" - }, - "password" : { - "type" : "string" - }, - "phone" : { - "type" : "string" - }, - "userStatus" : { - "type" : "integer", - "format" : "int32", - "description" : "User Status" - } - }, - "xml" : { - "name" : "User" - }, - "id" : "User" -},"Category": { - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "name" : { - "type" : "string" - } - }, - "xml" : { - "name" : "Category" - }, - "id" : "Category" -},"Pet": { - "required" : [ "name", "photoUrls" ], - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "category" : { - "$ref" : "Category" - }, - "name" : { - "type" : "string", - "example" : "doggie" - }, - "photoUrls" : { - "type" : "array", - "items" : { - "type" : "string" - } - }, - "tags" : { - "type" : "array", - "items" : { - "$ref" : "Tag" - } - }, - "status" : { - "type" : "string", - "description" : "pet status in the store", - "enum" : [ "available", "pending", "sold" ] - } - }, - "xml" : { - "name" : "Pet" - }, - "id" : "Pet" -},"Tag": { - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "name" : { - "type" : "string" - } - }, - "xml" : { - "name" : "Tag" - }, - "id" : "Tag" -},"Order": { - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "petId" : { - "type" : "integer", - "format" : "int64" - }, - "quantity" : { - "type" : "integer", - "format" : "int32" - }, - "shipDate" : { - "type" : "string", - "format" : "date-time" - }, - "status" : { - "type" : "string", - "description" : "Order Status", - "enum" : [ "placed", "approved", "delivered" ] - }, - "complete" : { - "type" : "boolean" - } - }, - "xml" : { - "name" : "Order" - }, - "id" : "Order" -} -} \ No newline at end of file diff --git a/samples/server/petstore/nodejs/controllers/Pet.js b/samples/server/petstore/nodejs/controllers/Pet.js new file mode 100644 index 000000000000..de5b166588bb --- /dev/null +++ b/samples/server/petstore/nodejs/controllers/Pet.js @@ -0,0 +1,124 @@ +'use strict'; + +var url = require('url'); + + +var Pet = require('./PetService'); + + +module.exports.updatePet = function updatePet (req, res, next) { + var body = req.swagger.params['body'].value; + + + var result = Pet.updatePet(body); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; + +module.exports.addPet = function addPet (req, res, next) { + var body = req.swagger.params['body'].value; + + + var result = Pet.addPet(body); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; + +module.exports.findPetsByStatus = function findPetsByStatus (req, res, next) { + var status = req.swagger.params['status'].value; + + + var result = Pet.findPetsByStatus(status); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; + +module.exports.findPetsByTags = function findPetsByTags (req, res, next) { + var tags = req.swagger.params['tags'].value; + + + var result = Pet.findPetsByTags(tags); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; + +module.exports.getPetById = function getPetById (req, res, next) { + var petId = req.swagger.params['petId'].value; + + + var result = Pet.getPetById(petId); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; + +module.exports.updatePetWithForm = function updatePetWithForm (req, res, next) { + var petId = req.swagger.params['petId'].value; + var name = req.swagger.params['name'].value; + var status = req.swagger.params['status'].value; + + + var result = Pet.updatePetWithForm(petId, name, status); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; + +module.exports.deletePet = function deletePet (req, res, next) { + var api_key = req.swagger.params['api_key'].value; + var petId = req.swagger.params['petId'].value; + + + var result = Pet.deletePet(api_key, petId); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; + +module.exports.uploadFile = function uploadFile (req, res, next) { + var petId = req.swagger.params['petId'].value; + var additionalMetadata = req.swagger.params['additionalMetadata'].value; + var file = req.swagger.params['file'].value; + + + var result = Pet.uploadFile(petId, additionalMetadata, file); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; diff --git a/samples/server/petstore/nodejs/controllers/PetService.js b/samples/server/petstore/nodejs/controllers/PetService.js new file mode 100644 index 000000000000..3e3deb958c45 --- /dev/null +++ b/samples/server/petstore/nodejs/controllers/PetService.js @@ -0,0 +1,112 @@ +'use strict'; + +exports.updatePet = function(body) { + + var examples = {}; + + + +} +exports.addPet = function(body) { + + var examples = {}; + + + +} +exports.findPetsByStatus = function(status) { + + var examples = {}; + + examples['application/json'] = [ { + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], + "id" : 123456789, + "category" : { + "id" : 123456789, + "name" : "aeiou" + }, + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +} ]; + + + + if(Object.keys(examples).length > 0) + return examples[Object.keys(examples)[0]]; + +} +exports.findPetsByTags = function(tags) { + + var examples = {}; + + examples['application/json'] = [ { + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], + "id" : 123456789, + "category" : { + "id" : 123456789, + "name" : "aeiou" + }, + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +} ]; + + + + if(Object.keys(examples).length > 0) + return examples[Object.keys(examples)[0]]; + +} +exports.getPetById = function(petId) { + + var examples = {}; + + examples['application/json'] = { + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], + "id" : 123456789, + "category" : { + "id" : 123456789, + "name" : "aeiou" + }, + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +}; + + + + if(Object.keys(examples).length > 0) + return examples[Object.keys(examples)[0]]; + +} +exports.updatePetWithForm = function(petId, name, status) { + + var examples = {}; + + + +} +exports.deletePet = function(api_key, petId) { + + var examples = {}; + + + +} +exports.uploadFile = function(petId, additionalMetadata, file) { + + var examples = {}; + + + +} diff --git a/samples/server/petstore/nodejs/controllers/Store.js b/samples/server/petstore/nodejs/controllers/Store.js new file mode 100644 index 000000000000..7059f9afa61d --- /dev/null +++ b/samples/server/petstore/nodejs/controllers/Store.js @@ -0,0 +1,62 @@ +'use strict'; + +var url = require('url'); + + +var Store = require('./StoreService'); + + +module.exports.getInventory = function getInventory (req, res, next) { + + + var result = Store.getInventory(); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; + +module.exports.placeOrder = function placeOrder (req, res, next) { + var body = req.swagger.params['body'].value; + + + var result = Store.placeOrder(body); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; + +module.exports.getOrderById = function getOrderById (req, res, next) { + var orderId = req.swagger.params['orderId'].value; + + + var result = Store.getOrderById(orderId); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; + +module.exports.deleteOrder = function deleteOrder (req, res, next) { + var orderId = req.swagger.params['orderId'].value; + + + var result = Store.deleteOrder(orderId); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; diff --git a/samples/server/petstore/nodejs/controllers/StoreService.js b/samples/server/petstore/nodejs/controllers/StoreService.js new file mode 100644 index 000000000000..1293843f0c6c --- /dev/null +++ b/samples/server/petstore/nodejs/controllers/StoreService.js @@ -0,0 +1,61 @@ +'use strict'; + +exports.getInventory = function() { + + var examples = {}; + + examples['application/json'] = { + "key" : 123 +}; + + + + if(Object.keys(examples).length > 0) + return examples[Object.keys(examples)[0]]; + +} +exports.placeOrder = function(body) { + + var examples = {}; + + examples['application/json'] = { + "id" : 123456789, + "petId" : 123456789, + "complete" : true, + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2015-03-19T21:51:51.599+0000" +}; + + + + if(Object.keys(examples).length > 0) + return examples[Object.keys(examples)[0]]; + +} +exports.getOrderById = function(orderId) { + + var examples = {}; + + examples['application/json'] = { + "id" : 123456789, + "petId" : 123456789, + "complete" : true, + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2015-03-19T21:51:51.603+0000" +}; + + + + if(Object.keys(examples).length > 0) + return examples[Object.keys(examples)[0]]; + +} +exports.deleteOrder = function(orderId) { + + var examples = {}; + + + +} diff --git a/samples/server/petstore/nodejs/controllers/User.js b/samples/server/petstore/nodejs/controllers/User.js new file mode 100644 index 000000000000..d89f34c9c3fd --- /dev/null +++ b/samples/server/petstore/nodejs/controllers/User.js @@ -0,0 +1,120 @@ +'use strict'; + +var url = require('url'); + + +var User = require('./UserService'); + + +module.exports.createUser = function createUser (req, res, next) { + var body = req.swagger.params['body'].value; + + + var result = User.createUser(body); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; + +module.exports.createUsersWithArrayInput = function createUsersWithArrayInput (req, res, next) { + var body = req.swagger.params['body'].value; + + + var result = User.createUsersWithArrayInput(body); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; + +module.exports.createUsersWithListInput = function createUsersWithListInput (req, res, next) { + var body = req.swagger.params['body'].value; + + + var result = User.createUsersWithListInput(body); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; + +module.exports.loginUser = function loginUser (req, res, next) { + var username = req.swagger.params['username'].value; + var password = req.swagger.params['password'].value; + + + var result = User.loginUser(username, password); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; + +module.exports.logoutUser = function logoutUser (req, res, next) { + + + var result = User.logoutUser(); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; + +module.exports.getUserByName = function getUserByName (req, res, next) { + var username = req.swagger.params['username'].value; + + + var result = User.getUserByName(username); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; + +module.exports.updateUser = function updateUser (req, res, next) { + var username = req.swagger.params['username'].value; + var body = req.swagger.params['body'].value; + + + var result = User.updateUser(username, body); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; + +module.exports.deleteUser = function deleteUser (req, res, next) { + var username = req.swagger.params['username'].value; + + + var result = User.deleteUser(username); + + if(typeof result !== 'undefined') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(result || {}, null, 2)); + } + else + res.end(); +}; diff --git a/samples/server/petstore/nodejs/controllers/UserService.js b/samples/server/petstore/nodejs/controllers/UserService.js new file mode 100644 index 000000000000..50676be64e95 --- /dev/null +++ b/samples/server/petstore/nodejs/controllers/UserService.js @@ -0,0 +1,77 @@ +'use strict'; + +exports.createUser = function(body) { + + var examples = {}; + + + +} +exports.createUsersWithArrayInput = function(body) { + + var examples = {}; + + + +} +exports.createUsersWithListInput = function(body) { + + var examples = {}; + + + +} +exports.loginUser = function(username, password) { + + var examples = {}; + + examples['application/json'] = "aeiou"; + + + + if(Object.keys(examples).length > 0) + return examples[Object.keys(examples)[0]]; + +} +exports.logoutUser = function() { + + var examples = {}; + + + +} +exports.getUserByName = function(username) { + + var examples = {}; + + examples['application/json'] = { + "id" : 123456789, + "lastName" : "aeiou", + "phone" : "aeiou", + "username" : "aeiou", + "email" : "aeiou", + "userStatus" : 123, + "firstName" : "aeiou", + "password" : "aeiou" +}; + + + + if(Object.keys(examples).length > 0) + return examples[Object.keys(examples)[0]]; + +} +exports.updateUser = function(username, body) { + + var examples = {}; + + + +} +exports.deleteUser = function(username) { + + var examples = {}; + + + +} diff --git a/samples/server/petstore/nodejs/index.js b/samples/server/petstore/nodejs/index.js new file mode 100644 index 000000000000..c73b630ed20a --- /dev/null +++ b/samples/server/petstore/nodejs/index.js @@ -0,0 +1,38 @@ +'use strict'; + +var app = require('connect')(); +var http = require('http'); +var swaggerTools = require('swagger-tools'); + +var serverPort = 8080; + +// swaggerRouter configuration +var options = { + swaggerUi: '/swagger.json', + controllers: './controllers', + useStubs: process.env.NODE_ENV === 'development' ? true : false // Conditionally turn on stubs (mock mode) +}; + +// The Swagger document (require it, build it programmatically, fetch it from a URL, ...) +var swaggerDoc = require('./api/swagger.json'); + +// Initialize the Swagger middleware +swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) { + // Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain + app.use(middleware.swaggerMetadata()); + + // Validate Swagger requests + app.use(middleware.swaggerValidator()); + + // Route validated requests to appropriate controller + app.use(middleware.swaggerRouter(options)); + + // Serve the Swagger documents and Swagger UI + app.use(middleware.swaggerUi()); + + // Start the server + http.createServer(app).listen(8080, function () { + console.log('Your server is listening on port %d (http://localhost:%d)', 8080, 8080); + console.log('Swagger-ui is available on http://localhost:%d/docs', 8080); + }); +}); \ No newline at end of file diff --git a/samples/server/petstore/nodejs/main.js b/samples/server/petstore/nodejs/main.js deleted file mode 100644 index bd84d18c3e2c..000000000000 --- a/samples/server/petstore/nodejs/main.js +++ /dev/null @@ -1,65 +0,0 @@ -var express = require("express") - , url = require("url") - , cors = require("cors") - , app = express() - , swagger = require("swagger-node-express") - , db = false - - -var corsOptions = { - credentials: true, - origin: function(origin,callback) { - if(origin===undefined) { - callback(null,false); - } else { - callback(null,true); - } - } -}; - -app.use(express.json()); -app.use(express.urlencoded()); -app.use(cors(corsOptions)); - -var subpath = express(); - -app.use("/v2", subpath); - -swagger.setAppHandler(subpath); - -swagger.configureSwaggerPaths("", "api-docs", "") - -var models = require("./app/models.js"); - -var UserApi = require("./app/apis/UserApi.js"); -var StoreApi = require("./app/apis/StoreApi.js"); -var PetApi = require("./app/apis/PetApi.js"); - -swagger.addModels(models) - .addPOST(UserApi.createUser) - .addPOST(UserApi.createUsersWithArrayInput) - .addPOST(UserApi.createUsersWithListInput) - .addGET(UserApi.loginUser) - .addGET(UserApi.logoutUser) - .addGET(UserApi.getUserByName) - .addPUT(UserApi.updateUser) - .addDELETE(UserApi.deleteUser) - .addGET(StoreApi.getInventory) - .addPOST(StoreApi.placeOrder) - .addGET(StoreApi.getOrderById) - .addDELETE(StoreApi.deleteOrder) - .addPUT(PetApi.updatePet) - .addPOST(PetApi.addPet) - .addGET(PetApi.findPetsByStatus) - .addGET(PetApi.findPetsByTags) - .addGET(PetApi.getPetById) - .addPOST(PetApi.updatePetWithForm) - .addDELETE(PetApi.deletePet) - .addPOST(PetApi.uploadFile) - ; - -// configures the app -swagger.configure("http://localhost:8002/v2", "0.1"); - -// start the server -app.listen(8002); diff --git a/samples/server/petstore/nodejs/package.json b/samples/server/petstore/nodejs/package.json index 09424acf1575..4d0356c8e609 100644 --- a/samples/server/petstore/nodejs/package.json +++ b/samples/server/petstore/nodejs/package.json @@ -1,16 +1,15 @@ { - "name": "swagger-client", - "description": "Wordnik node.js server generator", - "version": "1.0.0", - "homepage": "", - "main": "./main.js", - "engines": { - "node": ">= 0.8.x" - }, + "name": "", + "version": "", + "description": "This is a sample server Petstore server. You can find out more about Swagger at <a href="http://swagger.io">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key "special-key" to test the authorization filters", + "main": "index.js", + "keywords": [ + "swagger" + ], + "license": "MIT", + "private": true, "dependencies": { - "swagger-node-express": ">= 2.0.x", - "connect": ">= 1.8.x", - "cors": "2.1.1", - "express": "3.x" + "connect": "^3.2.0", + "swagger-tools": "0.8.*" } -} \ No newline at end of file +}