Merge branch 'develop_2.0' into add_springdox

This commit is contained in:
Wanny
2015-03-20 13:47:08 -07:00
107 changed files with 2672 additions and 1539 deletions

View File

@@ -26,6 +26,7 @@ public interface CodegenConfig {
String getTypeDeclaration(Property p);
String getTypeDeclaration(String name);
void processOpts();
String generateExamplePath(String path, Operation operation);
Set<String> 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<String, Model> definitions);
List<CodegenSecurity> fromSecurity(Map<String, SecuritySchemeDefinition> schemes);
Set<String> defaultIncludes();

View File

@@ -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;

View File

@@ -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;
}

View File

@@ -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;

View File

@@ -6,10 +6,12 @@ public class CodegenResponse {
public String code, message;
public Boolean hasMore;
public List<Map<String, String>> examples;
public final List<CodegenProperty> headers = new ArrayList<CodegenProperty>();
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;
}

View File

@@ -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<String, Response> 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<String, Model> definitions) {
CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION);
Set<String> imports = new HashSet<String>();
@@ -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<Parameter> 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;

View File

@@ -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<String, Object>(operation));
for(int i = 0; i < allOperations.size(); i++) {
Map<String, Object> oo = (Map<String, Object>) 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<String, Object> apis = new HashMap<String, Object>();
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<String>();
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<CodegenOperation> os = (List<CodegenOperation>) objs.get("operation");
if(os != null && os.size() > 0) {
CodegenOperation op = os.get(os.size() - 1);
op.hasMore = null;
}
}
return operations;
}

View File

@@ -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<String, Model> examples;
public ExampleGenerator(Map<String, Model> examples) {
this.examples = examples;
}
public List<Map<String, String>> generate(Map<String, String> examples, List<String> mediaTypes, Property property) {
List<Map<String, String>> output = new ArrayList<Map<String, String>>();
if(examples == null ) {
if(mediaTypes == null) {
// assume application/json for this
mediaTypes = Arrays.asList("application/json");
}
for(String mediaType : mediaTypes) {
Map<String, String> kv = new HashMap<String, String>();
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<String, String> kv = new HashMap<String, String>();
kv.put("contentType", key);
kv.put("example", value);
output.add(kv);
}
}
if(output.size() == 0) {
Map<String, String> kv = new HashMap<String, String>();
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<String, Object> mp = new HashMap<String, Object>();
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<String, Object> values = new HashMap<String, Object>();
for(String name : impl.getProperties().keySet()) {
Property property = impl.getProperties().get(name);
values.put(name, resolvePropertyToExample(mediaType, property));
}
return values;
}
return "";
}
}

View File

@@ -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 = "</";
protected Map<String, Model> 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<String, Model> examples) {
this.examples = examples;
if(examples == null)
examples = new HashMap<String, Model>();
}
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<String, Property> attributes = new LinkedHashMap<String, Property>();
Map<String, Property> elements = new LinkedHashMap<String, Property>();
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 "</" + name + ">";
}
protected String indent(int indent) {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < indent; i++) {
sb.append(" ");
}
return sb.toString();
}
}

View File

@@ -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<String>(
/**
* Reserved words. Override this with reserved words specific to your language
*/
reservedWords = new HashSet<String> (
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<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
List<Map<String, Object>> o = (List<Map<String, Object>>)objs.get("models");
for(Map<String, Object> 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<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> objectMap = (Map<String, Object>)objs.get("operations");
List<CodegenOperation> operations = (List<CodegenOperation>)objectMap.get("operation");
for(CodegenOperation operation : operations) {
operation.httpMethod = operation.httpMethod.toLowerCase();
List<CodegenParameter> params = operation.allParams;
if(params != null && params.size() == 0)
operation.allParams = null;
List<CodegenResponse> 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<Map<String, String>> examples = operation.examples;
for(int i = examples.size() - 1; i >= 0; i--) {
Map<String, String> 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;
}
}

View File

@@ -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;

View File

@@ -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();

View File

@@ -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

View File

@@ -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();
}
}
}

View File

@@ -59,9 +59,9 @@ public class {{classname}} {
Map<String, String> formParams = new HashMap<String, String>();
{{#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}}
}

View File

@@ -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<String, Client> hostMap = new HashMap<String, Client>();
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
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;

View File

@@ -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

View File

@@ -9,6 +9,7 @@
<div class="app-desc">{{{appDescription}}} for {{partner}}</div>
{{#infoUrl}}<div class="app-desc">More information: <a href="{{{infoUrl}}}">{{{infoUrl}}}</a></div>{{/infoUrl}}
{{#infoEmail}}<div class="app-desc">Contact Info: <a href="{{{infoEmail}}}">{{{infoEmail}}}</a></div>{{/infoEmail}}
{{#version}}<div class="app-desc">Version: {{{version}}}</div>{{/version}}
<div class="license-info">{{{licenseInfo}}}</div>
<div class="license-url">{{{licenseUrl}}}</div>
<h2>Access</h2>

View File

@@ -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)
[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.

View File

@@ -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}}

View File

@@ -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}}

View File

@@ -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}});
});
});

View File

@@ -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);

View File

@@ -1,3 +0,0 @@
exports.models = {
{{#models}}{{#model}}"{{classVarName}}": {{{modelJson}}}{{#hasMoreModels}},{{/hasMoreModels}}{{/model}}{{/models}}
}

View File

@@ -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.*"
}
}
}

View File

@@ -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}}

View File

@@ -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}}
}
}

View File

@@ -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}}

View File

@@ -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;

View File

@@ -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}}
/**

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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
end

View File

@@ -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

View File

@@ -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)

View File

@@ -0,0 +1,2 @@
# Swagger JSON
This is a swagger JSON built by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project.

View File

@@ -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")
}
}

View File

@@ -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)
}

View File

@@ -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)
}