Merge remote-tracking branch 'origin/master' into 2.4.0

This commit is contained in:
wing328 2018-01-07 23:13:24 +08:00
commit 007974e3de
67 changed files with 3926 additions and 1154 deletions

View File

@ -1,7 +1,7 @@
sudo: required sudo: required
language: java language: java
jdk: jdk:
- oraclejdk8 - openjdk7
cache: cache:
directories: directories:
@ -87,10 +87,10 @@ script:
#after_success: #after_success:
# push a snapshot version to maven repo # push a snapshot version to maven repo
#- if [ $SONATYPE_USERNAME ] && [ -z $TRAVIS_TAG ] && [ "$TRAVIS_BRANCH" = "master" ]; then - if [ $SONATYPE_USERNAME ] && [ -z $TRAVIS_TAG ] && [ "$TRAVIS_BRANCH" = "master" ]; then
# mvn clean deploy --settings .travis/settings.xml; mvn clean deploy --settings .travis/settings.xml;
# echo "Finished mvn clean deploy for $TRAVIS_BRANCH"; echo "Finished mvn clean deploy for $TRAVIS_BRANCH";
# fi; fi;
env: env:
- DOCKER_GENERATOR_IMAGE_NAME=swaggerapi/swagger-generator DOCKER_CODEGEN_CLI_IMAGE_NAME=swaggerapi/swagger-codegen-cli - DOCKER_GENERATOR_IMAGE_NAME=swaggerapi/swagger-generator DOCKER_CODEGEN_CLI_IMAGE_NAME=swaggerapi/swagger-codegen-cli

View File

@ -405,28 +405,28 @@ public class CodeGenMojo extends AbstractMojo {
// Set generation options // Set generation options
if (null != generateApis && generateApis) { if (null != generateApis && generateApis) {
System.setProperty("apis", ""); System.setProperty(CodegenConstants.APIS, "");
} else { } else {
System.clearProperty("apis"); System.clearProperty(CodegenConstants.APIS);
} }
if (null != generateModels && generateModels) { if (null != generateModels && generateModels) {
System.setProperty("models", modelsToGenerate); System.setProperty(CodegenConstants.MODELS, modelsToGenerate);
} else { } else {
System.clearProperty("models"); System.clearProperty(CodegenConstants.MODELS);
} }
if (null != generateSupportingFiles && generateSupportingFiles) { if (null != generateSupportingFiles && generateSupportingFiles) {
System.setProperty("supportingFiles", supportingFilesToGenerate); System.setProperty(CodegenConstants.SUPPORTING_FILES, supportingFilesToGenerate);
} else { } else {
System.clearProperty("supportingFiles"); System.clearProperty(CodegenConstants.SUPPORTING_FILES);
} }
System.setProperty("modelTests", generateModelTests.toString()); System.setProperty(CodegenConstants.MODEL_TESTS, generateModelTests.toString());
System.setProperty("modelDocs", generateModelDocumentation.toString()); System.setProperty(CodegenConstants.MODEL_DOCS, generateModelDocumentation.toString());
System.setProperty("apiTests", generateApiTests.toString()); System.setProperty(CodegenConstants.API_TESTS, generateApiTests.toString());
System.setProperty("apiDocs", generateApiDocumentation.toString()); System.setProperty(CodegenConstants.API_DOCS, generateApiDocumentation.toString());
System.setProperty("withXml", withXml.toString()); System.setProperty(CodegenConstants.WITH_XML, withXml.toString());
if (configOptions != null) { if (configOptions != null) {
// Retained for backwards-compataibility with configOptions -> instantiation-types // Retained for backwards-compataibility with configOptions -> instantiation-types

View File

@ -4,6 +4,8 @@ package io.swagger.codegen;
* A class for storing constants that are used throughout the project. * A class for storing constants that are used throughout the project.
*/ */
public class CodegenConstants { public class CodegenConstants {
/* System Properties */
// NOTE: We may want to move these to a separate class to avoid confusion or modification.
public static final String APIS = "apis"; public static final String APIS = "apis";
public static final String MODELS = "models"; public static final String MODELS = "models";
public static final String SUPPORTING_FILES = "supportingFiles"; public static final String SUPPORTING_FILES = "supportingFiles";
@ -11,6 +13,8 @@ public class CodegenConstants {
public static final String MODEL_DOCS = "modelDocs"; public static final String MODEL_DOCS = "modelDocs";
public static final String API_TESTS = "apiTests"; public static final String API_TESTS = "apiTests";
public static final String API_DOCS = "apiDocs"; public static final String API_DOCS = "apiDocs";
public static final String WITH_XML = "withXml";
/* /end System Properties */
public static final String API_PACKAGE = "apiPackage"; public static final String API_PACKAGE = "apiPackage";
public static final String API_PACKAGE_DESC = "package for generated api classes"; public static final String API_PACKAGE_DESC = "package for generated api classes";

View File

@ -1941,6 +1941,8 @@ public class DefaultCodegen {
if (property.defaultValue != null) { if (property.defaultValue != null) {
property.defaultValue = property.defaultValue.replace(baseItem.baseType, toEnumName(baseItem)); property.defaultValue = property.defaultValue.replace(baseItem.baseType, toEnumName(baseItem));
} }
updateCodegenPropertyEnum(property);
} }
} }

View File

@ -551,7 +551,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
return; return;
} }
Set<String> supportingFilesToGenerate = null; Set<String> supportingFilesToGenerate = null;
String supportingFiles = System.getProperty("supportingFiles"); String supportingFiles = System.getProperty(CodegenConstants.SUPPORTING_FILES);
if (supportingFiles != null && !supportingFiles.isEmpty()) { if (supportingFiles != null && !supportingFiles.isEmpty()) {
supportingFilesToGenerate = new HashSet<String>(Arrays.asList(supportingFiles.split(","))); supportingFilesToGenerate = new HashSet<String>(Arrays.asList(supportingFiles.split(",")));
} }

View File

@ -1,13 +1,26 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.CodegenConfig; import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.codegen.CodegenProperty; import com.samskivert.mustache.Escapers;
import io.swagger.codegen.DefaultCodegen; import com.samskivert.mustache.Mustache;
import io.swagger.models.properties.Property; import io.swagger.codegen.*;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Response;
import io.swagger.models.Swagger;
import io.swagger.models.properties.*;
import io.swagger.util.Json;
import java.util.Arrays; import java.util.*;
abstract public class AbstractAdaCodegen extends DefaultCodegen implements CodegenConfig { abstract public class AbstractAdaCodegen extends DefaultCodegen implements CodegenConfig {
protected String packageName = "swagger";
protected String projectName = "Swagger";
protected List<Map<String, Object>> orderedModels;
protected Map<String, List<String>> modelDepends;
protected Map<String, String> nullableTypeMapping;
protected HashMap<String, String> operationsScopes;
protected int scopeIndex = 0;
public AbstractAdaCodegen() { public AbstractAdaCodegen() {
super(); super();
@ -90,6 +103,56 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
"with", "with",
"xor") "xor")
); );
typeMapping = new HashMap<String, String>();
typeMapping.put("date", "Swagger.Date");
typeMapping.put("DateTime", "Swagger.Datetime");
typeMapping.put("string", "Swagger.UString");
typeMapping.put("integer", "Integer");
typeMapping.put("long", "Swagger.Long");
typeMapping.put("boolean", "Boolean");
typeMapping.put("array", "Swagger.Vector");
typeMapping.put("map", "Swagger.Map");
typeMapping.put("object", "Swagger.Object");
typeMapping.put("number", "Swagger.Number");
typeMapping.put("UUID", "Swagger.UString");
typeMapping.put("file", "Swagger.Http_Content_Type");
typeMapping.put("binary", "Swagger.Binary");
nullableTypeMapping = new HashMap<String, String>();
nullableTypeMapping.put("date", "Swagger.Nullable_Date");
nullableTypeMapping.put("DateTime", "Swagger.Nullable_Date");
nullableTypeMapping.put("string", "Swagger.Nullable_UString");
nullableTypeMapping.put("integer", "Swagger.Nullable_Integer");
nullableTypeMapping.put("long", "Swagger.Nullable_Long");
nullableTypeMapping.put("boolean", "Swagger.Nullable_Boolean");
nullableTypeMapping.put("object", "Swagger.Object");
modelDepends = new HashMap<String, List<String>>();
orderedModels = new ArrayList<Map<String, Object>>();
operationsScopes = new HashMap<String, String>();
super.importMapping = new HashMap<String, String>();
// CLI options
addOption(CodegenConstants.PROJECT_NAME, "GNAT project name",
this.projectName);
modelNameSuffix = "_Type";
embeddedTemplateDir = templateDir = "Ada";
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList("integer", "boolean", "Integer", "Character", "Boolean", "long", "float", "double"));
}
protected void addOption(String key, String description, String defaultValue) {
CliOption option = new CliOption(key, description);
if (defaultValue != null)
option.defaultValue(defaultValue);
cliOptions.add(option);
}
public String toFilename(String name) {
return name.replace(".", "-").toLowerCase();
} }
/** /**
@ -152,12 +215,394 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
return toAdaIdentifier(super.toParamName(name), "P_"); return toAdaIdentifier(super.toParamName(name), "P_");
} }
/**
* Output the proper model name (capitalized).
* In case the name belongs to the TypeSystem it won't be renamed.
*
* @param name the name of the model
* @return capitalized model name
*/
public String toModelName(final String name) {
String result = super.toModelName(name);
if (result.matches("^\\d.*") || result.startsWith("_")) {
result = "Model_" + result;
}
return result.replaceAll("[\\.-]", "_").replaceAll("__+", "_");
}
@Override @Override
public CodegenProperty fromProperty(String name, Property p) { public CodegenProperty fromProperty(String name, Property p) {
CodegenProperty property = super.fromProperty(name, p); CodegenProperty property = super.fromProperty(name, p);
String nameInCamelCase = property.nameInCamelCase; if (property != null) {
nameInCamelCase = sanitizeName(nameInCamelCase); String nameInCamelCase = property.nameInCamelCase;
property.nameInCamelCase = nameInCamelCase; nameInCamelCase = sanitizeName(nameInCamelCase);
property.nameInCamelCase = nameInCamelCase;
}
return property; return property;
} }
/**
* 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 reserved words
*
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
return "p_" + name; // add an underscore to the name
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*").replace("-", "_");
}
/**
* Override the Mustache compiler configuration.
*
* We don't want to have special characters escaped
*
* @param compiler the compiler.
* @return the compiler to use.
*/
@Override
public Mustache.Compiler processCompiler(Mustache.Compiler compiler) {
compiler = super.processCompiler(compiler).emptyStringIsFalse(true);
return compiler.withEscaper(Escapers.NONE);
}
/**
* Optional - type declaration. This is a String which is used by the
* templates to instantiate your types. There is typically special handling
* for different property types
*
* @return a string value used as the `dataType` field for model templates,
* `returnType` for api templates
*/
@Override
public String getTypeDeclaration(Property p) {
String swaggerType = getSwaggerType(p);
if (swaggerType != null) {
swaggerType = swaggerType.replace("-", "_");
}
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getTypeDeclaration(inner) + "_Vectors.Vector";
}
if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
String name = getTypeDeclaration(inner) + "_Map";
if (name.startsWith("Swagger.")) {
return name;
} else {
return "Swagger." + name;
}
}
if (typeMapping.containsKey(swaggerType)) {
if (p.getRequired()) {
return typeMapping.get(swaggerType);
} else {
return nullableTypeMapping.get(swaggerType);
}
}
// LOGGER.info("Swagger type " + swaggerType);
if (languageSpecificPrimitives.contains(swaggerType)) {
return swaggerType;
}
String modelType = toModelName(swaggerType).replace("-", "_");
if (p instanceof StringProperty || p instanceof DateProperty
|| p instanceof DateTimeProperty || p instanceof FileProperty
|| languageSpecificPrimitives.contains(modelType)) {
return modelType;
}
return modelPackage + ".Models." + modelType;
}
/**
* Overrides postProcessParameter to add a vendor extension "x-is-model-type".
* This boolean indicates that the parameter comes from the model package.
*
* @param parameter CodegenParameter object to be processed.
*/
@Override
public void postProcessParameter(CodegenParameter parameter){
// Give the base class a chance to process
super.postProcessParameter(parameter);
if (parameter.dataType == null) {
return;
}
boolean isModel = parameter.dataType.startsWith(modelPackage);
if (!isModel && !parameter.isPrimitiveType && !parameter.isDate
&& !parameter.isString && !parameter.isContainer && !parameter.isFile) {
isModel = true;
}
parameter.vendorExtensions.put("x-is-model-type", isModel);
}
/**
* Post process the media types (produces and consumes) for Ada code generator.
*
* For each media type, add a adaMediaType member that gives the Ada enum constant
* for the corresponding type.
*
* @param types the list of media types.
* @return the number of media types.
*/
protected int postProcessMediaTypes(List<Map<String, String>> types) {
int count = 0;
if (types != null) {
for (Map<String, String> media : types) {
String mt = media.get("mediaType");
if (mt != null) {
mt = mt.replace('/', '_');
media.put("adaMediaType", mt.toUpperCase());
count++;
}
}
}
return count;
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation,
Map<String, Model> definitions, Swagger swagger) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger);
if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
Response methodResponse = findMethodResponse(operation.getResponses());
if (methodResponse != null) {
if (methodResponse.getSchema() != null) {
CodegenProperty cm = fromProperty("response", methodResponse.getSchema());
op.vendorExtensions.put("x-codegen-response", cm);
if(cm.datatype == "HttpContent") {
op.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
}
}
}
}
return op;
}
@SuppressWarnings("unchecked")
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op1 : operationList) {
if (op1.summary != null) {
op1.summary = op1.summary.trim();
}
if (op1.notes != null) {
op1.notes = op1.notes.trim();
}
op1.vendorExtensions.put("x-has-uniq-produces", postProcessMediaTypes(op1.produces) == 1);
op1.vendorExtensions.put("x-has-uniq-consumes", postProcessMediaTypes(op1.consumes) == 1);
op1.vendorExtensions.put("x-has-notes", op1.notes != null && op1.notes.length() > 0);
// Set the file parameter type for both allParams and formParams.
for (CodegenParameter p : op1.allParams) {
if (p.isFormParam && p.isFile) {
p.dataType = "Swagger.File_Part_Type";
}
}
for (CodegenParameter p : op1.formParams) {
if (p.isFile) {
p.dataType = "Swagger.File_Part_Type";
}
}
postProcessAuthMethod(op1.authMethods);
/*
* Scan the path parameter to construct a x-path-index that tells the index of
* the path parameter.
*/
for (CodegenParameter p : op1.pathParams) {
String path = op1.path;
int pos = 0;
int index = 0;
while (pos >= 0 && pos < path.length()) {
int last;
pos = path.indexOf('{', pos);
if (pos < 0) {
break;
}
pos++;
last = path.indexOf('}', pos);
index++;
if (last < 0) {
break;
}
if (path.substring(pos, last - 1) == p.baseName) {
break;
}
pos = last + 1;
}
p.vendorExtensions.put("x-path-index", index);
}
}
return objs;
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// Collect the model dependencies.
List<Map<String, Object>> models = (List<Map<String, Object>>) objs.get("models");
for (Map<String, Object> model : models) {
Object v = model.get("model");
if (v instanceof CodegenModel) {
CodegenModel m = (CodegenModel) v;
List<String> d = new ArrayList<String>();
for (CodegenProperty p : m.allVars) {
boolean isModel = false;
CodegenProperty item = p;
if (p.isContainer) {
item = p.items;
}
if (item != null && !item.isString && !item.isPrimitiveType && !item.isContainer && !item.isInteger) {
if (!d.contains(item.datatype)) {
// LOGGER.info("Model " + m.name + " uses " + p.datatype);
d.add(item.datatype);
isModel = true;
}
}
p.vendorExtensions.put("x-is-model-type", isModel);
}
modelDepends.put(m.name, d);
orderedModels.add(model);
}
}
// Sort the models according to dependencies so that model that depend
// on others appear at end of the list.
final Map<String, List<String>> deps = modelDepends;
Collections.sort(orderedModels, new Comparator<Map<String, Object>>() {
@Override
public int compare(Map<String, Object> lhs, Map<String, Object> rhs) {
Object v = lhs.get("model");
String lhsName = ((CodegenModel) v).name;
v = rhs.get("model");
String rhsName = ((CodegenModel) v).name;
List<String> lhsList = deps.get(lhsName);
List<String> rhsList = deps.get(rhsName);
if (lhsList == rhsList) {
// LOGGER.info("First compare " + lhsName + "<" + rhsName);
return lhsName.compareTo(rhsName);
}
// Put models without dependencies first.
if (lhsList == null) {
// LOGGER.info(" Empty " + lhsName + ", no check " + rhsName);
return -1;
}
if (rhsList == null) {
// LOGGER.info(" No check " + lhsName + ", empty " + rhsName);
return 1;
}
// Put models that depend on another after.
if (lhsList.contains(rhsName)) {
// LOGGER.info(" LSH " + lhsName + " uses " + rhsName);
return 1;
}
if (rhsList.contains(lhsName)) {
// LOGGER.info(" RHS " + rhsName + " uses " + lhsName);
return -1;
}
// Put models with less dependencies first.
if (lhsList.size() < rhsList.size()) {
// LOGGER.info(" LSH size " + lhsName + " < RHS size " + rhsName);
return -1;
}
if (lhsList.size() > rhsList.size()) {
// LOGGER.info(" LSH size " + lhsName + " > RHS size " + rhsName);
return 1;
}
// Sort models on their name.
// LOGGER.info("Compare " + lhsName + "<" + rhsName);
return lhsName.compareTo(rhsName);
}
});
/* for (Map<String, Object> model : orderedModels) {
Object v = model.get("model");
if (v instanceof CodegenModel) {
CodegenModel m = (CodegenModel) v;
LOGGER.info("Order: " + m.name);
}
}*/
return postProcessModelsEnum(objs);
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
objs.put("orderedModels", orderedModels);
Swagger swagger = (Swagger)objs.get("swagger");
if(swagger != null) {
String host = swagger.getBasePath();
try {
swagger.setHost("SWAGGER_HOST");
objs.put("swagger-json", Json.pretty().writeValueAsString(swagger).replace("\r\n", "\n"));
} catch (JsonProcessingException e) {
LOGGER.error(e.getMessage(), e);
}
swagger.setHost(host);
}
/**
* Collect the scopes to generate unique identifiers for each of them.
*/
List<CodegenSecurity> authMethods = (List<CodegenSecurity>) objs.get("authMethods");
postProcessAuthMethod(authMethods);
return super.postProcessSupportingFileData(objs);
}
/**
* Collect the scopes to generate a unique identifier for each of them.
*
* @param authMethods the auth methods with their scopes.
*/
private void postProcessAuthMethod(List<CodegenSecurity> authMethods) {
if (authMethods != null) {
for (CodegenSecurity authMethod : authMethods) {
if (authMethod.scopes != null) {
for (Map<String, Object> scope : authMethod.scopes) {
String name = (String) scope.get("scope");
if (operationsScopes.containsKey(name)) {
scope.put("ident", operationsScopes.get(name));
} else {
String ident;
if (name.startsWith("https://")) {
int pos = name.lastIndexOf('/');
ident = name.substring(pos + 1);
} else {
ident = name;
}
scopeIndex++;
ident = toAdaIdentifier(sanitizeName(ident.replaceAll(":", "_")), "S_");
if (operationsScopes.containsValue(ident)) {
ident = ident + "_" + scopeIndex;
}
operationsScopes.put(name, ident);
scope.put("ident", ident);
}
}
}
authMethod.name = camelize(sanitizeName(authMethod.name), true);
}
}
}
} }

View File

@ -352,6 +352,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
* those vars referencing RefModel'd enums to work the same as inlined enums rather than as objects. * those vars referencing RefModel'd enums to work the same as inlined enums rather than as objects.
* @param models * @param models
*/ */
@SuppressWarnings({ "unchecked" })
private void postProcessEnumRefs(final Map<String, Object> models) { private void postProcessEnumRefs(final Map<String, Object> models) {
Map<String, CodegenModel> enumRefs = new HashMap<String, CodegenModel>(); Map<String, CodegenModel> enumRefs = new HashMap<String, CodegenModel>();
for (Map.Entry<String, Object> entry : models.entrySet()) { for (Map.Entry<String, Object> entry : models.entrySet()) {
@ -372,11 +373,57 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
// while enums in many other languages are true objects. // while enums in many other languages are true objects.
CodegenModel refModel = enumRefs.get(var.datatype); CodegenModel refModel = enumRefs.get(var.datatype);
var.allowableValues = refModel.allowableValues; var.allowableValues = refModel.allowableValues;
var.isEnum = true;
updateCodegenPropertyEnum(var); updateCodegenPropertyEnum(var);
// We do these after updateCodegenPropertyEnum to avoid generalities that don't mesh with C#. // We do these after updateCodegenPropertyEnum to avoid generalities that don't mesh with C#.
var.isPrimitiveType = true; var.isPrimitiveType = true;
var.isEnum = true; }
}
// We're looping all models here.
if (model.isEnum) {
// We now need to make allowableValues.enumVars look like the context of CodegenProperty
Boolean isString = false;
Boolean isInteger = false;
Boolean isLong = false;
Boolean isByte = false;
if (model.dataType.startsWith("byte")) {
// C# Actually supports byte and short enums, swagger spec only supports byte.
isByte = true;
model.vendorExtensions.put("x-enum-byte", true);
} else if (model.dataType.startsWith("int32")) {
isInteger = true;
model.vendorExtensions.put("x-enum-integer", true);
} else if (model.dataType.startsWith("int64")) {
isLong = true;
model.vendorExtensions.put("x-enum-long", true);
} else {
// C# doesn't support non-integral enums, so we need to treat everything else as strings (e.g. to not lose precision or data integrity)
isString = true;
model.vendorExtensions.put("x-enum-string", true);
}
// Since we iterate enumVars for modelnnerEnum and enumClass templates, and CodegenModel is missing some of CodegenProperty's properties,
// we can take advantage of Mustache's contextual lookup to add the same "properties" to the model's enumVars scope rather than CodegenProperty's scope.
List<Map<String, String>> enumVars = (ArrayList<Map<String, String>>)model.allowableValues.get("enumVars");
List<Map<String, Object>> newEnumVars = new ArrayList<Map<String, Object>>();
for (Map<String, String> enumVar : enumVars) {
Map<String, Object> mixedVars = new HashMap<String, Object>();
mixedVars.putAll(enumVar);
mixedVars.put("isString", isString);
mixedVars.put("isLong", isLong);
mixedVars.put("isInteger", isInteger);
mixedVars.put("isByte", isByte);
newEnumVars.add(mixedVars);
}
if (!newEnumVars.isEmpty()) {
model.allowableValues.put("enumVars", newEnumVars);
} }
} }
} else { } else {
@ -385,6 +432,42 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
} }
} }
/**
* Update codegen property's enum by adding "enumVars" (with name and value)
*
* @param var list of CodegenProperty
*/
@Override
public void updateCodegenPropertyEnum(CodegenProperty var) {
if (var.vendorExtensions == null) {
var.vendorExtensions = new HashMap<>();
}
super.updateCodegenPropertyEnum(var);
// Because C# uses nullable primitives for datatype, and datatype is used in DefaultCodegen for determining enum-ness, guard against weirdness here.
if (var.isEnum) {
if ("byte".equals(var.dataFormat)) {// C# Actually supports byte and short enums.
var.vendorExtensions.put("x-enum-byte", true);
var.isString = false;
var.isLong = false;
var.isInteger = false;
} else if ("int32".equals(var.dataFormat)) {
var.isInteger = true;
var.isString = false;
var.isLong = false;
} else if ("int64".equals(var.dataFormat)) {
var.isLong = true;
var.isString = false;
var.isInteger = false;
} else {// C# doesn't support non-integral enums, so we need to treat everything else as strings (e.g. to not lose precision or data integrity)
var.isString = true;
var.isInteger = false;
var.isLong = false;
}
}
}
@Override @Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) { public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
super.postProcessOperations(objs); super.postProcessOperations(objs);
@ -769,6 +852,19 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
this.interfacePrefix = interfacePrefix; this.interfacePrefix = interfacePrefix;
} }
@Override
public String toEnumValue(String value, String datatype) {
// C# only supports enums as literals for int, int?, long, long?, byte, and byte?. All else must be treated as strings.
// Per: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/enum
// The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.
// but we're not supporting unsigned integral types or shorts.
if(datatype.startsWith("int") || datatype.startsWith("long") || datatype.startsWith("byte")) {
return value;
}
return escapeText(value);
}
@Override @Override
public String toEnumVarName(String name, String datatype) { public String toEnumVarName(String name, String datatype) {
if (name.length() == 0) { if (name.length() == 0) {
@ -799,32 +895,6 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
return sanitizeName(camelize(property.name)) + "Enum"; return sanitizeName(camelize(property.name)) + "Enum";
} }
/*
@Override
public String toEnumName(CodegenProperty property) {
String enumName = sanitizeName(property.name);
if (!StringUtils.isEmpty(modelNamePrefix)) {
enumName = modelNamePrefix + "_" + enumName;
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
enumName = enumName + "_" + modelNameSuffix;
}
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(enumName)) {
LOGGER.warn(enumName + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + enumName));
enumName = "model_" + enumName; // e.g. return => ModelReturn (after camelize)
}
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
} else {
return enumName;
}
}
*/
public String testPackageName() { public String testPackageName() {
return this.packageName + ".Test"; return this.packageName + ".Test";
} }
@ -839,5 +909,4 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
public String escapeUnsafeCharacters(String input) { public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*").replace("--", "- -"); return input.replace("*/", "*_/").replace("/*", "/_*").replace("--", "- -");
} }
} }

View File

@ -5,12 +5,15 @@ import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property; import io.swagger.models.properties.Property;
import io.swagger.models.parameters.Parameter; import io.swagger.models.parameters.Parameter;
import io.swagger.models.Swagger;
import io.swagger.util.Yaml; import io.swagger.util.Yaml;
import java.util.*; import java.util.*;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -362,6 +365,19 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege
return postProcessModelsEnum(objs); return postProcessModelsEnum(objs);
} }
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
Swagger swagger = (Swagger)objs.get("swagger");
if(swagger != null) {
try {
objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger));
} catch (JsonProcessingException e) {
LOGGER.error(e.getMessage(), e);
}
}
return super.postProcessSupportingFileData(objs);
}
@Override @Override
protected boolean needToImport(String type) { protected boolean needToImport(String type) {
return !defaultIncludes.contains(type) return !defaultIncludes.contains(type)

View File

@ -1,58 +1,17 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import java.io.File; import java.io.File;
import java.util.*; import java.io.IOException;
import java.io.Writer;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import io.swagger.codegen.*; import io.swagger.codegen.*;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Response;
import io.swagger.models.Swagger;
import io.swagger.models.properties.*;
public class AdaCodegen extends AbstractAdaCodegen implements CodegenConfig { public class AdaCodegen extends AbstractAdaCodegen implements CodegenConfig {
protected String packageName = "swagger";
protected String projectName = "Swagger";
protected List<Map<String, Object>> orderedModels;
protected Map<String, List<String>> modelDepends;
public AdaCodegen() { public AdaCodegen() {
super(); super();
modelNameSuffix = "_Type";
orderedModels = new ArrayList<Map<String, Object>>();
modelDepends = new HashMap<String, List<String>>();
embeddedTemplateDir = templateDir = "Ada";
// CLI options
addOption(CodegenConstants.PROJECT_NAME, "GNAT project name",
this.projectName);
addOption(CodegenConstants.PACKAGE_NAME, "Ada package name (convention: name.space.model).",
this.modelPackage);
addOption(CodegenConstants.MODEL_PACKAGE, "Ada package for models (convention: name.space.model).",
this.modelPackage);
addOption(CodegenConstants.API_PACKAGE, "Ada package for apis (convention: name.space.api).",
this.apiPackage);
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList("integer", "boolean", "Integer", "Character", "Boolean", "long", "float", "double", "int32_t", "int64_t"));
typeMapping = new HashMap<String, String>();
typeMapping.put("date", "Swagger.Date");
typeMapping.put("DateTime", "Swagger.Datetime");
typeMapping.put("string", "Swagger.UString");
typeMapping.put("integer", "Integer");
typeMapping.put("long", "Swagger.Long");
typeMapping.put("boolean", "Boolean");
typeMapping.put("array", "Swagger.Vector");
typeMapping.put("map", "Swagger.Map");
typeMapping.put("object", "Swagger.Object");
typeMapping.put("number", "Swagger.Number");
typeMapping.put("UUID", "Swagger.UString");
typeMapping.put("file", "Swagger.Http_Content_Type");
typeMapping.put("binary", "Swagger.Binary");
super.importMapping = new HashMap<String, String>();
} }
@Override @Override
@ -70,36 +29,22 @@ public class AdaCodegen extends AbstractAdaCodegen implements CodegenConfig {
return "Generates an Ada client implementation (beta)."; return "Generates an Ada client implementation (beta).";
} }
protected void addOption(String key, String description, String defaultValue) {
CliOption option = new CliOption(key, description);
if (defaultValue != null)
option.defaultValue(defaultValue);
cliOptions.add(option);
}
public String toFilename(String name) {
return name.replace(".", "-").toLowerCase();
}
@Override @Override
public void processOpts() { public void processOpts() {
super.processOpts(); super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
packageName = (String) additionalProperties.get(CodegenConstants.PACKAGE_NAME); packageName = (String) additionalProperties.get(CodegenConstants.PACKAGE_NAME);
} }
String serverPrefix = "src" + File.separator + "server" + File.separator + toFilename(modelPackage); if (packageName == "") {
String clientPrefix = "src" + File.separator + "client" + File.separator + toFilename(modelPackage); packageName = modelPackage;
supportingFiles.add(new SupportingFile("model-spec.mustache", null, clientPrefix + "-models.ads")); }
supportingFiles.add(new SupportingFile("model-body.mustache", null, clientPrefix + "-models.adb")); String srcPrefix = "src" + File.separator;
supportingFiles.add(new SupportingFile("model-spec.mustache", null, serverPrefix + "-models.ads")); String modelPrefix = srcPrefix + "model" + File.separator + toFilename(modelPackage);
supportingFiles.add(new SupportingFile("model-body.mustache", null, serverPrefix + "-models.adb")); String clientPrefix = srcPrefix + "client" + File.separator + toFilename(modelPackage);
supportingFiles.add(new SupportingFile("model-spec.mustache", null, modelPrefix + "-models.ads"));
supportingFiles.add(new SupportingFile("model-body.mustache", null, modelPrefix + "-models.adb"));
supportingFiles.add(new SupportingFile("client-spec.mustache", null, clientPrefix + "-clients.ads")); supportingFiles.add(new SupportingFile("client-spec.mustache", null, clientPrefix + "-clients.ads"));
supportingFiles.add(new SupportingFile("client-body.mustache", null, clientPrefix + "-clients.adb")); supportingFiles.add(new SupportingFile("client-body.mustache", null, clientPrefix + "-clients.adb"));
supportingFiles.add(new SupportingFile("server-spec.mustache", null, serverPrefix + "-servers.ads"));
supportingFiles.add(new SupportingFile("server-body.mustache", null, serverPrefix + "-servers.adb"));
// String title = swagger.getInfo().getTitle();
supportingFiles.add(new SupportingFile("gnat-project.mustache", "", "project.gpr"));
if (additionalProperties.containsKey(CodegenConstants.PROJECT_NAME)) { if (additionalProperties.containsKey(CodegenConstants.PROJECT_NAME)) {
projectName = (String) additionalProperties.get(CodegenConstants.PROJECT_NAME); projectName = (String) additionalProperties.get(CodegenConstants.PROJECT_NAME);
@ -108,13 +53,47 @@ public class AdaCodegen extends AbstractAdaCodegen implements CodegenConfig {
// e.g. petstore.api (package name) => petstore_api (project name) // e.g. petstore.api (package name) => petstore_api (project name)
projectName = packageName.replaceAll("\\.", "_"); projectName = packageName.replaceAll("\\.", "_");
} }
String configBaseName = modelPackage.toLowerCase();
supportingFiles.add(new SupportingFile("gnat-project.mustache", "", toFilename(projectName) + ".gpr"));
// supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("config.gpr", "", "config.gpr"));
/* /*
* Additional Properties. These values can be passed to the templates and * Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files * are available in models, apis, and supporting files
*/ */
additionalProperties.put("package", this.modelPackage); additionalProperties.put("package", this.modelPackage);
additionalProperties.put("packageConfig", configBaseName);
additionalProperties.put("packageDir", "client");
additionalProperties.put("mainName", "client");
additionalProperties.put(CodegenConstants.PROJECT_NAME, projectName); additionalProperties.put(CodegenConstants.PROJECT_NAME, projectName);
String names[] = this.modelPackage.split("\\.");
String pkgName = names[0];
additionalProperties.put("packageLevel1", pkgName);
supportingFiles.add(new SupportingFile("package-spec-level1.mustache", null,
"src" + File.separator + toFilename(names[0]) + ".ads"));
if (names.length > 1) {
String fileName = toFilename(names[0]) + "-" + toFilename(names[1]) + ".ads";
pkgName = names[0] + "." + names[1];
additionalProperties.put("packageLevel2", pkgName);
supportingFiles.add(new SupportingFile("package-spec-level2.mustache", null,
"src" + File.separator + fileName));
}
pkgName = this.modelPackage;
supportingFiles.add(new SupportingFile("client.mustache", null,
"src" + File.separator + toFilename(pkgName) + "-client.adb"));
additionalProperties.put("packageName", toFilename(pkgName));
// add lambda for mustache templates
additionalProperties.put("lambdaAdaComment", new Mustache.Lambda() {
@Override
public void execute(Template.Fragment fragment, Writer writer) throws IOException {
String content = fragment.execute();
content = content.trim().replaceAll("\n$", "");
writer.write(content.replaceAll("\n", "\n -- "));
}
});
} }
@Override @Override
@ -126,237 +105,4 @@ public class AdaCodegen extends AbstractAdaCodegen implements CodegenConfig {
public String modelFileFolder() { public String modelFileFolder() {
return outputFolder + "/model/" + modelPackage().replace('.', File.separatorChar); return outputFolder + "/model/" + modelPackage().replace('.', File.separatorChar);
} }
/**
* 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 reserved words
*
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
return "p_" + name; // add an underscore to the name
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
/**
* Optional - type declaration. This is a String which is used by the
* templates to instantiate your types. There is typically special handling
* for different property types
*
* @return a string value used as the `dataType` field for model templates,
* `returnType` for api templates
*/
@Override
public String getTypeDeclaration(Property p) {
String swaggerType = getSwaggerType(p);
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getTypeDeclaration(inner) + "_Vectors.Vector";
}
if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return "Swagger." + getTypeDeclaration(inner) + "_Map";
}
if (typeMapping.containsKey(swaggerType)) {
return typeMapping.get(swaggerType);
}
// LOGGER.info("Swagger type " + swaggerType);
if (languageSpecificPrimitives.contains(swaggerType)) {
return swaggerType;
}
String modelType = toModelName(swaggerType);
if (p instanceof StringProperty || p instanceof DateProperty
|| p instanceof DateTimeProperty || p instanceof FileProperty
|| languageSpecificPrimitives.contains(modelType)) {
return modelType;
}
return modelPackage + ".Models." + modelType;
}
/**
* Overrides postProcessParameter to add a vendor extension "x-is-model-type".
* This boolean indicates that the parameter comes from the model package.
*
* @param parameter CodegenParameter object to be processed.
*/
@Override
public void postProcessParameter(CodegenParameter parameter){
// Give the base class a chance to process
super.postProcessParameter(parameter);
boolean isModel = parameter.dataType.startsWith(modelPackage);
if (!isModel && !parameter.isPrimitiveType && !parameter.isDate
&& !parameter.isString && !parameter.isContainer && !parameter.isFile) {
isModel = true;
}
parameter.vendorExtensions.put("x-is-model-type", isModel);
}
/**
* Post process the media types (produces and consumes) for Ada code generator.
*
* For each media type, add a adaMediaType member that gives the Ada enum constant
* for the corresponding type.
*
* @param types the list of media types.
* @return the number of media types.
*/
protected int postProcessMediaTypes(List<Map<String, String>> types) {
int count = 0;
if (types != null) {
for (Map<String, String> media : types) {
String mt = media.get("mediaType");
if (mt != null) {
mt = mt.replace('/', '_');
media.put("adaMediaType", mt.toUpperCase());
count++;
}
}
}
return count;
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation,
Map<String, Model> definitions, Swagger swagger) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger);
if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
Response methodResponse = findMethodResponse(operation.getResponses());
if (methodResponse != null) {
if (methodResponse.getSchema() != null) {
CodegenProperty cm = fromProperty("response", methodResponse.getSchema());
op.vendorExtensions.put("x-codegen-response", cm);
if(cm.datatype == "HttpContent") {
op.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
}
}
}
}
return op;
}
@SuppressWarnings("unchecked")
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op1 : operationList) {
op1.vendorExtensions.put("x-has-uniq-produces", postProcessMediaTypes(op1.produces) == 1);
op1.vendorExtensions.put("x-has-uniq-consumes", postProcessMediaTypes(op1.consumes) == 1);
op1.vendorExtensions.put("x-has-notes", op1.notes.length() > 0);
}
return objs;
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// Collect the model dependencies.
List<Map<String, Object>> models = (List<Map<String, Object>>) objs.get("models");
for (Map<String, Object> model : models) {
Object v = model.get("model");
if (v instanceof CodegenModel) {
CodegenModel m = (CodegenModel) v;
List<String> d = new ArrayList<String>();
for (CodegenProperty p : m.allVars) {
boolean isModel = false;
CodegenProperty item = p;
if (p.isContainer) {
item = p.items;
}
if (item != null && !item.isString && !item.isPrimitiveType && !item.isContainer && !item.isInteger) {
if (!d.contains(item.datatype)) {
// LOGGER.info("Model " + m.name + " uses " + p.datatype);
d.add(item.datatype);
isModel = true;
}
}
p.vendorExtensions.put("x-is-model-type", isModel);
}
modelDepends.put(m.name, d);
orderedModels.add(model);
}
}
// Sort the models according to dependencies so that model that depend
// on others appear at end of the list.
final Map<String, List<String>> deps = modelDepends;
Collections.sort(orderedModels, new Comparator<Map<String, Object>>() {
@Override
public int compare(Map<String, Object> lhs, Map<String, Object> rhs) {
Object v = lhs.get("model");
String lhsName = ((CodegenModel) v).name;
v = rhs.get("model");
String rhsName = ((CodegenModel) v).name;
List<String> lhsList = deps.get(lhsName);
List<String> rhsList = deps.get(rhsName);
if (lhsList == rhsList) {
// LOGGER.info("First compare " + lhsName + "<" + rhsName);
return lhsName.compareTo(rhsName);
}
// Put models without dependencies first.
if (lhsList == null) {
// LOGGER.info(" Empty " + lhsName + ", no check " + rhsName);
return -1;
}
if (rhsList == null) {
// LOGGER.info(" No check " + lhsName + ", empty " + rhsName);
return 1;
}
// Put models that depend on another after.
if (lhsList.contains(rhsName)) {
// LOGGER.info(" LSH " + lhsName + " uses " + rhsName);
return 1;
}
if (rhsList.contains(lhsName)) {
// LOGGER.info(" RHS " + rhsName + " uses " + lhsName);
return -1;
}
// Put models with less dependencies first.
if (lhsList.size() < rhsList.size()) {
// LOGGER.info(" LSH size " + lhsName + " < RHS size " + rhsName);
return -1;
}
if (lhsList.size() > rhsList.size()) {
// LOGGER.info(" LSH size " + lhsName + " > RHS size " + rhsName);
return 1;
}
// Sort models on their name.
// LOGGER.info("Compare " + lhsName + "<" + rhsName);
return lhsName.compareTo(rhsName);
}
});
/* for (Map<String, Object> model : orderedModels) {
Object v = model.get("model");
if (v instanceof CodegenModel) {
CodegenModel m = (CodegenModel) v;
LOGGER.info("Order: " + m.name);
}
}*/
return postProcessModelsEnum(objs);
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
objs.put("orderedModels", orderedModels);
return super.postProcessSupportingFileData(objs);
}
} }

View File

@ -0,0 +1,111 @@
package io.swagger.codegen.languages;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import io.swagger.codegen.*;
public class AdaServerCodegen extends AbstractAdaCodegen implements CodegenConfig {
public AdaServerCodegen() {
super();
}
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
@Override
public String getName() {
return "ada-server";
}
@Override
public String getHelp() {
return "Generates an Ada server implementation (beta).";
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
packageName = (String) additionalProperties.get(CodegenConstants.PACKAGE_NAME);
}
String srcPrefix = "src" + File.separator;
String serverPrefix = srcPrefix + "server" + File.separator + toFilename(modelPackage);
String modelPrefix = srcPrefix + "model" + File.separator + toFilename(modelPackage);
String implPrefix = srcPrefix + toFilename(modelPackage);
supportingFiles.add(new SupportingFile("model-spec.mustache", null, modelPrefix + "-models.ads"));
supportingFiles.add(new SupportingFile("model-body.mustache", null, modelPrefix + "-models.adb"));
supportingFiles.add(new SupportingFile("server-skeleton-spec.mustache", null, serverPrefix + "-skeletons.ads"));
supportingFiles.add(new SupportingFile("server-skeleton-body.mustache", null, serverPrefix + "-skeletons.adb"));
supportingFiles.add(new SupportingFile("server-spec.mustache", null, implPrefix + "-servers.ads"));
supportingFiles.add(new SupportingFile("server-body.mustache", null, implPrefix + "-servers.adb"));
supportingFiles.add(new SupportingFile("swagger.mustache", "web" + File.separator + "swagger", "swagger.json"));
if (additionalProperties.containsKey(CodegenConstants.PROJECT_NAME)) {
projectName = (String) additionalProperties.get(CodegenConstants.PROJECT_NAME);
} else {
// default: set project based on package name
// e.g. petstore.api (package name) => petstore_api (project name)
projectName = packageName.replaceAll("\\.", "_");
}
String configBaseName = modelPackage.toLowerCase();
supportingFiles.add(new SupportingFile("gnat-project.mustache", "", toFilename(projectName) + ".gpr"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("config.gpr", "", "config.gpr"));
supportingFiles.add(new SupportingFile("server-properties.mustache", "", configBaseName + ".properties"));
/*
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files
*/
additionalProperties.put("package", this.modelPackage);
additionalProperties.put("packageConfig", configBaseName);
additionalProperties.put("packageDir", "server");
additionalProperties.put("mainName", "server");
additionalProperties.put(CodegenConstants.PROJECT_NAME, projectName);
String names[] = this.modelPackage.split("\\.");
String pkgName = names[0];
additionalProperties.put("packageLevel1", pkgName);
supportingFiles.add(new SupportingFile("package-spec-level1.mustache", null,
"src" + File.separator + toFilename(names[0]) + ".ads"));
if (names.length > 1) {
String fileName = toFilename(names[0]) + "-" + toFilename(names[1]) + ".ads";
pkgName = names[0] + "." + names[1];
additionalProperties.put("packageLevel2", pkgName);
supportingFiles.add(new SupportingFile("package-spec-level2.mustache", null,
"src" + File.separator + fileName));
}
pkgName = this.modelPackage;
supportingFiles.add(new SupportingFile("server.mustache", null,
"src" + File.separator + toFilename(pkgName) + "-server.adb"));
additionalProperties.put("packageName", toFilename(pkgName));
// add lambda for mustache templates
additionalProperties.put("lambdaAdaComment", new Mustache.Lambda() {
@Override
public void execute(Template.Fragment fragment, Writer writer) throws IOException {
String content = fragment.execute();
content = content.trim().replaceAll("\n$", "");
writer.write(content.replaceAll("\n", "\n -- "));
}
});
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + apiPackage().replace('.', File.separatorChar);
}
@Override
public String modelFileFolder() {
return outputFolder + "/model/" + modelPackage().replace('.', File.separatorChar);
}
}

View File

@ -671,19 +671,6 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
return codegenModel; return codegenModel;
} }
@Override
public String toEnumValue(String value, String datatype) {
if ("int?".equalsIgnoreCase(datatype) || "long?".equalsIgnoreCase(datatype) ||
"double?".equalsIgnoreCase(datatype) || "float?".equalsIgnoreCase(datatype)) {
return value;
} else if ("float?".equalsIgnoreCase(datatype)) {
// for float in C#, append "f". e.g. 3.14 => 3.14f
return value + "f";
} else {
return "\"" + escapeText(value) + "\"";
}
}
@Override @Override
public String toEnumVarName(String value, String datatype) { public String toEnumVarName(String value, String datatype) {
if (value.length() == 0) { if (value.length() == 0) {
@ -696,8 +683,8 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
} }
// number // number
if ("int?".equals(datatype) || "long?".equals(datatype) || if(datatype.startsWith("int") || datatype.startsWith("long") ||
"double?".equals(datatype) || "float?".equals(datatype)) { datatype.startsWith("double") || datatype.startsWith("float")) {
String varName = "NUMBER_" + value; String varName = "NUMBER_" + value;
varName = varName.replaceAll("-", "MINUS_"); varName = varName.replaceAll("-", "MINUS_");
varName = varName.replaceAll("\\+", "PLUS_"); varName = varName.replaceAll("\\+", "PLUS_");

View File

@ -87,6 +87,7 @@ public class GoClientCodegen extends AbstractGoCodegen {
modelPackage = packageName; modelPackage = packageName;
apiPackage = packageName; apiPackage = packageName;
supportingFiles.add(new SupportingFile("swagger.mustache", "api", "swagger.yaml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));

View File

@ -5,20 +5,12 @@ import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property; import io.swagger.models.properties.Property;
import io.swagger.models.parameters.Parameter; import io.swagger.models.parameters.Parameter;
import io.swagger.models.*;
import io.swagger.util.Yaml;
import java.io.File; import java.io.File;
import java.util.*; import java.util.*;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -167,17 +159,4 @@ public class GoServerCodegen extends AbstractGoCodegen {
return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar);
} }
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
Swagger swagger = (Swagger)objs.get("swagger");
if(swagger != null) {
try {
objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger));
} catch (JsonProcessingException e) {
LOGGER.error(e.getMessage(), e);
}
}
return super.postProcessSupportingFileData(objs);
}
} }

View File

@ -0,0 +1,102 @@
# {{appDescription}} - Swagger Ada Server
## Overview
This Ada server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project.
By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server,
you can easily generate a server stub.
## Building
To build the server you will need the GNAT Ada compiler as well as
the [Swagger Ada library](https://github.com/stcarrez/swagger-ada).
When the GNAT Ada compiler and Swagger Ada libraries are installed,
run the following command:
```
gprbuild -p -P{{projectName}}
```
After the build is successfull, you will get the server binary
in bin/{{packageName}}-server and you can start it as follows:
```
./bin/{{packageName}}-server
```
## Structure of the server
The server consists of several Ada packages that are generated from
the OpenAPI specification.
Source file | Package | Description
------------ | ------------- | -------------
src/{{packageName}}.ads|{{package}}|The server root package declaration
src/{{packageName}}-servers.ads|{{package}}.Servers|The server declaration and instantiation
src/{{packageName}}-servers.adb|{{package}}.Servers|The server implementation (empty stubs)
src/server/{{packageName}}-skeletons.ads|{{package}}.Skeletons|The server skeleton declaration
src/server/{{packageName}}-skeletons.adb|{{package}}.Skeletons|The server skeleton implementation
src/server/{{packageName}}-models.ads|{{package}}.Skeletons|The server model types declaration
src/server/{{packageName}}-models.adb|{{package}}.Skeletons|The server model types implementation
src/{{packageName}}-server.adb|{{package}}.Server|The server main procedure
Files generated in **src/server** should not be modified. The server implementation
files (**src/{{packageName}}-server.ads** and **src/{{packageName}}-server.adb**) should
be modified to implement the server operations. You can also customize the server
main procedure according to your needs.
## Server model
The server instance is represented by the **{{package}}.Servers.Server_Type** Ada type.
The REST API will need an instance of it to make the operation call. Two server model
exists:
* The instance per request model creates an instance of the server type for each request.
* The shared instance model shares the same instance across all concurrent REST requests. This instance is protected using an Ada protected object which holds the server instance.
The choice of the server model is made at the compilation time by instantiating either
the **{{package}}.Skeletons.Skeleton** package or the **{{package}}.Skeletons.Shared_Instance**
package. Such instantiation is done in **src/{{packageName}}-server.ads** and the default
is to use the **Shared_Instance**.
## Implementing a server operation
All you have to do is implement the server operation in the **src/{{packageName}}-servers.adb** file.
The package already contains the operation with its parameters and you only have to replace
the **null** instruction by real code.
# Documentation
## API Documentation
All URIs are relative to *{{basePath}}*
Method | HTTP request | Description
------------- | ------------- | -------------
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}[**{{nickname}}**]({{apiDocPath}}{{classname}}.md#{{nickname}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
## Models
{{#models}}{{#model}} - [{{package}}.Models.{{classname}}]({{modelDocPath}}{{classname}}.md)
{{/model}}{{/models}}
## Authorization
{{^authMethods}} All endpoints do not require authorization.
{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}}
{{#authMethods}}## {{{name}}}
{{#isApiKey}}- **Type**: API key
- **API key parameter name**: {{{keyParamName}}}
- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}}
{{/isApiKey}}
{{#isBasic}}- **Type**: HTTP basic authentication
{{/isBasic}}
{{#isOAuth}}- **Type**: OAuth
- **Flow**: {{{flow}}}
- **Authorization URL**: {{{authorizationUrl}}}
- **Scopes**: {{^scopes}}N/A{{/scopes}}
{{#scopes}} - **{{{scope}}}**: {{{description}}}
{{/scopes}}
{{/isOAuth}}
{{/authMethods}}

View File

@ -7,7 +7,7 @@ package body {{package}}.Clients is
{{#operation}} {{#operation}}
-- {{summary}}{{#vendorExtensions.x-has-notes}} -- {{summary}}{{#vendorExtensions.x-has-notes}}
-- {{unescapedNotes}}{{/vendorExtensions.x-has-notes}} -- {{#lambdaAdaComment}}{{unescapedNotes}}{{/lambdaAdaComment}}{{/vendorExtensions.x-has-notes}}
procedure {{operationId}} procedure {{operationId}}
(Client : in out Client_Type{{#hasParams}};{{/hasParams}}{{#allParams}} (Client : in out Client_Type{{#hasParams}};{{/hasParams}}{{#allParams}}
{{paramName}} : in {{^isFile}}{{^isString}}{{^isPrimitiveType}}{{^isContainer}}{{package}}.Models.{{/isContainer}}{{/isPrimitiveType}}{{/isString}}{{/isFile}}{{dataType}}{{#hasMore}};{{/hasMore}}{{/allParams}}{{#returnType}}; {{paramName}} : in {{^isFile}}{{^isString}}{{^isPrimitiveType}}{{^isContainer}}{{package}}.Models.{{/isContainer}}{{/isPrimitiveType}}{{/isString}}{{/isFile}}{{dataType}}{{#hasMore}};{{/hasMore}}{{/allParams}}{{#returnType}};
@ -19,8 +19,9 @@ package body {{package}}.Clients is
Reply : Swagger.Value_Type; Reply : Swagger.Value_Type;
{{/returnType}} {{/returnType}}
begin begin
Client.Set_Accept (({{#hasProduces}}{{#produces}}{{#vendorExtensions.x-has-uniq-produces}}1 => {{/vendorExtensions.x-has-uniq-produces}}Swagger.Clients.{{adaMediaType}}{{#hasMore}}, {{#hasProduces}}
{{/hasMore}}{{/produces}}{{/hasProduces}}));{{#hasBodyParam}} Client.Set_Accept (({{#produces}}{{#vendorExtensions.x-has-uniq-produces}}1 => {{/vendorExtensions.x-has-uniq-produces}}Swagger.Clients.{{adaMediaType}}{{#hasMore}},
{{/hasMore}}{{/produces}}));{{/hasProduces}}{{#hasBodyParam}}
Client.Initialize (Req, ({{#hasConsumes}}{{#consumes}}{{#vendorExtensions.x-has-uniq-consumes}}1 -> {{/vendorExtensions.x-has-uniq-consumes}}Swagger.Clients.{{adaMediaType}}{{#hasMore}}, Client.Initialize (Req, ({{#hasConsumes}}{{#consumes}}{{#vendorExtensions.x-has-uniq-consumes}}1 -> {{/vendorExtensions.x-has-uniq-consumes}}Swagger.Clients.{{adaMediaType}}{{#hasMore}},
{{/hasMore}}{{/consumes}}{{/hasConsumes}}{{^hasConsumes}}1 => Swagger.Clients.APPLICATION_JSON{{/hasConsumes}}));{{#bodyParams}}{{#vendorExtensions.x-is-model-type}} {{/hasMore}}{{/consumes}}{{/hasConsumes}}{{^hasConsumes}}1 => Swagger.Clients.APPLICATION_JSON{{/hasConsumes}}));{{#bodyParams}}{{#vendorExtensions.x-is-model-type}}
{{package}}.Models.Serialize (Req.Stream, "{{baseName}}", {{paramName}});{{/vendorExtensions.x-is-model-type}}{{^vendorExtensions.x-is-model-type}}{{#isFile}} {{package}}.Models.Serialize (Req.Stream, "{{baseName}}", {{paramName}});{{/vendorExtensions.x-is-model-type}}{{^vendorExtensions.x-is-model-type}}{{#isFile}}

View File

@ -12,7 +12,7 @@ package {{package}}.Clients is
{{#operations}} {{#operations}}
{{#operation}} {{#operation}}
-- {{summary}}{{#vendorExtensions.x-has-notes}} -- {{summary}}{{#vendorExtensions.x-has-notes}}
-- {{unescapedNotes}}{{/vendorExtensions.x-has-notes}} -- {{#lambdaAdaComment}}{{unescapedNotes}}{{/lambdaAdaComment}}{{/vendorExtensions.x-has-notes}}
procedure {{operationId}} procedure {{operationId}}
(Client : in out Client_Type{{#hasParams}};{{/hasParams}}{{#allParams}} (Client : in out Client_Type{{#hasParams}};{{/hasParams}}{{#allParams}}
{{paramName}} : in {{^isFile}}{{^isString}}{{^isPrimitiveType}}{{^isContainer}}{{package}}.Models.{{/isContainer}}{{/isPrimitiveType}}{{/isString}}{{/isFile}}{{dataType}}{{#hasMore}};{{/hasMore}}{{/allParams}}{{#returnType}}; {{paramName}} : in {{^isFile}}{{^isString}}{{^isPrimitiveType}}{{^isContainer}}{{package}}.Models.{{/isContainer}}{{/isPrimitiveType}}{{/isString}}{{/isFile}}{{dataType}}{{#hasMore}};{{/hasMore}}{{/allParams}}{{#returnType}};

View File

@ -0,0 +1,43 @@
with {{package}}.Clients;
with {{package}}.Models;
with Swagger;
with Util.Http.Clients.Curl;
with Ada.Text_IO;
with Ada.Command_Line;
with Ada.Calendar.Formatting;
with Ada.Exceptions;
procedure {{package}}.Client is
use Ada.Text_IO;
procedure Usage;
Server : constant Swagger.UString := Swagger.To_UString ("http://localhost:8080/v2");
Arg_Count : constant Natural := Ada.Command_Line.Argument_Count;
Arg : Positive := 1;
procedure Usage is
begin
Put_Line ("Usage: {{projectName}} {params}...");
end Usage;
begin
if Arg_Count <= 1 then
Usage;
return;
end if;
Util.Http.Clients.Curl.Register;
declare
Command : constant String := Ada.Command_Line.Argument (Arg);
Item : constant String := Ada.Command_Line.Argument (Arg + 1);
C : {{package}}.Clients.Client_Type;
begin
C.Set_Server (Server);
Arg := Arg + 2;
exception
when E : Constraint_Error =>
Put_Line ("Constraint error raised: " & Ada.Exceptions.Exception_Message (E));
end;
end {{package}}.Client;

View File

@ -0,0 +1,88 @@
abstract project Config is
for Source_Dirs use ();
type Yes_No is ("yes", "no");
type Library_Type_Type is ("relocatable", "static");
type Mode_Type is ("distrib", "debug", "optimize", "profile");
Mode : Mode_Type := external ("MODE", "debug");
Coverage : Yes_No := External ("COVERAGE", "no");
Processors := External ("PROCESSORS", "1");
package Builder is
case Mode is
when "debug" =>
for Default_Switches ("Ada") use ("-g", "-j" & Processors);
when others =>
for Default_Switches ("Ada") use ("-g", "-O2", "-j" & Processors);
end case;
end Builder;
package compiler is
warnings := ("-gnatwua");
defaults := ("-gnat2012");
case Mode is
when "distrib" =>
for Default_Switches ("Ada") use defaults & ("-gnatafno", "-gnatVa", "-gnatwa");
when "debug" =>
for Default_Switches ("Ada") use defaults & warnings
& ("-gnata", "-gnatVaMI", "-gnaty3abcefhiklmnprstxM99");
when "optimize" =>
for Default_Switches ("Ada") use defaults & warnings
& ("-gnatn", "-gnatp", "-fdata-sections", "-ffunction-sections");
when "profile" =>
for Default_Switches ("Ada") use defaults & warnings & ("-pg");
end case;
case Coverage is
when "yes" =>
for Default_Switches ("ada") use Compiler'Default_Switches ("Ada") &
("-fprofile-arcs", "-ftest-coverage");
when others =>
end case;
end compiler;
package binder is
case Mode is
when "debug" =>
for Default_Switches ("Ada") use ("-E");
when others =>
for Default_Switches ("Ada") use ("-E");
end case;
end binder;
package linker is
case Mode is
when "profile" =>
for Default_Switches ("Ada") use ("-pg");
when "distrib" =>
for Default_Switches ("Ada") use ("-s");
when "optimize" =>
for Default_Switches ("Ada") use ("-Wl,--gc-sections");
when others =>
null;
end case;
case Coverage is
when "yes" =>
for Default_Switches ("ada") use Linker'Default_Switches ("ada") &
("-fprofile-arcs");
when others =>
end case;
end linker;
package Ide is
for VCS_Kind use "git";
end Ide;
end Config;

View File

@ -1,18 +1,21 @@
-- {{{appName}}} -- {{{appName}}}
-- {{{appDescription}}} -- {{{appDescription}}}
-- OpenAPI spec version: 1.0.0 -- OpenAPI spec version: 1.0.0
-- --
-- https://github.com/swagger-api/swagger-codegen.git -- https://github.com/swagger-api/swagger-codegen.git
-- --
-- NOTE: Auto generated by the swagger code generator program. -- NOTE: Auto generated by the swagger code generator program.
with "config"; with "config";
with "util"; with "util";
with "util_http";
with "asf"; with "asf";
with "security";
with "swagger";
project {{{projectName}}} is project {{{projectName}}} is
Mains := ("{{{appName}}}-server.adb"); Mains := ("{{{packageName}}}-{{{mainName}}}.adb");
for Main use Mains; for Main use Mains;
for Source_Dirs use ("src", "src/client", "src/server"); for Source_Dirs use ("src", "src/model", "src/{{{packageDir}}}");
for Object_Dir use "./" & Config'Exec_Dir & "/bin"; for Object_Dir use "./" & Config'Exec_Dir & "/bin";
package Binder renames Config.Binder; package Binder renames Config.Binder;

View File

@ -5,7 +5,7 @@ package body {{package}}.Models is
use Swagger.Streams; use Swagger.Streams;
{{#orderedModels}} {{#orderedModels}}
{{#model}} {{#model}}{{^isArrayModel}}
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String; Name : in String;
@ -56,7 +56,7 @@ package body {{package}}.Models is
end loop; end loop;
end Deserialize; end Deserialize;
{{/model}} {{/isArrayModel}}{{/model}}
{{/orderedModels}} {{/orderedModels}}
end {{package}}.Models; end {{package}}.Models;

View File

@ -5,11 +5,11 @@ with Swagger.Streams;
with Ada.Containers.Vectors; with Ada.Containers.Vectors;
package {{package}}.Models is package {{package}}.Models is
{{#orderedModels}}{{#model}} {{#orderedModels}}{{#model}}{{^isArrayModel}}
-- ------------------------------ {{#title}} -- ------------------------------
-- {{title}} -- {{title}}{{#description}}
-- {{description}} -- {{#lambdaAdaComment}}{{description}}{{/lambdaAdaComment}}{{/description}}
-- ------------------------------ -- ------------------------------{{/title}}
type {{classname}} is type {{classname}} is
record record
{{#vars}} {{#vars}}
@ -37,7 +37,9 @@ package {{package}}.Models is
Name : in String; Name : in String;
Value : out {{classname}}_Vectors.Vector); Value : out {{classname}}_Vectors.Vector);
{{/model}} {{/isArrayModel}}{{#isArrayModel}}
subtype {{classname}} is {{arrayModelType}}_Type_Vectors.Vector;
{{/isArrayModel}}{{/model}}
{{/orderedModels}} {{/orderedModels}}
end {{package}}.Models; end {{package}}.Models;

View File

@ -0,0 +1,14 @@
-- {{{appName}}}
-- {{{appDescription}}}
-- ------------ EDIT NOTE ------------
-- This file was generated with swagger-codegen. You can modify it to implement
-- the server. After you modify this file, you should add the following line
-- to the .swagger-codegen-ignore file:
--
-- src/{{packageName}}.ads
--
-- Then, you can drop this edit note comment.
-- ------------ EDIT NOTE ------------
package {{packageLevel1}} is
end {{packageLevel1}};

View File

@ -0,0 +1,14 @@
-- {{{appName}}}
-- {{{appDescription}}}
-- ------------ EDIT NOTE ------------
-- This file was generated with swagger-codegen. You can modify it to implement
-- the server. After you modify this file, you should add the following line
-- to the .swagger-codegen-ignore file:
--
-- src/{{packageName}}.ads
--
-- Then, you can drop this edit note comment.
-- ------------ EDIT NOTE ------------
package {{packageLevel2}} is
end {{packageLevel2}};

View File

@ -1,14 +1,30 @@
{{>licenseInfo}} -- {{{appName}}}
-- {{{appDescription}}}
-- ------------ EDIT NOTE ------------
-- This file was generated with swagger-codegen. You can modify it to implement
-- the server. After you modify this file, you should add the following line
-- to the .swagger-codegen-ignore file:
--
-- src/{{packageName}}-servers.adb
--
-- Then, you can drop this edit note comment.
-- ------------ EDIT NOTE ------------
package body {{package}}.Servers is package body {{package}}.Servers is
{{#apiInfo}} {{#apiInfo}}
{{#apis}} {{#apis}}
{{#operations}} {{#operations}}
{{#operation}} {{#operation}}
-- {{summary}} -- {{summary}}{{#vendorExtensions.x-has-notes}}
-- {{notes}} -- {{#lambdaAdaComment}}{{unescapedNotes}}{{/lambdaAdaComment}}{{/vendorExtensions.x-has-notes}}
procedure {{operationId}} ({{#allParams}}{{paramName}} : in {{dataType}}{{#hasMore}}; overriding
{{/hasMore}}{{/allParams}}) is procedure {{operationId}}
(Server : in out Server_Type{{#hasParams}};{{/hasParams}}
{{#allParams}}{{paramName}} : in {{dataType}}{{#hasMore}};
{{/hasMore}}{{/allParams}}{{#returnType}};
Result : out {{returnType}}{{/returnType}};
Context : in out Swagger.Servers.Context_Type) is
begin begin
null; null;
end {{operationId}}; end {{operationId}};
@ -16,4 +32,5 @@ package body {{package}}.Servers is
{{/operations}} {{/operations}}
{{/apis}} {{/apis}}
{{/apiInfo}} {{/apiInfo}}
end {{package}}.Servers; end {{package}}.Servers;

View File

@ -0,0 +1,22 @@
swagger.dir=web
swagger.web.enable=false
swagger.ui.enable=true
# Configuration for log4j
log4j.rootCategory=DEBUG,console,result
log4j.appender.console=Console
log4j.appender.console.level=DEBUG
log4j.appender.console.layout=level-message
log4j.appender.result=File
log4j.appender.result.File={{projectName}}.log
# Logger configuration
log4j.logger.log=WARN
log4j.logger.Util.Properties=DEBUG
log4j.logger.Util.Log=WARN
log4j.logger.Util=DEBUG
log4j.logger.ASF=DEBUG
log4j.logger.Util.Serialize.Mappers=WARN
log4j.logger.Util.Serialize.IO=INFO

View File

@ -0,0 +1,231 @@
{{>licenseInfo}}
with Swagger.Streams;
with Swagger.Servers.Operation;
package body {{package}}.Skeletons is
package body Skeleton is
{{#apiInfo}}
{{#apis}}
{{#operations}}
{{#operation}}
package API_{{operationId}} is
new Swagger.Servers.Operation (Handler => {{operationId}},
Method => Swagger.Servers.{{httpMethod}},
URI => "{{path}}");
-- {{summary}}
procedure {{operationId}}
(Req : in out Swagger.Servers.Request'Class;
Reply : in out Swagger.Servers.Response'Class;
Stream : in out Swagger.Servers.Output_Stream'Class;
Context : in out Swagger.Servers.Context_Type) is
{{#hasBodyParam}}
Input : Swagger.Value_Type;
{{/hasBodyParam}}
Impl : Implementation_Type;
{{#allParams}}
{{paramName}} : {{dataType}};
{{/allParams}}
{{#returnType}}
Result : {{returnType}};
{{/returnType}}
begin
{{#authMethods}}
{{#scopes}}
if not Context.Has_Permission (ACL_{{ident}}.Permission) then
Context.Set_Error (403, "Permission denied");
return;
end if;
{{/scopes}}
{{/authMethods}}
{{#queryParams}}
Swagger.Servers.Get_Query_Parameter (Req, "{{baseName}}", {{paramName}});
{{/queryParams}}
{{#pathParams}}
Swagger.Servers.Get_Path_Parameter (Req, {{vendorExtensions.x-path-index}}, {{paramName}});
{{/pathParams}}
{{#hasFormParams}}
{{#formParams}}
Swagger.Servers.Get_Parameter (Req, "{{baseName}}", {{paramName}});
{{/formParams}}
{{/hasFormParams}}
{{#hasParams}}
{{#hasBodyParam}}
Swagger.Servers.Read (Req, Input);
{{#bodyParams}}{{#vendorExtensions.x-is-model-type}}
{{package}}.Models.Deserialize (Input, "{{baseName}}", {{paramName}});{{/vendorExtensions.x-is-model-type}}{{^vendorExtensions.x-is-model-type}}{{#isFile}}
-- TODO: Serialize (Input.Stream, "{{basename}}", {{paramName}});{{/isFile}}{{^isFile}}{{^isLong}}
Deserialize (Input, "{{baseName}}", {{paramName}});{{/isLong}}{{#isLong}}
Deserialize (Input, "{{baseName}}", {{paramName}});{{/isLong}}{{/isFile}}{{/vendorExtensions.x-is-model-type}}{{/bodyParams}}
{{/hasBodyParam}}
Impl.{{operationId}}
({{#allParams}}{{paramName}}{{#hasMore}},
{{/hasMore}}{{/allParams}}{{#returnType}}{{#hasParams}}, {{/hasParams}}Result{{/returnType}}, Context);
{{/hasParams}}
{{^hasParams}}
{{#returnType}}
Impl.{{operationId}} (Result, Context);
{{/returnType}}
{{^returnType}}
Impl.{{operationId}} (Context);
{{/returnType}}
{{/hasParams}}
{{#returnType}}
Stream.Start_Document;{{#vendorExtensions.x-codegen-response.isString}}
Swagger.Streams.Serialize (Stream, "", Result);{{/vendorExtensions.x-codegen-response.isString}}{{^vendorExtensions.x-codegen-response.isString}}{{#returnTypeIsPrimitive}}
Swagger.Streams.Serialize (Stream, "", Result);{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}
{{package}}.Models.Serialize (Stream, "", Result);{{/returnTypeIsPrimitive}}{{/vendorExtensions.x-codegen-response.isString}}
Stream.End_Document;{{/returnType}}
end {{operationId}};
{{/operation}}
{{/operations}}
{{/apis}}
{{/apiInfo}}
procedure Register (Server : in out Swagger.Servers.Application_Type'Class) is
begin
{{#apiInfo}}
{{#apis}}
{{#operations}}
{{#operation}}
Swagger.Servers.Register (Server, API_{{operationId}}.Definition);
{{/operation}}
{{/operations}}
{{/apis}}
{{/apiInfo}}
end Register;
end Skeleton;
package body Shared_Instance is
{{#apiInfo}}
{{#apis}}
{{#operations}}
{{#operation}}
-- {{summary}}
procedure {{operationId}}
(Req : in out Swagger.Servers.Request'Class;
Reply : in out Swagger.Servers.Response'Class;
Stream : in out Swagger.Servers.Output_Stream'Class;
Context : in out Swagger.Servers.Context_Type) is
{{#hasBodyParam}}
Input : Swagger.Value_Type;
{{/hasBodyParam}}
{{#allParams}}
{{paramName}} : {{dataType}};
{{/allParams}}
{{#returnType}}
Result : {{returnType}};
{{/returnType}}
begin
{{#queryParams}}
Swagger.Servers.Get_Query_Parameter (Req, "{{baseName}}", {{paramName}});
{{/queryParams}}
{{#pathParams}}
Swagger.Servers.Get_Path_Parameter (Req, {{vendorExtensions.x-path-index}}, {{paramName}});
{{/pathParams}}
{{#hasFormParams}}
{{#formParams}}
Swagger.Servers.Get_Parameter (Req, "{{baseName}}", {{paramName}});
{{/formParams}}
{{/hasFormParams}}
{{#hasParams}}
{{#hasBodyParam}}
Swagger.Servers.Read (Req, Input);
{{#bodyParams}}{{#vendorExtensions.x-is-model-type}}
{{package}}.Models.Deserialize (Input, "{{baseName}}", {{paramName}});{{/vendorExtensions.x-is-model-type}}{{^vendorExtensions.x-is-model-type}}{{#isFile}}
-- TODO: Serialize (Input.Stream, "{{basename}}", {{paramName}});{{/isFile}}{{^isFile}}{{^isLong}}
Deserialize (Input, "{{baseName}}", {{paramName}});{{/isLong}}{{#isLong}}
Deserialize (Input, "{{baseName}}", {{paramName}});{{/isLong}}{{/isFile}}{{/vendorExtensions.x-is-model-type}}{{/bodyParams}}
{{/hasBodyParam}}
Server.{{operationId}}
({{#allParams}}{{paramName}}{{#hasMore}},
{{/hasMore}}{{/allParams}}{{#returnType}}{{#hasParams}}, {{/hasParams}}Result{{/returnType}}, Context);
{{/hasParams}}
{{^hasParams}}
{{#returnType}}
Server.{{operationId}} (Result, Context);
{{/returnType}}
{{^returnType}}
Server.{{operationId}} (Context);
{{/returnType}}
{{/hasParams}}
{{#returnType}}
Stream.Start_Document;{{#vendorExtensions.x-codegen-response.isString}}
Swagger.Streams.Serialize (Stream, "", Result);{{/vendorExtensions.x-codegen-response.isString}}{{^vendorExtensions.x-codegen-response.isString}}{{#returnTypeIsPrimitive}}
Swagger.Streams.Serialize (Stream, "", Result);{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}
{{package}}.Models.Serialize (Stream, "", Result);{{/returnTypeIsPrimitive}}{{/vendorExtensions.x-codegen-response.isString}}
Stream.End_Document;{{/returnType}}
end {{operationId}};
package API_{{operationId}} is
new Swagger.Servers.Operation (Handler => {{operationId}},
Method => Swagger.Servers.{{httpMethod}},
URI => "{{path}}");
{{/operation}}
{{/operations}}
{{/apis}}
{{/apiInfo}}
procedure Register (Server : in out Swagger.Servers.Application_Type'Class) is
begin
{{#apiInfo}}
{{#apis}}
{{#operations}}
{{#operation}}
Swagger.Servers.Register (Server, API_{{operationId}}.Definition);
{{/operation}}
{{/operations}}
{{/apis}}
{{/apiInfo}}
end Register;
protected body Server is
{{#apiInfo}}
{{#apis}}
{{#operations}}
{{#operation}}
-- {{summary}}
{{#hasParams}}
procedure {{operationId}}
({{#allParams}}{{paramName}} : in {{dataType}}{{#hasMore}};
{{/hasMore}}{{/allParams}}{{#returnType}};
Result : out {{returnType}}{{/returnType}};
Context : in out Swagger.Servers.Context_Type) is
begin
Impl.{{operationId}}
({{#allParams}}{{paramName}}{{#hasMore}},
{{/hasMore}}{{/allParams}}{{#returnType}},
Result{{/returnType}},
Context);
end {{operationId}};
{{/hasParams}}
{{^hasParams}}
{{#returnType}}
procedure {{operationId}} (Result : out {{returnType}};
Context : in out Swagger.Servers.Context_Type) is
begin
Impl.{{operationId}} (Result, Context);
end {{operationId}};
{{/returnType}}
{{^returnType}}
procedure {{operationId}} (Context : in out Swagger.Servers.Context_Type) is
begin
Impl.{{operationId}} (Context);
end {{operationId}};
{{/returnType}}
{{/hasParams}}
{{/operation}}
{{/operations}}
{{/apis}}
{{/apiInfo}}
end Server;
end Shared_Instance;
end {{package}}.Skeletons;

View File

@ -0,0 +1,115 @@
{{>licenseInfo}}
{{#imports}}with {{import}};
{{/imports}}
with Swagger.Servers;
with {{package}}.Models;
with Security.Permissions;
package {{package}}.Skeletons is
use {{package}}.Models;
type Server_Type is limited interface;
{{#authMethods}}{{#scopes}}
-- {{description}}
package ACL_{{ident}} is new Security.Permissions.Definition ("{{scope}}");
{{/scopes}}{{/authMethods}}
{{#apiInfo}}
{{#apis}}
{{#operations}}
{{#operation}}
-- {{summary}}{{#vendorExtensions.x-has-notes}}
-- {{#lambdaAdaComment}}{{unescapedNotes}}{{/lambdaAdaComment}}{{/vendorExtensions.x-has-notes}}
procedure {{operationId}}
(Server : in out Server_Type{{#hasParams}};{{/hasParams}}
{{#allParams}}{{paramName}} : in {{dataType}}{{#hasMore}};
{{/hasMore}}{{/allParams}}{{#returnType}};
Result : out {{returnType}}{{/returnType}};
Context : in out Swagger.Servers.Context_Type) is abstract;
{{/operation}}
{{/operations}}
{{/apis}}
{{/apiInfo}}
generic
type Implementation_Type is limited new Server_Type with private;
package Skeleton is
procedure Register (Server : in out Swagger.Servers.Application_Type'Class);
{{#apiInfo}}
{{#apis}}
{{#operations}}
{{#operation}}
-- {{summary}}
procedure {{operationId}}
(Req : in out Swagger.Servers.Request'Class;
Reply : in out Swagger.Servers.Response'Class;
Stream : in out Swagger.Servers.Output_Stream'Class;
Context : in out Swagger.Servers.Context_Type);
{{/operation}}
{{/operations}}
{{/apis}}
{{/apiInfo}}
end Skeleton;
generic
type Implementation_Type is limited new Server_Type with private;
package Shared_Instance is
procedure Register (Server : in out Swagger.Servers.Application_Type'Class);
{{#apiInfo}}
{{#apis}}
{{#operations}}
{{#operation}}
-- {{summary}}
procedure {{operationId}}
(Req : in out Swagger.Servers.Request'Class;
Reply : in out Swagger.Servers.Response'Class;
Stream : in out Swagger.Servers.Output_Stream'Class;
Context : in out Swagger.Servers.Context_Type);
{{/operation}}
{{/operations}}
{{/apis}}
{{/apiInfo}}
private
protected Server is
{{#apiInfo}}
{{#apis}}
{{#operations}}
{{#operation}}
-- {{summary}}
{{#hasParams}}
procedure {{operationId}}
({{#allParams}}{{paramName}} : in {{dataType}}{{#hasMore}};
{{/hasMore}}{{/allParams}}{{#returnType}};
Result : out {{returnType}}{{/returnType}};
Context : in out Swagger.Servers.Context_Type);
{{/hasParams}}
{{^hasParams}}
{{#returnType}}
procedure {{operationId}}
(Result : out {{returnType}};
Context : in out Swagger.Servers.Context_Type);
{{/returnType}}
{{^returnType}}
procedure {{operationId}} (Context : in out Swagger.Servers.Context_Type);
{{/returnType}}
{{/hasParams}}
{{/operation}}
{{/operations}}
{{/apis}}
{{/apiInfo}}
private
Impl : Implementation_Type;
end Server;
end Shared_Instance;
end {{package}}.Skeletons;

View File

@ -1,20 +1,43 @@
{{>licenseInfo}} -- {{{appName}}}
-- {{{appDescription}}}
-- ------------ EDIT NOTE ------------
-- This file was generated with swagger-codegen. You can modify it to implement
-- the server. After you modify this file, you should add the following line
-- to the .swagger-codegen-ignore file:
--
-- src/{{packageName}}-servers.ads
--
-- Then, you can drop this edit note comment.
-- ------------ EDIT NOTE ------------
{{#imports}}with {{import}}; {{#imports}}with {{import}};
{{/imports}} {{/imports}}
with Swagger.Servers;
with {{package}}.Models; with {{package}}.Models;
with {{package}}.Skeletons;
package {{package}}.Servers is package {{package}}.Servers is
use {{package}}.Models;
type Server_Type is limited new {{package}}.Skeletons.Server_Type with null record;
{{#apiInfo}} {{#apiInfo}}
{{#apis}} {{#apis}}
{{#operations}} {{#operations}}
{{#operation}} {{#operation}}
-- {{summary}} -- {{summary}}{{#vendorExtensions.x-has-notes}}
-- {{notes}} -- {{#lambdaAdaComment}}{{unescapedNotes}}{{/lambdaAdaComment}}{{/vendorExtensions.x-has-notes}}
procedure {{operationId}} ({{#allParams}}{{paramName}} : in {{dataType}}{{#hasMore}}; overriding
{{/hasMore}}{{/allParams}}); procedure {{operationId}}
(Server : in out Server_Type{{#hasParams}};{{/hasParams}}
{{#allParams}}{{paramName}} : in {{dataType}}{{#hasMore}};
{{/hasMore}}{{/allParams}}{{#returnType}};
Result : out {{returnType}}{{/returnType}};
Context : in out Swagger.Servers.Context_Type);
{{/operation}} {{/operation}}
{{/operations}} {{/operations}}
{{/apis}} {{/apis}}
{{/apiInfo}} {{/apiInfo}}
package Server_Impl is
new {{package}}.Skeletons.Shared_Instance (Server_Type);
end {{package}}.Servers; end {{package}}.Servers;

View File

@ -0,0 +1,43 @@
with Ada.IO_Exceptions;
with AWS.Config.Set;
with Swagger.Servers.AWS;
with Swagger.Servers.Applications;
with Util.Log.Loggers;
with Util.Properties;
with {{package}}.Servers;
procedure {{package}}.Server is
procedure Configure (Config : in out AWS.Config.Object);
CONFIG_PATH : constant String := "{{packageConfig}}.properties";
procedure Configure (Config : in out AWS.Config.Object) is
begin
AWS.Config.Set.Server_Port (Config, 8080);
AWS.Config.Set.Max_Connection (Config, 8);
AWS.Config.Set.Accept_Queue_Size (Config, 512);
end Configure;
App : aliased Swagger.Servers.Applications.Application_Type;
WS : Swagger.Servers.AWS.AWS_Container;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("{{package}}.Server");
Props : Util.Properties.Manager;
begin
Props.Load_Properties (CONFIG_PATH);
Util.Log.Loggers.Initialize (Props);
App.Configure (Props);
{{package}}.Servers.Server_Impl.Register (App);
WS.Configure (Configure'Access);
WS.Register_Application ("{{basePathWithoutHost}}", App'Unchecked_Access);
App.Dump_Routes (Util.Log.INFO_LEVEL);
Log.Info ("Connect you browser to: http://localhost:8080{{basePathWithoutHost}}/ui/index.html");
WS.Start;
delay 6000.0;
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH);
end {{package}}.Server;

View File

@ -0,0 +1 @@
{{{swagger-json}}}

View File

@ -1,4 +1,5 @@
io.swagger.codegen.languages.AdaCodegen io.swagger.codegen.languages.AdaCodegen
io.swagger.codegen.languages.AdaServerCodegen
io.swagger.codegen.languages.AkkaScalaClientCodegen io.swagger.codegen.languages.AkkaScalaClientCodegen
io.swagger.codegen.languages.AndroidClientCodegen io.swagger.codegen.languages.AndroidClientCodegen
io.swagger.codegen.languages.Apache2ConfigCodegen io.swagger.codegen.languages.Apache2ConfigCodegen

View File

@ -4,14 +4,16 @@
{{#description}} {{#description}}
/// <value>{{description}}</value> /// <value>{{description}}</value>
{{/description}} {{/description}}
{{#allowableValues}}{{#enumVars}}{{#-first}}{{#isString}}
[JsonConverter(typeof(StringEnumConverter))] [JsonConverter(typeof(StringEnumConverter))]
{{>visibility}} enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} {{/isString}}{{/-first}}{{/enumVars}}{{/allowableValues}}
{{>visibility}} enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{#vendorExtensions.x-enum-byte}}: byte{{/vendorExtensions.x-enum-byte}}
{ {
{{#allowableValues}}{{#enumVars}} {{#allowableValues}}{{#enumVars}}
/// <summary> /// <summary>
/// Enum {{name}} for {{{value}}} /// Enum {{name}} for value: {{{value}}}
/// </summary> /// </summary>
[EnumMember(Value = {{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}})] {{#isString}}[EnumMember(Value = "{{{value}}}")]{{/isString}}
{{name}}{{#isInteger}} = {{{value}}}{{/isInteger}}{{^isInteger}} = {{-index}}{{/isInteger}}{{^-last}}, {{name}}{{^isString}} = {{{value}}}{{/isString}}{{#isString}} = {{-index}}{{/isString}}{{^-last}},
{{/-last}}{{/enumVars}}{{/allowableValues}} {{/-last}}{{/enumVars}}{{/allowableValues}}
} }{{! NOTE: This model's enumVars is modified to look like CodegenProperty}}

View File

@ -1,19 +1,21 @@
{{^isContainer}} {{^isContainer}}
/// <summary> /// <summary>
/// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{description}}{{/description}} /// {{^description}}Defines {{{name}}}{{/description}}{{#description}}{{description}}{{/description}}
/// </summary> /// </summary>
{{#description}} {{#description}}
/// <value>{{description}}</value> /// <value>{{description}}</value>
{{/description}} {{/description}}
{{#isString}}
[JsonConverter(typeof(StringEnumConverter))] [JsonConverter(typeof(StringEnumConverter))]
{{>visibility}} enum {{#datatypeWithEnum}}{{&.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} {{/isString}}
{{>visibility}} enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{#vendorExtensions.x-enum-byte}}: byte{{/vendorExtensions.x-enum-byte}}
{ {
{{#allowableValues}}{{#enumVars}} {{#allowableValues}}{{#enumVars}}
/// <summary> /// <summary>
/// Enum {{name}} for {{{value}}} /// Enum {{name}} for value: {{{value}}}
/// </summary> /// </summary>
[EnumMember(Value = {{#isLong}}"{{/isLong}}{{#isInteger}}"{{/isInteger}}{{#isFloat}}"{{/isFloat}}{{#isDouble}}"{{/isDouble}}{{{value}}}{{#isLong}}"{{/isLong}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isFloat}}"{{/isFloat}})] {{#isString}}[EnumMember(Value = "{{{value}}}")]{{/isString}}
{{name}}{{#isLong}} = {{{value}}}{{/isLong}}{{#isInteger}} = {{{value}}}{{/isInteger}}{{^isInteger}} = {{-index}}{{/isInteger}}{{^-last}}, {{name}}{{^isString}} = {{{value}}}{{/isString}}{{#isString}} = {{-index}}{{/isString}}{{^-last}},
{{/-last}}{{/enumVars}}{{/allowableValues}} {{/-last}}{{/enumVars}}{{/allowableValues}}
} }
{{/isContainer}} {{/isContainer}}

View File

@ -0,0 +1 @@
{{{swagger-yaml}}}

View File

@ -31,6 +31,8 @@ import scala.concurrent._
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.util.{Failure, Success, Try} import scala.util.{Failure, Success, Try}
import org.json4s._
{{#operations}} {{#operations}}
class {{classname}}( class {{classname}}(
val defBasePath: String = "{{{basePath}}}", val defBasePath: String = "{{{basePath}}}",

View File

@ -31,50 +31,50 @@ namespace IO.Swagger.Model
public partial class MyClassWithOptionalInlineEnum : IEquatable<MyClassWithOptionalInlineEnum>, IValidatableObject public partial class MyClassWithOptionalInlineEnum : IEquatable<MyClassWithOptionalInlineEnum>, IValidatableObject
{ {
/// <summary> /// <summary>
/// Gets or Sets Days /// Defines Days
/// </summary> /// </summary>
[JsonConverter(typeof(StringEnumConverter))] [JsonConverter(typeof(StringEnumConverter))]
public enum DaysEnum public enum DaysEnum
{ {
/// <summary> /// <summary>
/// Enum Sun for "sun" /// Enum Sun for value: sun
/// </summary> /// </summary>
[EnumMember(Value = "sun")] [EnumMember(Value = "sun")]
Sun = 1, Sun = 1,
/// <summary> /// <summary>
/// Enum Mon for "mon" /// Enum Mon for value: mon
/// </summary> /// </summary>
[EnumMember(Value = "mon")] [EnumMember(Value = "mon")]
Mon = 2, Mon = 2,
/// <summary> /// <summary>
/// Enum Tue for "tue" /// Enum Tue for value: tue
/// </summary> /// </summary>
[EnumMember(Value = "tue")] [EnumMember(Value = "tue")]
Tue = 3, Tue = 3,
/// <summary> /// <summary>
/// Enum Wed for "wed" /// Enum Wed for value: wed
/// </summary> /// </summary>
[EnumMember(Value = "wed")] [EnumMember(Value = "wed")]
Wed = 4, Wed = 4,
/// <summary> /// <summary>
/// Enum Thu for "thu" /// Enum Thu for value: thu
/// </summary> /// </summary>
[EnumMember(Value = "thu")] [EnumMember(Value = "thu")]
Thu = 5, Thu = 5,
/// <summary> /// <summary>
/// Enum Fri for "fri" /// Enum Fri for value: fri
/// </summary> /// </summary>
[EnumMember(Value = "fri")] [EnumMember(Value = "fri")]
Fri = 6, Fri = 6,
/// <summary> /// <summary>
/// Enum Sat for "sat" /// Enum Sat for value: sat
/// </summary> /// </summary>
[EnumMember(Value = "sat")] [EnumMember(Value = "sat")]
Sat = 7 Sat = 7

View File

@ -31,50 +31,50 @@ namespace IO.Swagger.Model
public partial class MyClassWithRequiredInlineEnum : IEquatable<MyClassWithRequiredInlineEnum>, IValidatableObject public partial class MyClassWithRequiredInlineEnum : IEquatable<MyClassWithRequiredInlineEnum>, IValidatableObject
{ {
/// <summary> /// <summary>
/// Gets or Sets Days /// Defines Days
/// </summary> /// </summary>
[JsonConverter(typeof(StringEnumConverter))] [JsonConverter(typeof(StringEnumConverter))]
public enum DaysEnum public enum DaysEnum
{ {
/// <summary> /// <summary>
/// Enum Sun for "sun" /// Enum Sun for value: sun
/// </summary> /// </summary>
[EnumMember(Value = "sun")] [EnumMember(Value = "sun")]
Sun = 1, Sun = 1,
/// <summary> /// <summary>
/// Enum Mon for "mon" /// Enum Mon for value: mon
/// </summary> /// </summary>
[EnumMember(Value = "mon")] [EnumMember(Value = "mon")]
Mon = 2, Mon = 2,
/// <summary> /// <summary>
/// Enum Tue for "tue" /// Enum Tue for value: tue
/// </summary> /// </summary>
[EnumMember(Value = "tue")] [EnumMember(Value = "tue")]
Tue = 3, Tue = 3,
/// <summary> /// <summary>
/// Enum Wed for "wed" /// Enum Wed for value: wed
/// </summary> /// </summary>
[EnumMember(Value = "wed")] [EnumMember(Value = "wed")]
Wed = 4, Wed = 4,
/// <summary> /// <summary>
/// Enum Thu for "thu" /// Enum Thu for value: thu
/// </summary> /// </summary>
[EnumMember(Value = "thu")] [EnumMember(Value = "thu")]
Thu = 5, Thu = 5,
/// <summary> /// <summary>
/// Enum Fri for "fri" /// Enum Fri for value: fri
/// </summary> /// </summary>
[EnumMember(Value = "fri")] [EnumMember(Value = "fri")]
Fri = 6, Fri = 6,
/// <summary> /// <summary>
/// Enum Sat for "sat" /// Enum Sat for value: sat
/// </summary> /// </summary>
[EnumMember(Value = "sat")] [EnumMember(Value = "sat")]
Sat = 7 Sat = 7

View File

@ -27,48 +27,50 @@ namespace IO.Swagger.Model
/// <summary> /// <summary>
/// Defines WeekDays /// Defines WeekDays
/// </summary> /// </summary>
[JsonConverter(typeof(StringEnumConverter))] [JsonConverter(typeof(StringEnumConverter))]
public enum WeekDays public enum WeekDays
{ {
/// <summary> /// <summary>
/// Enum Sun for "sun" /// Enum Sun for value: sun
/// </summary> /// </summary>
[EnumMember(Value = "sun")] [EnumMember(Value = "sun")]
Sun = 1, Sun = 1,
/// <summary> /// <summary>
/// Enum Mon for "mon" /// Enum Mon for value: mon
/// </summary> /// </summary>
[EnumMember(Value = "mon")] [EnumMember(Value = "mon")]
Mon = 2, Mon = 2,
/// <summary> /// <summary>
/// Enum Tue for "tue" /// Enum Tue for value: tue
/// </summary> /// </summary>
[EnumMember(Value = "tue")] [EnumMember(Value = "tue")]
Tue = 3, Tue = 3,
/// <summary> /// <summary>
/// Enum Wed for "wed" /// Enum Wed for value: wed
/// </summary> /// </summary>
[EnumMember(Value = "wed")] [EnumMember(Value = "wed")]
Wed = 4, Wed = 4,
/// <summary> /// <summary>
/// Enum Thu for "thu" /// Enum Thu for value: thu
/// </summary> /// </summary>
[EnumMember(Value = "thu")] [EnumMember(Value = "thu")]
Thu = 5, Thu = 5,
/// <summary> /// <summary>
/// Enum Fri for "fri" /// Enum Fri for value: fri
/// </summary> /// </summary>
[EnumMember(Value = "fri")] [EnumMember(Value = "fri")]
Fri = 6, Fri = 6,
/// <summary> /// <summary>
/// Enum Sat for "sat" /// Enum Sat for value: sat
/// </summary> /// </summary>
[EnumMember(Value = "sat")] [EnumMember(Value = "sat")]
Sat = 7 Sat = 7

View File

@ -1 +1 @@
2.3.0-SNAPSHOT 2.3.0

View File

@ -1,22 +1,20 @@
version := "1.0.0" version := "1.0.0"
name := "swagger-scala-client"
name := "swagger-scala-client" organization := "io.swagger"
scalaVersion := "2.11.12"
organization := "io.swagger"
scalaVersion := "2.11.8"
libraryDependencies ++= Seq( libraryDependencies ++= Seq(
"com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.4.2", "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.9.2",
"com.sun.jersey" % "jersey-core" % "1.19", "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.9.2",
"com.sun.jersey" % "jersey-client" % "1.19", "com.sun.jersey" % "jersey-core" % "1.19.4",
"com.sun.jersey.contribs" % "jersey-multipart" % "1.19", "com.sun.jersey" % "jersey-client" % "1.19.4",
"com.sun.jersey.contribs" % "jersey-multipart" % "1.19.4",
"org.jfarcand" % "jersey-ahc-client" % "1.0.5", "org.jfarcand" % "jersey-ahc-client" % "1.0.5",
"io.swagger" % "swagger-core" % "1.5.8", "io.swagger" % "swagger-core" % "1.5.8",
"joda-time" % "joda-time" % "2.2", "joda-time" % "joda-time" % "2.9.9",
"org.joda" % "joda-convert" % "1.2", "org.joda" % "joda-convert" % "1.9.2",
"org.scalatest" %% "scalatest" % "2.2.4" % "test", "org.scalatest" %% "scalatest" % "3.0.4" % "test",
"junit" % "junit" % "4.8.1" % "test", "junit" % "junit" % "4.12" % "test",
"com.wordnik.swagger" %% "swagger-async-httpclient" % "0.3.5" "com.wordnik.swagger" %% "swagger-async-httpclient" % "0.3.5"
) )

View File

@ -1,235 +1,255 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-scala-client</artifactId> <artifactId>swagger-scala-client</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>swagger-scala-client</name> <name>swagger-scala-client</name>
<version>1.0.0</version> <version>1.0.0</version>
<prerequisites>
<maven>2.2.0</maven>
</prerequisites>
<pluginRepositories> <pluginRepositories>
<pluginRepository> <pluginRepository>
<id>maven-mongodb-plugin-repo</id> <id>maven-mongodb-plugin-repo</id>
<name>maven mongodb plugin repository</name> <name>maven mongodb plugin repository</name>
<url>http://maven-mongodb-plugin.googlecode.com/svn/maven/repo</url> <url>http://maven-mongodb-plugin.googlecode.com/svn/maven/repo</url>
<layout>default</layout> <layout>default</layout>
</pluginRepository> </pluginRepository>
</pluginRepositories> </pluginRepositories>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-enforcer-plugin</artifactId>
<version>2.12</version> <version>3.0.0-M1</version>
<configuration> <executions>
<systemProperties> <execution>
<property> <id>enforce-maven</id>
<name>loggerPath</name> <goals>
<value>conf/log4j.properties</value> <goal>enforce</goal>
</property> </goals>
</systemProperties> <configuration>
<argLine>-Xms512m -Xmx1500m</argLine> <rules>
<parallel>methods</parallel> <requireMavenVersion>
<forkMode>pertest</forkMode> <version>2.2.0</version>
</configuration> </requireMavenVersion>
</plugin> </rules>
<plugin> </configuration>
<artifactId>maven-dependency-plugin</artifactId> </execution>
<executions> </executions>
<execution> </plugin>
<phase>package</phase> <plugin>
<goals> <groupId>org.apache.maven.plugins</groupId>
<goal>copy-dependencies</goal> <artifactId>maven-surefire-plugin</artifactId>
</goals> <version>2.12</version>
<configuration> <configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory> <systemProperties>
</configuration> <property>
</execution> <name>loggerPath</name>
</executions> <value>conf/log4j.properties</value>
</plugin> </property>
</systemProperties>
<argLine>-Xms512m -Xmx1500m</argLine>
<parallel>methods</parallel>
<forkMode>pertest</forkMode>
</configuration>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<!-- attach test jar --> <!-- attach test jar -->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<version>2.2</version> <version>2.2</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
<goal>jar</goal> <goal>jar</goal>
<goal>test-jar</goal> <goal>test-jar</goal>
</goals> </goals>
</execution> </execution>
</executions> </executions>
<configuration> <configuration>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId> <artifactId>build-helper-maven-plugin</artifactId>
<version>1.9.1</version> <version>1.9.1</version>
<executions> <executions>
<execution> <execution>
<id>add_sources</id> <id>add_sources</id>
<phase>generate-sources</phase> <phase>generate-sources</phase>
<goals> <goals>
<goal>add-source</goal> <goal>add-source</goal>
</goals> </goals>
<configuration> <configuration>
<sources> <sources>
<source>src/main/java</source> <source>
</sources> src/main/java</source>
</configuration> </sources>
</execution> </configuration>
<execution> </execution>
<id>add_test_sources</id> <execution>
<phase>generate-test-sources</phase> <id>add_test_sources</id>
<goals> <phase>generate-test-sources</phase>
<goal>add-test-source</goal> <goals>
</goals> <goal>add-test-source</goal>
<configuration> </goals>
<sources> <configuration>
<source>src/test/java</source> <sources>
</sources> <source>
</configuration> src/test/java</source>
</execution> </sources>
</executions> </configuration>
</plugin> </execution>
<plugin> </executions>
<groupId>org.apache.maven.plugins</groupId> </plugin>
<artifactId>maven-compiler-plugin</artifactId> <plugin>
<version>3.6.1</version> <groupId>org.apache.maven.plugins</groupId>
<configuration> <artifactId>maven-compiler-plugin</artifactId>
<source>1.7</source> <version>3.6.1</version>
<target>1.7</target> <configuration>
</configuration> <source>
</plugin> 1.7</source>
<plugin> <target>1.7</target>
<groupId>net.alchim31.maven</groupId> </configuration>
<artifactId>scala-maven-plugin</artifactId> </plugin>
<version>${scala-maven-plugin-version}</version> <plugin>
<executions> <groupId>net.alchim31.maven</groupId>
<execution> <artifactId>scala-maven-plugin</artifactId>
<id>scala-compile-first</id> <version>${scala-maven-plugin-version}</version>
<phase>process-resources</phase> <executions>
<goals> <execution>
<goal>add-source</goal> <id>scala-compile-first</id>
<goal>compile</goal> <phase>process-resources</phase>
</goals> <goals>
</execution> <goal>add-source</goal>
<execution> <goal>compile</goal>
<id>scala-test-compile</id> </goals>
<phase>process-test-resources</phase> </execution>
<goals> <execution>
<goal>testCompile</goal> <id>scala-test-compile</id>
</goals> <phase>process-test-resources</phase>
</execution> <goals>
</executions> <goal>testCompile</goal>
<configuration> </goals>
<jvmArgs> </execution>
<jvmArg>-Xms128m</jvmArg> </executions>
<jvmArg>-Xmx1500m</jvmArg> <configuration>
</jvmArgs> <jvmArgs>
</configuration> <jvmArg>-Xms128m</jvmArg>
</plugin> <jvmArg>-Xmx1500m</jvmArg>
</plugins> </jvmArgs>
</build> </configuration>
<reporting> </plugin>
<plugins> </plugins>
<plugin> </build>
<groupId>org.scala-tools</groupId> <reporting>
<artifactId>maven-scala-plugin</artifactId> <plugins>
<configuration> <plugin>
<scalaVersion>${scala-version}</scalaVersion> <groupId>org.scala-tools</groupId>
</configuration> <artifactId>maven-scala-plugin</artifactId>
</plugin> <configuration>
</plugins> <scalaVersion>${scala-version}</scalaVersion>
</reporting> </configuration>
<dependencies> </plugin>
<dependency> </plugins>
<groupId>com.fasterxml.jackson.module</groupId> </reporting>
<artifactId>jackson-module-scala_2.11</artifactId> <dependencies>
<version>${jackson-version}</version> <dependency>
</dependency> <groupId>com.fasterxml.jackson.module</groupId>
<dependency> <artifactId>jackson-module-scala_2.11</artifactId>
<groupId>com.fasterxml.jackson.datatype</groupId> <version>${jackson-version}</version>
<artifactId>jackson-datatype-joda</artifactId> </dependency>
<version>${jackson-version}</version> <dependency>
</dependency> <groupId>com.fasterxml.jackson.datatype</groupId>
<dependency> <artifactId>jackson-datatype-joda</artifactId>
<groupId>com.sun.jersey</groupId> <version>${jackson-version}</version>
<artifactId>jersey-client</artifactId> </dependency>
<version>${jersey-version}</version> <dependency>
</dependency> <groupId>com.sun.jersey</groupId>
<dependency> <artifactId>jersey-client</artifactId>
<groupId>com.sun.jersey.contribs</groupId> <version>${jersey-version}</version>
<artifactId>jersey-multipart</artifactId> </dependency>
<version>${jersey-version}</version> <dependency>
</dependency> <groupId>com.sun.jersey.contribs</groupId>
<dependency> <artifactId>jersey-multipart</artifactId>
<groupId>org.jfarcand</groupId> <version>${jersey-version}</version>
<artifactId>jersey-ahc-client</artifactId> </dependency>
<version>${jersey-async-version}</version> <dependency>
<scope>compile</scope> <groupId>org.jfarcand</groupId>
</dependency> <artifactId>jersey-ahc-client</artifactId>
<dependency> <version>${jersey-async-version}</version>
<groupId>org.scala-lang</groupId> <scope>compile</scope>
<artifactId>scala-library</artifactId> </dependency>
<version>${scala-version}</version> <dependency>
</dependency> <groupId>org.scala-lang</groupId>
<dependency> <artifactId>scala-library</artifactId>
<groupId>io.swagger</groupId> <version>${scala-version}</version>
<artifactId>swagger-core</artifactId> </dependency>
<version>${swagger-core-version}</version> <dependency>
</dependency> <groupId>io.swagger</groupId>
<dependency> <artifactId>swagger-core</artifactId>
<groupId>org.scalatest</groupId> <version>${swagger-core-version}</version>
<artifactId>scalatest_2.11</artifactId> </dependency>
<version>${scala-test-version}</version> <dependency>
<scope>test</scope> <groupId>org.scalatest</groupId>
</dependency> <artifactId>scalatest_2.11</artifactId>
<dependency> <version>${scala-test-version}</version>
<groupId>junit</groupId> <scope>test</scope>
<artifactId>junit</artifactId> </dependency>
<version>${junit-version}</version> <dependency>
<scope>test</scope> <groupId>junit</groupId>
</dependency> <artifactId>junit</artifactId>
<dependency> <version>${junit-version}</version>
<groupId>joda-time</groupId> <scope>test</scope>
<artifactId>joda-time</artifactId> </dependency>
<version>${joda-time-version}</version> <dependency>
</dependency> <groupId>joda-time</groupId>
<dependency> <artifactId>joda-time</artifactId>
<groupId>org.joda</groupId> <version>${joda-time-version}</version>
<artifactId>joda-convert</artifactId> </dependency>
<version>${joda-version}</version> <dependency>
</dependency> <groupId>org.joda</groupId>
<dependency> <artifactId>joda-convert</artifactId>
<groupId>com.wordnik.swagger</groupId> <version>${joda-version}</version>
<artifactId>swagger-async-httpclient_2.11</artifactId> </dependency>
<version>${swagger-async-httpclient-version}</version> <dependency>
</dependency> <groupId>com.wordnik.swagger</groupId>
</dependencies> <artifactId>swagger-async-httpclient_2.11</artifactId>
<properties> <version>${swagger-async-httpclient-version}</version>
<scala-version>2.11.12</scala-version> </dependency>
<joda-version>1.2</joda-version> </dependencies>
<joda-time-version>2.2</joda-time-version> <properties>
<jersey-version>1.19</jersey-version> <scala-version>2.11.12</scala-version>
<swagger-core-version>1.5.16</swagger-core-version> <joda-version>1.9.2</joda-version>
<jersey-async-version>1.0.5</jersey-async-version> <joda-time-version>2.9.9</joda-time-version>
<maven-plugin.version>1.0.0</maven-plugin.version> <jersey-version>1.19.4</jersey-version>
<jackson-version>2.8.9</jackson-version> <swagger-core-version>1.5.16</swagger-core-version>
<jersey-async-version>1.0.5</jersey-async-version>
<maven-plugin.version>1.0.0</maven-plugin.version>
<jackson-version>2.9.2</jackson-version>
<junit-version>4.8.1</junit-version> <junit-version>4.12</junit-version>
<scala-maven-plugin-version>3.1.5</scala-maven-plugin-version> <scala-maven-plugin-version>3.1.5</scala-maven-plugin-version>
<scala-test-version>2.2.4</scala-test-version> <scala-test-version>3.0.4</scala-test-version>
<swagger-async-httpclient-version>0.3.5</swagger-async-httpclient-version> <swagger-async-httpclient-version>0.3.5</swagger-async-httpclient-version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
</project> </project>

View File

@ -38,7 +38,7 @@ import com.fasterxml.jackson.annotation._
import com.fasterxml.jackson.databind.annotation.JsonSerialize import com.fasterxml.jackson.databind.annotation.JsonSerialize
object ScalaJsonUtil { object ScalaJsonUtil {
def getJsonMapper = { def getJsonMapper: ObjectMapper = {
val mapper = new ObjectMapper() val mapper = new ObjectMapper()
mapper.registerModule(new DefaultScalaModule()) mapper.registerModule(new DefaultScalaModule())
mapper.registerModule(new JodaModule()) mapper.registerModule(new JodaModule())
@ -130,9 +130,8 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper,
val builder = client.resource(host + path + querystring).accept(contentType) val builder = client.resource(host + path + querystring).accept(contentType)
headerParams.map(p => builder.header(p._1, p._2)) headerParams.map(p => builder.header(p._1, p._2))
defaultHeaders.foreach(p => { defaultHeaders.foreach(p => {
headerParams.contains(p._1) match { if (!headerParams.contains(p._1) && p._2 != null) {
case true => // override default with supplied header builder.header(p._1, p._2)
case false => if (p._2 != null) builder.header(p._1, p._2)
} }
}) })
var formData: MultivaluedMapImpl = null var formData: MultivaluedMapImpl = null
@ -142,7 +141,7 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper,
} }
val response: ClientResponse = method match { val response: ClientResponse = method match {
case "GET" => builder.get(classOf[ClientResponse]).asInstanceOf[ClientResponse] case "GET" => builder.get(classOf[ClientResponse])
case "POST" => case "POST" =>
if (formData != null && formData.size() > 0) { if (formData != null && formData.size() > 0) {
builder.post(classOf[ClientResponse], formData) builder.post(classOf[ClientResponse], formData)
@ -181,46 +180,48 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper,
response.getStatusInfo.getStatusCode match { response.getStatusInfo.getStatusCode match {
case 204 => "" case 204 => ""
case code: Int if Range(200, 299).contains(code) => case code: Int if Range(200, 299).contains(code) =>
response.hasEntity match { if (response.hasEntity) {
case true => response.getEntity(classOf[String]) response.getEntity(classOf[String])
case false => "" } else {
""
} }
case _ => case _ =>
val entity = response.hasEntity match { val entity = if (response.hasEntity) {
case true => response.getEntity(classOf[String]) response.getEntity(classOf[String])
case false => "no data" } else {
"no data"
} }
throw new ApiException(response.getStatusInfo.getStatusCode, entity) throw new ApiException(response.getStatusInfo.getStatusCode, entity)
} }
} }
def getClient(host: String): Client = { def getClient(host: String): Client = {
hostMap.contains(host) match { if (hostMap.contains(host)) {
case true => hostMap(host) hostMap(host)
case false => } else {
val client = newClient(host) val client = newClient(host)
// client.addFilter(new LoggingFilter()) // client.addFilter(new LoggingFilter())
hostMap += host -> client hostMap += host -> client
client client
} }
} }
def newClient(host: String): Client = asyncHttpClient match { def newClient(host: String): Client = if (asyncHttpClient) {
case true => import com.ning.http.client.Realm
import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig import org.sonatype.spice.jersey.client.ahc.AhcHttpClient
import org.sonatype.spice.jersey.client.ahc.AhcHttpClient import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig
import com.ning.http.client.Realm
val config: DefaultAhcConfig = new DefaultAhcConfig() val config: DefaultAhcConfig = new DefaultAhcConfig()
if (!authScheme.isEmpty) { if (!authScheme.isEmpty) {
val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme) val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme)
config config
.getAsyncHttpClientConfigBuilder .getAsyncHttpClientConfigBuilder
.setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum) .setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum)
.setUsePreemptiveAuth(authPreemptive).build) .setUsePreemptiveAuth(authPreemptive).build)
} }
AhcHttpClient.create(config) AhcHttpClient.create(config)
case _ => Client.create() } else {
Client.create()
} }
} }

View File

@ -7,8 +7,8 @@ import com.wordnik.swagger.client._
import java.io.Closeable import java.io.Closeable
class AsyncClient(config: SwaggerConfig) extends Closeable { class AsyncClient(config: SwaggerConfig) extends Closeable {
val locator = config.locator lazy val locator: ServiceLocator = config.locator
val name = config.name lazy val name: String = config.name
private[this] val client = transportClient private[this] val client = transportClient

View File

@ -40,6 +40,8 @@ import scala.concurrent._
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.util.{Failure, Success, Try} import scala.util.{Failure, Success, Try}
import org.json4s._
class FakeApi( class FakeApi(
val defBasePath: String = "https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r", val defBasePath: String = "https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r",
defApiInvoker: ApiInvoker = ApiInvoker defApiInvoker: ApiInvoker = ApiInvoker
@ -48,12 +50,12 @@ class FakeApi(
implicit val formats = new org.json4s.DefaultFormats { implicit val formats = new org.json4s.DefaultFormats {
override def dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+0000") override def dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+0000")
} }
implicit val stringReader = ClientResponseReaders.StringReader implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader
implicit val unitReader = ClientResponseReaders.UnitReader implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader
implicit val jvalueReader = ClientResponseReaders.JValueReader implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader
implicit val jsonReader = JsonFormatsReader implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader
implicit val stringWriter = RequestWriters.StringWriter implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter
implicit val jsonWriter = JsonFormatsWriter implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter
var basePath: String = defBasePath var basePath: String = defBasePath
var apiInvoker: ApiInvoker = defApiInvoker var apiInvoker: ApiInvoker = defApiInvoker
@ -62,13 +64,14 @@ class FakeApi(
apiInvoker.defaultHeaders += key -> value apiInvoker.defaultHeaders += key -> value
} }
val config = SwaggerConfig.forUrl(new URI(defBasePath)) val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath))
val client = new RestClient(config) val client = new RestClient(config)
val helper = new FakeApiAsyncHelper(client, config) val helper = new FakeApiAsyncHelper(client, config)
/** /**
* To test code injection *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r * To test code injection *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r
* *
*
* @param testCodeInjectEndRnNR To test code injection *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r (optional) * @param testCodeInjectEndRnNR To test code injection *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r (optional)
* @return void * @return void
*/ */
@ -83,9 +86,10 @@ class FakeApi(
/** /**
* To test code injection *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r asynchronously * To test code injection *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r asynchronously
* *
*
* @param testCodeInjectEndRnNR To test code injection *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r (optional) * @param testCodeInjectEndRnNR To test code injection *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r (optional)
* @return Future(void) * @return Future(void)
*/ */
def testCodeInject * &#39; &quot; &#x3D;end rn n rAsync(testCodeInjectEndRnNR: Option[String] = None) = { def testCodeInject * &#39; &quot; &#x3D;end rn n rAsync(testCodeInjectEndRnNR: Option[String] = None) = {
helper.testCodeInject * &#39; &quot; &#x3D;end rn n r(testCodeInjectEndRnNR) helper.testCodeInject * &#39; &quot; &#x3D;end rn n r(testCodeInjectEndRnNR)
} }

View File

@ -14,7 +14,7 @@ package io.swagger.client.model
case class ModelReturn ( case class ModelReturn (
/* property description *_/ ' \" =end -- \\r\\n \\n \\r */ // property description *_/ ' \" =end -- \\r\\n \\n \\r
_return: Option[Integer] = None _return: Option[Integer] = None
) )

View File

@ -21,3 +21,4 @@
#docs/*.md #docs/*.md
# Then explicitly reverse the ignore rule for a single file: # Then explicitly reverse the ignore rule for a single file:
#!docs/README.md #!docs/README.md
petstore.gpr

View File

@ -1,14 +1,22 @@
-- Swagger Petstore
-- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special_key` to test the authorization filters.
-- OpenAPI spec version: 1.0.0
--
-- https://github.com/swagger-api/swagger-codegen.git
--
-- NOTE: Auto generated by the swagger code generator program.
with "config"; with "config";
with "util"; with "util";
with "util_http"; with "util_http";
with "asf";
with "security";
with "swagger"; with "swagger";
project Petstore is project Petstore is
Mains := ("petstore.adb"); Mains := ("petstore.adb");
for Main use Mains; for Main use Mains;
for Source_Dirs use ("src", "src/client"); for Source_Dirs use ("src", "src/model", "src/client");
for Object_Dir use "./obj"; for Object_Dir use "./" & Config'Exec_Dir & "/bin";
for Exec_Dir use "./bin";
package Binder renames Config.Binder; package Binder renames Config.Binder;
package Builder renames Config.Builder; package Builder renames Config.Builder;

View File

@ -1,5 +1,5 @@
-- Swagger Petstore -- Swagger Petstore
-- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. -- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special_key` to test the authorization filters.
-- --
-- OpenAPI spec version: 1.0.0 -- OpenAPI spec version: 1.0.0
-- Contact: apiteam@swagger.io -- Contact: apiteam@swagger.io
@ -31,7 +31,7 @@ package body Samples.Petstore.Clients is
procedure Delete_Pet procedure Delete_Pet
(Client : in out Client_Type; (Client : in out Client_Type;
Pet_Id : in Swagger.Long; Pet_Id : in Swagger.Long;
Api_Key : in Swagger.UString) is Api_Key : in Swagger.Nullable_UString) is
URI : Swagger.Clients.URI_Type; URI : Swagger.Clients.URI_Type;
begin begin
Client.Set_Accept ((Swagger.Clients.APPLICATION_XML, Client.Set_Accept ((Swagger.Clients.APPLICATION_XML,
@ -46,7 +46,7 @@ package body Samples.Petstore.Clients is
-- Multiple status values can be provided with comma separated strings -- Multiple status values can be provided with comma separated strings
procedure Find_Pets_By_Status procedure Find_Pets_By_Status
(Client : in out Client_Type; (Client : in out Client_Type;
Status : in Swagger.UString_Vectors.Vector; Status : in Swagger.Nullable_UString_Vectors.Vector;
Result : out Samples.Petstore.Models.Pet_Type_Vectors.Vector) is Result : out Samples.Petstore.Models.Pet_Type_Vectors.Vector) is
URI : Swagger.Clients.URI_Type; URI : Swagger.Clients.URI_Type;
Reply : Swagger.Value_Type; Reply : Swagger.Value_Type;
@ -64,7 +64,7 @@ package body Samples.Petstore.Clients is
-- Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. -- Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
procedure Find_Pets_By_Tags procedure Find_Pets_By_Tags
(Client : in out Client_Type; (Client : in out Client_Type;
Tags : in Swagger.UString_Vectors.Vector; Tags : in Swagger.Nullable_UString_Vectors.Vector;
Result : out Samples.Petstore.Models.Pet_Type_Vectors.Vector) is Result : out Samples.Petstore.Models.Pet_Type_Vectors.Vector) is
URI : Swagger.Clients.URI_Type; URI : Swagger.Clients.URI_Type;
Reply : Swagger.Value_Type; Reply : Swagger.Value_Type;
@ -117,8 +117,8 @@ package body Samples.Petstore.Clients is
procedure Update_Pet_With_Form procedure Update_Pet_With_Form
(Client : in out Client_Type; (Client : in out Client_Type;
Pet_Id : in Swagger.Long; Pet_Id : in Swagger.Long;
Name : in Swagger.UString; Name : in Swagger.Nullable_UString;
Status : in Swagger.UString) is Status : in Swagger.Nullable_UString) is
URI : Swagger.Clients.URI_Type; URI : Swagger.Clients.URI_Type;
Req : Swagger.Clients.Request_Type; Req : Swagger.Clients.Request_Type;
begin begin
@ -137,8 +137,8 @@ package body Samples.Petstore.Clients is
procedure Upload_File procedure Upload_File
(Client : in out Client_Type; (Client : in out Client_Type;
Pet_Id : in Swagger.Long; Pet_Id : in Swagger.Long;
Additional_Metadata : in Swagger.UString; Additional_Metadata : in Swagger.Nullable_UString;
File : in Swagger.Http_Content_Type; File : in Swagger.File_Part_Type;
Result : out Samples.Petstore.Models.ApiResponse_Type) is Result : out Samples.Petstore.Models.ApiResponse_Type) is
URI : Swagger.Clients.URI_Type; URI : Swagger.Clients.URI_Type;
Req : Swagger.Clients.Request_Type; Req : Swagger.Clients.Request_Type;
@ -156,7 +156,7 @@ package body Samples.Petstore.Clients is
end Upload_File; end Upload_File;
-- Delete purchase order by ID -- Delete purchase order by ID
-- For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors -- For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
procedure Delete_Order procedure Delete_Order
(Client : in out Client_Type; (Client : in out Client_Type;
Order_Id : in Swagger.UString) is Order_Id : in Swagger.UString) is
@ -174,7 +174,7 @@ package body Samples.Petstore.Clients is
-- Returns a map of status codes to quantities -- Returns a map of status codes to quantities
procedure Get_Inventory procedure Get_Inventory
(Client : in out Client_Type; (Client : in out Client_Type;
Result : out Swagger.Integer_Map) is Result : out Swagger.Nullable_Integer_Map) is
URI : Swagger.Clients.URI_Type; URI : Swagger.Clients.URI_Type;
Reply : Swagger.Value_Type; Reply : Swagger.Value_Type;
begin begin
@ -186,7 +186,7 @@ package body Samples.Petstore.Clients is
end Get_Inventory; end Get_Inventory;
-- Find purchase order by ID -- Find purchase order by ID
-- For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions -- For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
procedure Get_Order_By_Id procedure Get_Order_By_Id
(Client : in out Client_Type; (Client : in out Client_Type;
Order_Id : in Swagger.Long; Order_Id : in Swagger.Long;

View File

@ -1,5 +1,5 @@
-- Swagger Petstore -- Swagger Petstore
-- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. -- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special_key` to test the authorization filters.
-- --
-- OpenAPI spec version: 1.0.0 -- OpenAPI spec version: 1.0.0
-- Contact: apiteam@swagger.io -- Contact: apiteam@swagger.io
@ -22,20 +22,20 @@ package Samples.Petstore.Clients is
procedure Delete_Pet procedure Delete_Pet
(Client : in out Client_Type; (Client : in out Client_Type;
Pet_Id : in Swagger.Long; Pet_Id : in Swagger.Long;
Api_Key : in Swagger.UString); Api_Key : in Swagger.Nullable_UString);
-- Finds Pets by status -- Finds Pets by status
-- Multiple status values can be provided with comma separated strings -- Multiple status values can be provided with comma separated strings
procedure Find_Pets_By_Status procedure Find_Pets_By_Status
(Client : in out Client_Type; (Client : in out Client_Type;
Status : in Swagger.UString_Vectors.Vector; Status : in Swagger.Nullable_UString_Vectors.Vector;
Result : out Samples.Petstore.Models.Pet_Type_Vectors.Vector); Result : out Samples.Petstore.Models.Pet_Type_Vectors.Vector);
-- Finds Pets by tags -- Finds Pets by tags
-- Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. -- Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
procedure Find_Pets_By_Tags procedure Find_Pets_By_Tags
(Client : in out Client_Type; (Client : in out Client_Type;
Tags : in Swagger.UString_Vectors.Vector; Tags : in Swagger.Nullable_UString_Vectors.Vector;
Result : out Samples.Petstore.Models.Pet_Type_Vectors.Vector); Result : out Samples.Petstore.Models.Pet_Type_Vectors.Vector);
-- Find pet by ID -- Find pet by ID
@ -54,19 +54,19 @@ package Samples.Petstore.Clients is
procedure Update_Pet_With_Form procedure Update_Pet_With_Form
(Client : in out Client_Type; (Client : in out Client_Type;
Pet_Id : in Swagger.Long; Pet_Id : in Swagger.Long;
Name : in Swagger.UString; Name : in Swagger.Nullable_UString;
Status : in Swagger.UString); Status : in Swagger.Nullable_UString);
-- uploads an image -- uploads an image
procedure Upload_File procedure Upload_File
(Client : in out Client_Type; (Client : in out Client_Type;
Pet_Id : in Swagger.Long; Pet_Id : in Swagger.Long;
Additional_Metadata : in Swagger.UString; Additional_Metadata : in Swagger.Nullable_UString;
File : in Swagger.Http_Content_Type; File : in Swagger.File_Part_Type;
Result : out Samples.Petstore.Models.ApiResponse_Type); Result : out Samples.Petstore.Models.ApiResponse_Type);
-- Delete purchase order by ID -- Delete purchase order by ID
-- For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors -- For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
procedure Delete_Order procedure Delete_Order
(Client : in out Client_Type; (Client : in out Client_Type;
Order_Id : in Swagger.UString); Order_Id : in Swagger.UString);
@ -75,10 +75,10 @@ package Samples.Petstore.Clients is
-- Returns a map of status codes to quantities -- Returns a map of status codes to quantities
procedure Get_Inventory procedure Get_Inventory
(Client : in out Client_Type; (Client : in out Client_Type;
Result : out Swagger.Integer_Map); Result : out Swagger.Nullable_Integer_Map);
-- Find purchase order by ID -- Find purchase order by ID
-- For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions -- For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
procedure Get_Order_By_Id procedure Get_Order_By_Id
(Client : in out Client_Type; (Client : in out Client_Type;
Order_Id : in Swagger.Long; Order_Id : in Swagger.Long;

View File

@ -1,5 +1,5 @@
-- Swagger Petstore -- Swagger Petstore
-- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. -- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special_key` to test the authorization filters.
-- --
-- OpenAPI spec version: 1.0.0 -- OpenAPI spec version: 1.0.0
-- Contact: apiteam@swagger.io -- Contact: apiteam@swagger.io
@ -13,6 +13,7 @@ package body Samples.Petstore.Models is
use Swagger.Streams; use Swagger.Streams;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String; Name : in String;
Value : in ApiResponse_Type) is Value : in ApiResponse_Type) is
@ -61,6 +62,8 @@ package body Samples.Petstore.Models is
end Deserialize; end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String; Name : in String;
Value : in Category_Type) is Value : in Category_Type) is
@ -107,6 +110,8 @@ package body Samples.Petstore.Models is
end Deserialize; end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String; Name : in String;
Value : in Tag_Type) is Value : in Tag_Type) is
@ -153,6 +158,8 @@ package body Samples.Petstore.Models is
end Deserialize; end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String; Name : in String;
Value : in User_Type) is Value : in User_Type) is
@ -211,6 +218,8 @@ package body Samples.Petstore.Models is
end Deserialize; end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String; Name : in String;
Value : in Order_Type) is Value : in Order_Type) is
@ -265,6 +274,8 @@ package body Samples.Petstore.Models is
end Deserialize; end Deserialize;
procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class;
Name : in String; Name : in String;
Value : in Pet_Type) is Value : in Pet_Type) is
@ -319,4 +330,5 @@ package body Samples.Petstore.Models is
end Deserialize; end Deserialize;
end Samples.Petstore.Models; end Samples.Petstore.Models;

View File

@ -1,5 +1,5 @@
-- Swagger Petstore -- Swagger Petstore
-- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. -- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special_key` to test the authorization filters.
-- --
-- OpenAPI spec version: 1.0.0 -- OpenAPI spec version: 1.0.0
-- Contact: apiteam@swagger.io -- Contact: apiteam@swagger.io
@ -18,9 +18,9 @@ package Samples.Petstore.Models is
-- ------------------------------ -- ------------------------------
type ApiResponse_Type is type ApiResponse_Type is
record record
Code : Integer; Code : Swagger.Nullable_Integer;
P_Type : Swagger.UString; P_Type : Swagger.Nullable_UString;
Message : Swagger.UString; Message : Swagger.Nullable_UString;
end record; end record;
package ApiResponse_Type_Vectors is package ApiResponse_Type_Vectors is
@ -44,14 +44,15 @@ package Samples.Petstore.Models is
Value : out ApiResponse_Type_Vectors.Vector); Value : out ApiResponse_Type_Vectors.Vector);
-- ------------------------------ -- ------------------------------
-- Pet category -- Pet category
-- A category for a pet -- A category for a pet
-- ------------------------------ -- ------------------------------
type Category_Type is type Category_Type is
record record
Id : Swagger.Long; Id : Swagger.Nullable_Long;
Name : Swagger.UString; Name : Swagger.Nullable_UString;
end record; end record;
package Category_Type_Vectors is package Category_Type_Vectors is
@ -75,14 +76,15 @@ package Samples.Petstore.Models is
Value : out Category_Type_Vectors.Vector); Value : out Category_Type_Vectors.Vector);
-- ------------------------------ -- ------------------------------
-- Pet Tag -- Pet Tag
-- A tag for a pet -- A tag for a pet
-- ------------------------------ -- ------------------------------
type Tag_Type is type Tag_Type is
record record
Id : Swagger.Long; Id : Swagger.Nullable_Long;
Name : Swagger.UString; Name : Swagger.Nullable_UString;
end record; end record;
package Tag_Type_Vectors is package Tag_Type_Vectors is
@ -106,20 +108,21 @@ package Samples.Petstore.Models is
Value : out Tag_Type_Vectors.Vector); Value : out Tag_Type_Vectors.Vector);
-- ------------------------------ -- ------------------------------
-- a User -- a User
-- A User who is purchasing from the pet store -- A User who is purchasing from the pet store
-- ------------------------------ -- ------------------------------
type User_Type is type User_Type is
record record
Id : Swagger.Long; Id : Swagger.Nullable_Long;
Username : Swagger.UString; Username : Swagger.Nullable_UString;
First_Name : Swagger.UString; First_Name : Swagger.Nullable_UString;
Last_Name : Swagger.UString; Last_Name : Swagger.Nullable_UString;
Email : Swagger.UString; Email : Swagger.Nullable_UString;
Password : Swagger.UString; Password : Swagger.Nullable_UString;
Phone : Swagger.UString; Phone : Swagger.Nullable_UString;
User_Status : Integer; User_Status : Swagger.Nullable_Integer;
end record; end record;
package User_Type_Vectors is package User_Type_Vectors is
@ -143,18 +146,19 @@ package Samples.Petstore.Models is
Value : out User_Type_Vectors.Vector); Value : out User_Type_Vectors.Vector);
-- ------------------------------ -- ------------------------------
-- Pet Order -- Pet Order
-- An order for a pets from the pet store -- An order for a pets from the pet store
-- ------------------------------ -- ------------------------------
type Order_Type is type Order_Type is
record record
Id : Swagger.Long; Id : Swagger.Nullable_Long;
Pet_Id : Swagger.Long; Pet_Id : Swagger.Nullable_Long;
Quantity : Integer; Quantity : Swagger.Nullable_Integer;
Ship_Date : Swagger.Datetime; Ship_Date : Swagger.Nullable_Date;
Status : Swagger.UString; Status : Swagger.Nullable_UString;
Complete : Boolean; Complete : Swagger.Nullable_Boolean;
end record; end record;
package Order_Type_Vectors is package Order_Type_Vectors is
@ -178,18 +182,19 @@ package Samples.Petstore.Models is
Value : out Order_Type_Vectors.Vector); Value : out Order_Type_Vectors.Vector);
-- ------------------------------ -- ------------------------------
-- a Pet -- a Pet
-- A pet for sale in the pet store -- A pet for sale in the pet store
-- ------------------------------ -- ------------------------------
type Pet_Type is type Pet_Type is
record record
Id : Swagger.Long; Id : Swagger.Nullable_Long;
Category : Samples.Petstore.Models.Category_Type; Category : Samples.Petstore.Models.Category_Type;
Name : Swagger.UString; Name : Swagger.UString;
Photo_Urls : Swagger.UString_Vectors.Vector; Photo_Urls : Swagger.Nullable_UString_Vectors.Vector;
Tags : Samples.Petstore.Models.Tag_Type_Vectors.Vector; Tags : Samples.Petstore.Models.Tag_Type_Vectors.Vector;
Status : Swagger.UString; Status : Swagger.Nullable_UString;
end record; end record;
package Pet_Type_Vectors is package Pet_Type_Vectors is
@ -213,4 +218,5 @@ package Samples.Petstore.Models is
Value : out Pet_Type_Vectors.Vector); Value : out Pet_Type_Vectors.Vector);
end Samples.Petstore.Models; end Samples.Petstore.Models;

View File

@ -5,10 +5,12 @@ with Util.Http.Clients.Curl;
with Ada.Text_IO; with Ada.Text_IO;
with Ada.Command_Line; with Ada.Command_Line;
with Ada.Calendar.Formatting; with Ada.Calendar.Formatting;
with Ada.Strings.Unbounded;
with Ada.Exceptions; with Ada.Exceptions;
procedure Test is procedure Test is
use Ada.Text_IO; use Ada.Text_IO;
use type Ada.Strings.Unbounded.Unbounded_String;
procedure Usage; procedure Usage;
procedure Print_Pet (Pet : in Samples.Petstore.Models.Pet_Type); procedure Print_Pet (Pet : in Samples.Petstore.Models.Pet_Type);
@ -48,14 +50,14 @@ procedure Test is
procedure Print_Pet (Pet : in Samples.Petstore.Models.Pet_Type) is procedure Print_Pet (Pet : in Samples.Petstore.Models.Pet_Type) is
Need_Indent : Boolean := False; Need_Indent : Boolean := False;
begin begin
Put_Line ("Id : " & Swagger.Long'Image (Pet.Id)); Put_Line ("Id : " & Swagger.Long'Image (Pet.Id.Value));
Put_Line ("Name : " & Swagger.To_String (Pet.Name)); Put_Line ("Name : " & Swagger.To_String (Pet.Name));
Put_Line ("Status : " & Swagger.To_String (Pet.Status)); Put_Line ("Status : " & Swagger.To_String (Pet.Status.Value));
if not Pet.Tags.Is_Empty then if not Pet.Tags.Is_Empty then
Put ("Tags : "); Put ("Tags : ");
for Tag of Pet.Tags loop for Tag of Pet.Tags loop
Put_Line ((if Need_Indent then " " else "") Put_Line ((if Need_Indent then " " else "")
& Swagger.To_String (Tag.Name)); & Swagger.To_String (Tag.Name.Value));
Need_Indent := True; Need_Indent := True;
end loop; end loop;
end if; end if;
@ -63,7 +65,7 @@ procedure Test is
Need_Indent := False; Need_Indent := False;
Put ("URLs : "); Put ("URLs : ");
for Url of Pet.Photo_Urls loop for Url of Pet.Photo_Urls loop
Put_Line ((if Need_Indent then " " else "") & Url); Put_Line ((if Need_Indent then " " else "") & Swagger.To_String (Url.Value));
Need_Indent := True; Need_Indent := True;
end loop; end loop;
end if; end if;
@ -71,12 +73,12 @@ procedure Test is
procedure Print_Order (Order : in Samples.Petstore.Models.Order_Type) is procedure Print_Order (Order : in Samples.Petstore.Models.Order_Type) is
begin begin
Put_Line ("Id : " & Swagger.Long'Image (Order.Id)); Put_Line ("Id : " & Swagger.Long'Image (Order.Id.Value));
Put_Line ("Pet id : " & Swagger.Long'Image (Order.Pet_Id)); Put_Line ("Pet id : " & Swagger.Long'Image (Order.Pet_Id.Value));
Put_Line ("Quantity : " & Integer'Image (Order.Quantity)); Put_Line ("Quantity : " & Integer'Image (Order.Quantity.Value));
Put_Line ("Status : " & Swagger.To_String (Order.Status)); Put_Line ("Status : " & Swagger.To_String (Order.Status.Value));
Put_Line ("Ship date : " & Ada.Calendar.Formatting.Image (Order.Ship_Date)); Put_Line ("Ship date : " & Ada.Calendar.Formatting.Image (Order.Ship_Date.Value));
Put_Line ("Complete : " & Boolean'Image (Order.Complete)); Put_Line ("Complete : " & Boolean'Image (Order.Complete.Value));
end Print_Order; end Print_Order;
procedure Get_User (C : in out Samples.Petstore.Clients.Client_Type) is procedure Get_User (C : in out Samples.Petstore.Clients.Client_Type) is
@ -85,13 +87,13 @@ procedure Test is
begin begin
for I in Arg .. Arg_Count loop for I in Arg .. Arg_Count loop
C.Get_User_By_Name (Swagger.To_UString (Ada.Command_Line.Argument (I)), User); C.Get_User_By_Name (Swagger.To_UString (Ada.Command_Line.Argument (I)), User);
Put_Line ("Id : " & Swagger.Long'Image (User.Id)); Put_Line ("Id : " & Swagger.Long'Image (User.Id.Value));
Put_Line ("Username : " & Swagger.To_String (User.Username)); Put_Line ("Username : " & Swagger.To_String (User.Username.Value));
Put_Line ("Firstname: " & Swagger.To_String (User.First_Name)); Put_Line ("Firstname: " & Swagger.To_String (User.First_Name.Value));
Put_Line ("Lastname : " & Swagger.To_String (User.Last_Name)); Put_Line ("Lastname : " & Swagger.To_String (User.Last_Name.Value));
Put_Line ("Email : " & Swagger.To_String (User.Email)); Put_Line ("Email : " & Swagger.To_String (User.Email.Value));
Put_Line ("Password : " & Swagger.To_String (User.Password)); Put_Line ("Password : " & Swagger.To_String (User.Password.Value));
Put_Line ("Phone : " & Swagger.To_String (User.Phone)); Put_Line ("Phone : " & Swagger.To_String (User.Phone.Value));
end loop; end loop;
end Get_User; end Get_User;
@ -128,10 +130,10 @@ procedure Test is
begin begin
for I in Arg .. Arg_Count loop for I in Arg .. Arg_Count loop
declare declare
Status : Swagger.UString_Vectors.Vector; Status : Swagger.Nullable_UString_Vectors.Vector;
P : constant String := Ada.Command_Line.Argument (I); P : constant String := Ada.Command_Line.Argument (I);
begin begin
Status.Append (P); Status.Append ((Is_Null => False, Value => Swagger.To_UString (P)));
C.Find_Pets_By_Status (Status, Pets); C.Find_Pets_By_Status (Status, Pets);
for Pet of Pets loop for Pet of Pets loop
Print_Pet (Pet); Print_Pet (Pet);
@ -141,17 +143,17 @@ procedure Test is
end List_Pet; end List_Pet;
procedure List_Inventory (C : in out Samples.Petstore.Clients.Client_Type) is procedure List_Inventory (C : in out Samples.Petstore.Clients.Client_Type) is
List : Swagger.Integer_Map; List : Swagger.Nullable_Integer_Map;
Iter : Swagger.Integer_Maps.Cursor; Iter : Swagger.Nullable_Integer_Maps.Cursor;
begin begin
C.Get_Inventory (List); C.Get_Inventory (List);
Ada.Text_IO.Put_Line ("Inventory size " & Natural'Image (Natural (List.Length))); Ada.Text_IO.Put_Line ("Inventory size " & Natural'Image (Natural (List.Length)));
Iter := List.First; Iter := List.First;
while Swagger.Integer_Maps.Has_Element (Iter) loop while Swagger.Nullable_Integer_Maps.Has_Element (Iter) loop
Put (Swagger.Integer_Maps.Key (Iter)); Put (Swagger.Nullable_Integer_Maps.Key (Iter));
Set_Col (70); Set_Col (70);
Put_Line (Natural'Image (Swagger.Integer_Maps.Element (Iter))); Put_Line (Natural'Image (Swagger.Nullable_Integer_Maps.Element (Iter).Value));
Swagger.Integer_Maps.Next (Iter); Swagger.Nullable_Integer_Maps.Next (Iter);
end loop; end loop;
end List_Inventory; end List_Inventory;
@ -174,11 +176,14 @@ procedure Test is
Usage; Usage;
return; return;
end if; end if;
Pet.Id := Swagger.Long'Value (Ada.Command_Line.Argument (Arg)); Pet.Id := (Is_Null => False, Value => Swagger.Long'Value (Ada.Command_Line.Argument (Arg)));
Pet.Name := Swagger.To_UString (Ada.Command_Line.Argument (Arg + 1)); Pet.Name := Swagger.To_UString (Ada.Command_Line.Argument (Arg + 1));
Pet.Status := Swagger.To_UString (Ada.Command_Line.Argument (Arg + 2)); Pet.Status := (Is_Null => False,
Pet.Category.Id := Swagger.Long'Value (Ada.Command_Line.Argument (Arg + 3)); Value => Swagger.To_UString (Ada.Command_Line.Argument (Arg + 2)));
Pet.Category.Name := Swagger.To_UString (Ada.Command_Line.Argument (Arg + 4)); Pet.Category.Id := (Is_Null => False,
Value => Swagger.Long'Value (Ada.Command_Line.Argument (Arg + 3)));
Pet.Category.Name := (Is_Null => False,
Value => Swagger.To_UString (Ada.Command_Line.Argument (Arg + 4)));
C.Add_Pet (Pet); C.Add_Pet (Pet);
end Add_Pet; end Add_Pet;
@ -201,7 +206,8 @@ procedure Test is
begin begin
Arg := Arg + 1; Arg := Arg + 1;
for I in Arg .. Arg_Count loop for I in Arg .. Arg_Count loop
C.Delete_Pet (Swagger.Long'Value (Ada.Command_Line.Argument (I)), Key); C.Delete_Pet (Swagger.Long'Value (Ada.Command_Line.Argument (I)),
(Is_Null => False, Value => Key));
end loop; end loop;
end Delete_Pet; end Delete_Pet;

View File

@ -1,2 +1,14 @@
-- Swagger Petstore
-- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special_key` to test the authorization filters.
-- ------------ EDIT NOTE ------------
-- This file was generated with swagger-codegen. You can modify it to implement
-- the server. After you modify this file, you should add the following line
-- to the .swagger-codegen-ignore file:
--
-- src/samples-petstore.ads
--
-- Then, you can drop this edit note comment.
-- ------------ EDIT NOTE ------------
package Samples.Petstore is package Samples.Petstore is
end Samples.Petstore; end Samples.Petstore;

View File

@ -1,2 +1,14 @@
-- Swagger Petstore
-- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special_key` to test the authorization filters.
-- ------------ EDIT NOTE ------------
-- This file was generated with swagger-codegen. You can modify it to implement
-- the server. After you modify this file, you should add the following line
-- to the .swagger-codegen-ignore file:
--
-- src/samples-petstore.ads
--
-- Then, you can drop this edit note comment.
-- ------------ EDIT NOTE ------------
package Samples is package Samples is
end Samples; end Samples;

File diff suppressed because it is too large Load Diff

View File

@ -1 +1 @@
2.3.0-SNAPSHOT 2.3.0

View File

@ -1,22 +1,20 @@
version := "1.0.0" version := "1.0.0"
name := "swagger-scala-client"
name := "swagger-scala-client" organization := "io.swagger"
scalaVersion := "2.11.12"
organization := "io.swagger"
scalaVersion := "2.11.8"
libraryDependencies ++= Seq( libraryDependencies ++= Seq(
"com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.4.2", "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.9.2",
"com.sun.jersey" % "jersey-core" % "1.19", "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.9.2",
"com.sun.jersey" % "jersey-client" % "1.19", "com.sun.jersey" % "jersey-core" % "1.19.4",
"com.sun.jersey.contribs" % "jersey-multipart" % "1.19", "com.sun.jersey" % "jersey-client" % "1.19.4",
"com.sun.jersey.contribs" % "jersey-multipart" % "1.19.4",
"org.jfarcand" % "jersey-ahc-client" % "1.0.5", "org.jfarcand" % "jersey-ahc-client" % "1.0.5",
"io.swagger" % "swagger-core" % "1.5.8", "io.swagger" % "swagger-core" % "1.5.8",
"joda-time" % "joda-time" % "2.2", "joda-time" % "joda-time" % "2.9.9",
"org.joda" % "joda-convert" % "1.2", "org.joda" % "joda-convert" % "1.9.2",
"org.scalatest" %% "scalatest" % "2.2.4" % "test", "org.scalatest" %% "scalatest" % "3.0.4" % "test",
"junit" % "junit" % "4.8.1" % "test", "junit" % "junit" % "4.12" % "test",
"com.wordnik.swagger" %% "swagger-async-httpclient" % "0.3.5" "com.wordnik.swagger" %% "swagger-async-httpclient" % "0.3.5"
) )

View File

@ -1,235 +1,255 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-scala-client</artifactId> <artifactId>swagger-scala-client</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>swagger-scala-client</name> <name>swagger-scala-client</name>
<version>1.0.0</version> <version>1.0.0</version>
<prerequisites>
<maven>2.2.0</maven>
</prerequisites>
<pluginRepositories> <pluginRepositories>
<pluginRepository> <pluginRepository>
<id>maven-mongodb-plugin-repo</id> <id>maven-mongodb-plugin-repo</id>
<name>maven mongodb plugin repository</name> <name>maven mongodb plugin repository</name>
<url>http://maven-mongodb-plugin.googlecode.com/svn/maven/repo</url> <url>http://maven-mongodb-plugin.googlecode.com/svn/maven/repo</url>
<layout>default</layout> <layout>default</layout>
</pluginRepository> </pluginRepository>
</pluginRepositories> </pluginRepositories>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-enforcer-plugin</artifactId>
<version>2.12</version> <version>3.0.0-M1</version>
<configuration> <executions>
<systemProperties> <execution>
<property> <id>enforce-maven</id>
<name>loggerPath</name> <goals>
<value>conf/log4j.properties</value> <goal>enforce</goal>
</property> </goals>
</systemProperties> <configuration>
<argLine>-Xms512m -Xmx1500m</argLine> <rules>
<parallel>methods</parallel> <requireMavenVersion>
<forkMode>pertest</forkMode> <version>2.2.0</version>
</configuration> </requireMavenVersion>
</plugin> </rules>
<plugin> </configuration>
<artifactId>maven-dependency-plugin</artifactId> </execution>
<executions> </executions>
<execution> </plugin>
<phase>package</phase> <plugin>
<goals> <groupId>org.apache.maven.plugins</groupId>
<goal>copy-dependencies</goal> <artifactId>maven-surefire-plugin</artifactId>
</goals> <version>2.12</version>
<configuration> <configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory> <systemProperties>
</configuration> <property>
</execution> <name>loggerPath</name>
</executions> <value>conf/log4j.properties</value>
</plugin> </property>
</systemProperties>
<argLine>-Xms512m -Xmx1500m</argLine>
<parallel>methods</parallel>
<forkMode>pertest</forkMode>
</configuration>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<!-- attach test jar --> <!-- attach test jar -->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<version>2.2</version> <version>2.2</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
<goal>jar</goal> <goal>jar</goal>
<goal>test-jar</goal> <goal>test-jar</goal>
</goals> </goals>
</execution> </execution>
</executions> </executions>
<configuration> <configuration>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId> <artifactId>build-helper-maven-plugin</artifactId>
<version>1.9.1</version> <version>1.9.1</version>
<executions> <executions>
<execution> <execution>
<id>add_sources</id> <id>add_sources</id>
<phase>generate-sources</phase> <phase>generate-sources</phase>
<goals> <goals>
<goal>add-source</goal> <goal>add-source</goal>
</goals> </goals>
<configuration> <configuration>
<sources> <sources>
<source>src/main/java</source> <source>
</sources> src/main/java</source>
</configuration> </sources>
</execution> </configuration>
<execution> </execution>
<id>add_test_sources</id> <execution>
<phase>generate-test-sources</phase> <id>add_test_sources</id>
<goals> <phase>generate-test-sources</phase>
<goal>add-test-source</goal> <goals>
</goals> <goal>add-test-source</goal>
<configuration> </goals>
<sources> <configuration>
<source>src/test/java</source> <sources>
</sources> <source>
</configuration> src/test/java</source>
</execution> </sources>
</executions> </configuration>
</plugin> </execution>
<plugin> </executions>
<groupId>org.apache.maven.plugins</groupId> </plugin>
<artifactId>maven-compiler-plugin</artifactId> <plugin>
<version>3.6.1</version> <groupId>org.apache.maven.plugins</groupId>
<configuration> <artifactId>maven-compiler-plugin</artifactId>
<source>1.7</source> <version>3.6.1</version>
<target>1.7</target> <configuration>
</configuration> <source>
</plugin> 1.7</source>
<plugin> <target>1.7</target>
<groupId>net.alchim31.maven</groupId> </configuration>
<artifactId>scala-maven-plugin</artifactId> </plugin>
<version>${scala-maven-plugin-version}</version> <plugin>
<executions> <groupId>net.alchim31.maven</groupId>
<execution> <artifactId>scala-maven-plugin</artifactId>
<id>scala-compile-first</id> <version>${scala-maven-plugin-version}</version>
<phase>process-resources</phase> <executions>
<goals> <execution>
<goal>add-source</goal> <id>scala-compile-first</id>
<goal>compile</goal> <phase>process-resources</phase>
</goals> <goals>
</execution> <goal>add-source</goal>
<execution> <goal>compile</goal>
<id>scala-test-compile</id> </goals>
<phase>process-test-resources</phase> </execution>
<goals> <execution>
<goal>testCompile</goal> <id>scala-test-compile</id>
</goals> <phase>process-test-resources</phase>
</execution> <goals>
</executions> <goal>testCompile</goal>
<configuration> </goals>
<jvmArgs> </execution>
<jvmArg>-Xms128m</jvmArg> </executions>
<jvmArg>-Xmx1500m</jvmArg> <configuration>
</jvmArgs> <jvmArgs>
</configuration> <jvmArg>-Xms128m</jvmArg>
</plugin> <jvmArg>-Xmx1500m</jvmArg>
</plugins> </jvmArgs>
</build> </configuration>
<reporting> </plugin>
<plugins> </plugins>
<plugin> </build>
<groupId>org.scala-tools</groupId> <reporting>
<artifactId>maven-scala-plugin</artifactId> <plugins>
<configuration> <plugin>
<scalaVersion>${scala-version}</scalaVersion> <groupId>org.scala-tools</groupId>
</configuration> <artifactId>maven-scala-plugin</artifactId>
</plugin> <configuration>
</plugins> <scalaVersion>${scala-version}</scalaVersion>
</reporting> </configuration>
<dependencies> </plugin>
<dependency> </plugins>
<groupId>com.fasterxml.jackson.module</groupId> </reporting>
<artifactId>jackson-module-scala_2.11</artifactId> <dependencies>
<version>${jackson-version}</version> <dependency>
</dependency> <groupId>com.fasterxml.jackson.module</groupId>
<dependency> <artifactId>jackson-module-scala_2.11</artifactId>
<groupId>com.fasterxml.jackson.datatype</groupId> <version>${jackson-version}</version>
<artifactId>jackson-datatype-joda</artifactId> </dependency>
<version>${jackson-version}</version> <dependency>
</dependency> <groupId>com.fasterxml.jackson.datatype</groupId>
<dependency> <artifactId>jackson-datatype-joda</artifactId>
<groupId>com.sun.jersey</groupId> <version>${jackson-version}</version>
<artifactId>jersey-client</artifactId> </dependency>
<version>${jersey-version}</version> <dependency>
</dependency> <groupId>com.sun.jersey</groupId>
<dependency> <artifactId>jersey-client</artifactId>
<groupId>com.sun.jersey.contribs</groupId> <version>${jersey-version}</version>
<artifactId>jersey-multipart</artifactId> </dependency>
<version>${jersey-version}</version> <dependency>
</dependency> <groupId>com.sun.jersey.contribs</groupId>
<dependency> <artifactId>jersey-multipart</artifactId>
<groupId>org.jfarcand</groupId> <version>${jersey-version}</version>
<artifactId>jersey-ahc-client</artifactId> </dependency>
<version>${jersey-async-version}</version> <dependency>
<scope>compile</scope> <groupId>org.jfarcand</groupId>
</dependency> <artifactId>jersey-ahc-client</artifactId>
<dependency> <version>${jersey-async-version}</version>
<groupId>org.scala-lang</groupId> <scope>compile</scope>
<artifactId>scala-library</artifactId> </dependency>
<version>${scala-version}</version> <dependency>
</dependency> <groupId>org.scala-lang</groupId>
<dependency> <artifactId>scala-library</artifactId>
<groupId>io.swagger</groupId> <version>${scala-version}</version>
<artifactId>swagger-core</artifactId> </dependency>
<version>${swagger-core-version}</version> <dependency>
</dependency> <groupId>io.swagger</groupId>
<dependency> <artifactId>swagger-core</artifactId>
<groupId>org.scalatest</groupId> <version>${swagger-core-version}</version>
<artifactId>scalatest_2.11</artifactId> </dependency>
<version>${scala-test-version}</version> <dependency>
<scope>test</scope> <groupId>org.scalatest</groupId>
</dependency> <artifactId>scalatest_2.11</artifactId>
<dependency> <version>${scala-test-version}</version>
<groupId>junit</groupId> <scope>test</scope>
<artifactId>junit</artifactId> </dependency>
<version>${junit-version}</version> <dependency>
<scope>test</scope> <groupId>junit</groupId>
</dependency> <artifactId>junit</artifactId>
<dependency> <version>${junit-version}</version>
<groupId>joda-time</groupId> <scope>test</scope>
<artifactId>joda-time</artifactId> </dependency>
<version>${joda-time-version}</version> <dependency>
</dependency> <groupId>joda-time</groupId>
<dependency> <artifactId>joda-time</artifactId>
<groupId>org.joda</groupId> <version>${joda-time-version}</version>
<artifactId>joda-convert</artifactId> </dependency>
<version>${joda-version}</version> <dependency>
</dependency> <groupId>org.joda</groupId>
<dependency> <artifactId>joda-convert</artifactId>
<groupId>com.wordnik.swagger</groupId> <version>${joda-version}</version>
<artifactId>swagger-async-httpclient_2.11</artifactId> </dependency>
<version>${swagger-async-httpclient-version}</version> <dependency>
</dependency> <groupId>com.wordnik.swagger</groupId>
</dependencies> <artifactId>swagger-async-httpclient_2.11</artifactId>
<properties> <version>${swagger-async-httpclient-version}</version>
<scala-version>2.11.12</scala-version> </dependency>
<joda-version>1.2</joda-version> </dependencies>
<joda-time-version>2.2</joda-time-version> <properties>
<jersey-version>1.19</jersey-version> <scala-version>2.11.12</scala-version>
<swagger-core-version>1.5.16</swagger-core-version> <joda-version>1.9.2</joda-version>
<jersey-async-version>1.0.5</jersey-async-version> <joda-time-version>2.9.9</joda-time-version>
<maven-plugin.version>1.0.0</maven-plugin.version> <jersey-version>1.19.4</jersey-version>
<jackson-version>2.8.9</jackson-version> <swagger-core-version>1.5.16</swagger-core-version>
<jersey-async-version>1.0.5</jersey-async-version>
<maven-plugin.version>1.0.0</maven-plugin.version>
<jackson-version>2.9.2</jackson-version>
<junit-version>4.8.1</junit-version> <junit-version>4.12</junit-version>
<scala-maven-plugin-version>3.1.5</scala-maven-plugin-version> <scala-maven-plugin-version>3.1.5</scala-maven-plugin-version>
<scala-test-version>2.2.4</scala-test-version> <scala-test-version>3.0.4</scala-test-version>
<swagger-async-httpclient-version>0.3.5</swagger-async-httpclient-version> <swagger-async-httpclient-version>0.3.5</swagger-async-httpclient-version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
</project> </project>

View File

@ -38,7 +38,7 @@ import com.fasterxml.jackson.annotation._
import com.fasterxml.jackson.databind.annotation.JsonSerialize import com.fasterxml.jackson.databind.annotation.JsonSerialize
object ScalaJsonUtil { object ScalaJsonUtil {
def getJsonMapper = { def getJsonMapper: ObjectMapper = {
val mapper = new ObjectMapper() val mapper = new ObjectMapper()
mapper.registerModule(new DefaultScalaModule()) mapper.registerModule(new DefaultScalaModule())
mapper.registerModule(new JodaModule()) mapper.registerModule(new JodaModule())
@ -130,9 +130,8 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper,
val builder = client.resource(host + path + querystring).accept(contentType) val builder = client.resource(host + path + querystring).accept(contentType)
headerParams.map(p => builder.header(p._1, p._2)) headerParams.map(p => builder.header(p._1, p._2))
defaultHeaders.foreach(p => { defaultHeaders.foreach(p => {
headerParams.contains(p._1) match { if (!headerParams.contains(p._1) && p._2 != null) {
case true => // override default with supplied header builder.header(p._1, p._2)
case false => if (p._2 != null) builder.header(p._1, p._2)
} }
}) })
var formData: MultivaluedMapImpl = null var formData: MultivaluedMapImpl = null
@ -142,7 +141,7 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper,
} }
val response: ClientResponse = method match { val response: ClientResponse = method match {
case "GET" => builder.get(classOf[ClientResponse]).asInstanceOf[ClientResponse] case "GET" => builder.get(classOf[ClientResponse])
case "POST" => case "POST" =>
if (formData != null && formData.size() > 0) { if (formData != null && formData.size() > 0) {
builder.post(classOf[ClientResponse], formData) builder.post(classOf[ClientResponse], formData)
@ -181,46 +180,48 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper,
response.getStatusInfo.getStatusCode match { response.getStatusInfo.getStatusCode match {
case 204 => "" case 204 => ""
case code: Int if Range(200, 299).contains(code) => case code: Int if Range(200, 299).contains(code) =>
response.hasEntity match { if (response.hasEntity) {
case true => response.getEntity(classOf[String]) response.getEntity(classOf[String])
case false => "" } else {
""
} }
case _ => case _ =>
val entity = response.hasEntity match { val entity = if (response.hasEntity) {
case true => response.getEntity(classOf[String]) response.getEntity(classOf[String])
case false => "no data" } else {
"no data"
} }
throw new ApiException(response.getStatusInfo.getStatusCode, entity) throw new ApiException(response.getStatusInfo.getStatusCode, entity)
} }
} }
def getClient(host: String): Client = { def getClient(host: String): Client = {
hostMap.contains(host) match { if (hostMap.contains(host)) {
case true => hostMap(host) hostMap(host)
case false => } else {
val client = newClient(host) val client = newClient(host)
// client.addFilter(new LoggingFilter()) // client.addFilter(new LoggingFilter())
hostMap += host -> client hostMap += host -> client
client client
} }
} }
def newClient(host: String): Client = asyncHttpClient match { def newClient(host: String): Client = if (asyncHttpClient) {
case true => import com.ning.http.client.Realm
import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig import org.sonatype.spice.jersey.client.ahc.AhcHttpClient
import org.sonatype.spice.jersey.client.ahc.AhcHttpClient import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig
import com.ning.http.client.Realm
val config: DefaultAhcConfig = new DefaultAhcConfig() val config: DefaultAhcConfig = new DefaultAhcConfig()
if (!authScheme.isEmpty) { if (!authScheme.isEmpty) {
val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme) val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme)
config config
.getAsyncHttpClientConfigBuilder .getAsyncHttpClientConfigBuilder
.setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum) .setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum)
.setUsePreemptiveAuth(authPreemptive).build) .setUsePreemptiveAuth(authPreemptive).build)
} }
AhcHttpClient.create(config) AhcHttpClient.create(config)
case _ => Client.create() } else {
Client.create()
} }
} }

View File

@ -7,8 +7,8 @@ import com.wordnik.swagger.client._
import java.io.Closeable import java.io.Closeable
class AsyncClient(config: SwaggerConfig) extends Closeable { class AsyncClient(config: SwaggerConfig) extends Closeable {
val locator = config.locator lazy val locator: ServiceLocator = config.locator
val name = config.name lazy val name: String = config.name
private[this] val client = transportClient private[this] val client = transportClient

View File

@ -43,6 +43,8 @@ import scala.concurrent._
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.util.{Failure, Success, Try} import scala.util.{Failure, Success, Try}
import org.json4s._
class PetApi( class PetApi(
val defBasePath: String = "http://petstore.swagger.io/v2", val defBasePath: String = "http://petstore.swagger.io/v2",
defApiInvoker: ApiInvoker = ApiInvoker defApiInvoker: ApiInvoker = ApiInvoker
@ -51,12 +53,12 @@ class PetApi(
implicit val formats = new org.json4s.DefaultFormats { implicit val formats = new org.json4s.DefaultFormats {
override def dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+0000") override def dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+0000")
} }
implicit val stringReader = ClientResponseReaders.StringReader implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader
implicit val unitReader = ClientResponseReaders.UnitReader implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader
implicit val jvalueReader = ClientResponseReaders.JValueReader implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader
implicit val jsonReader = JsonFormatsReader implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader
implicit val stringWriter = RequestWriters.StringWriter implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter
implicit val jsonWriter = JsonFormatsWriter implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter
var basePath: String = defBasePath var basePath: String = defBasePath
var apiInvoker: ApiInvoker = defApiInvoker var apiInvoker: ApiInvoker = defApiInvoker
@ -65,13 +67,14 @@ class PetApi(
apiInvoker.defaultHeaders += key -> value apiInvoker.defaultHeaders += key -> value
} }
val config = SwaggerConfig.forUrl(new URI(defBasePath)) val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath))
val client = new RestClient(config) val client = new RestClient(config)
val helper = new PetApiAsyncHelper(client, config) val helper = new PetApiAsyncHelper(client, config)
/** /**
* Add a new pet to the store * Add a new pet to the store
* *
*
* @param body Pet object that needs to be added to the store * @param body Pet object that needs to be added to the store
* @return void * @return void
*/ */
@ -86,9 +89,10 @@ class PetApi(
/** /**
* Add a new pet to the store asynchronously * Add a new pet to the store asynchronously
* *
*
* @param body Pet object that needs to be added to the store * @param body Pet object that needs to be added to the store
* @return Future(void) * @return Future(void)
*/ */
def addPetAsync(body: Pet) = { def addPetAsync(body: Pet) = {
helper.addPet(body) helper.addPet(body)
} }
@ -96,6 +100,7 @@ class PetApi(
/** /**
* Deletes a pet * Deletes a pet
* *
*
* @param petId Pet id to delete * @param petId Pet id to delete
* @param apiKey (optional) * @param apiKey (optional)
* @return void * @return void
@ -111,10 +116,11 @@ class PetApi(
/** /**
* Deletes a pet asynchronously * Deletes a pet asynchronously
* *
*
* @param petId Pet id to delete * @param petId Pet id to delete
* @param apiKey (optional) * @param apiKey (optional)
* @return Future(void) * @return Future(void)
*/ */
def deletePetAsync(petId: Long, apiKey: Option[String] = None) = { def deletePetAsync(petId: Long, apiKey: Option[String] = None) = {
helper.deletePet(petId, apiKey) helper.deletePet(petId, apiKey)
} }
@ -122,6 +128,7 @@ class PetApi(
/** /**
* Finds Pets by status * Finds Pets by status
* Multiple status values can be provided with comma separated strings * Multiple status values can be provided with comma separated strings
*
* @param status Status values that need to be considered for filter * @param status Status values that need to be considered for filter
* @return List[Pet] * @return List[Pet]
*/ */
@ -136,9 +143,10 @@ class PetApi(
/** /**
* Finds Pets by status asynchronously * Finds Pets by status asynchronously
* Multiple status values can be provided with comma separated strings * Multiple status values can be provided with comma separated strings
*
* @param status Status values that need to be considered for filter * @param status Status values that need to be considered for filter
* @return Future(List[Pet]) * @return Future(List[Pet])
*/ */
def findPetsByStatusAsync(status: List[String]): Future[List[Pet]] = { def findPetsByStatusAsync(status: List[String]): Future[List[Pet]] = {
helper.findPetsByStatus(status) helper.findPetsByStatus(status)
} }
@ -146,6 +154,7 @@ class PetApi(
/** /**
* Finds Pets by tags * Finds Pets by tags
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
*
* @param tags Tags to filter by * @param tags Tags to filter by
* @return List[Pet] * @return List[Pet]
*/ */
@ -160,9 +169,10 @@ class PetApi(
/** /**
* Finds Pets by tags asynchronously * Finds Pets by tags asynchronously
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
*
* @param tags Tags to filter by * @param tags Tags to filter by
* @return Future(List[Pet]) * @return Future(List[Pet])
*/ */
def findPetsByTagsAsync(tags: List[String]): Future[List[Pet]] = { def findPetsByTagsAsync(tags: List[String]): Future[List[Pet]] = {
helper.findPetsByTags(tags) helper.findPetsByTags(tags)
} }
@ -170,6 +180,7 @@ class PetApi(
/** /**
* Find pet by ID * Find pet by ID
* Returns a single pet * Returns a single pet
*
* @param petId ID of pet to return * @param petId ID of pet to return
* @return Pet * @return Pet
*/ */
@ -184,9 +195,10 @@ class PetApi(
/** /**
* Find pet by ID asynchronously * Find pet by ID asynchronously
* Returns a single pet * Returns a single pet
*
* @param petId ID of pet to return * @param petId ID of pet to return
* @return Future(Pet) * @return Future(Pet)
*/ */
def getPetByIdAsync(petId: Long): Future[Pet] = { def getPetByIdAsync(petId: Long): Future[Pet] = {
helper.getPetById(petId) helper.getPetById(petId)
} }
@ -194,6 +206,7 @@ class PetApi(
/** /**
* Update an existing pet * Update an existing pet
* *
*
* @param body Pet object that needs to be added to the store * @param body Pet object that needs to be added to the store
* @return void * @return void
*/ */
@ -208,9 +221,10 @@ class PetApi(
/** /**
* Update an existing pet asynchronously * Update an existing pet asynchronously
* *
*
* @param body Pet object that needs to be added to the store * @param body Pet object that needs to be added to the store
* @return Future(void) * @return Future(void)
*/ */
def updatePetAsync(body: Pet) = { def updatePetAsync(body: Pet) = {
helper.updatePet(body) helper.updatePet(body)
} }
@ -218,6 +232,7 @@ class PetApi(
/** /**
* Updates a pet in the store with form data * Updates a pet in the store with form data
* *
*
* @param petId ID of pet that needs to be updated * @param petId ID of pet that needs to be updated
* @param name Updated name of the pet (optional) * @param name Updated name of the pet (optional)
* @param status Updated status of the pet (optional) * @param status Updated status of the pet (optional)
@ -234,11 +249,12 @@ class PetApi(
/** /**
* Updates a pet in the store with form data asynchronously * Updates a pet in the store with form data asynchronously
* *
*
* @param petId ID of pet that needs to be updated * @param petId ID of pet that needs to be updated
* @param name Updated name of the pet (optional) * @param name Updated name of the pet (optional)
* @param status Updated status of the pet (optional) * @param status Updated status of the pet (optional)
* @return Future(void) * @return Future(void)
*/ */
def updatePetWithFormAsync(petId: Long, name: Option[String] = None, status: Option[String] = None) = { def updatePetWithFormAsync(petId: Long, name: Option[String] = None, status: Option[String] = None) = {
helper.updatePetWithForm(petId, name, status) helper.updatePetWithForm(petId, name, status)
} }
@ -246,6 +262,7 @@ class PetApi(
/** /**
* uploads an image * uploads an image
* *
*
* @param petId ID of pet to update * @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server (optional) * @param additionalMetadata Additional data to pass to server (optional)
* @param file file to upload (optional) * @param file file to upload (optional)
@ -262,11 +279,12 @@ class PetApi(
/** /**
* uploads an image asynchronously * uploads an image asynchronously
* *
*
* @param petId ID of pet to update * @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server (optional) * @param additionalMetadata Additional data to pass to server (optional)
* @param file file to upload (optional) * @param file file to upload (optional)
* @return Future(ApiResponse) * @return Future(ApiResponse)
*/ */
def uploadFileAsync(petId: Long, additionalMetadata: Option[String] = None, file: Option[File] = None): Future[ApiResponse] = { def uploadFileAsync(petId: Long, additionalMetadata: Option[String] = None, file: Option[File] = None): Future[ApiResponse] = {
helper.uploadFile(petId, additionalMetadata, file) helper.uploadFile(petId, additionalMetadata, file)
} }
@ -296,7 +314,7 @@ class PetApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends
)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { )(implicit reader: ClientResponseReader[Unit]): Future[Unit] = {
// create path and map variables // create path and map variables
val path = (addFmt("/pet/{petId}") val path = (addFmt("/pet/{petId}")
replaceAll ("\\{" + "petId" + "\\}",petId.toString)) replaceAll("\\{" + "petId" + "\\}", petId.toString))
// query params // query params
val queryParams = new mutable.HashMap[String, String] val queryParams = new mutable.HashMap[String, String]
@ -350,7 +368,7 @@ class PetApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends
def getPetById(petId: Long)(implicit reader: ClientResponseReader[Pet]): Future[Pet] = { def getPetById(petId: Long)(implicit reader: ClientResponseReader[Pet]): Future[Pet] = {
// create path and map variables // create path and map variables
val path = (addFmt("/pet/{petId}") val path = (addFmt("/pet/{petId}")
replaceAll ("\\{" + "petId" + "\\}",petId.toString)) replaceAll("\\{" + "petId" + "\\}", petId.toString))
// query params // query params
val queryParams = new mutable.HashMap[String, String] val queryParams = new mutable.HashMap[String, String]
@ -385,7 +403,7 @@ class PetApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends
)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { )(implicit reader: ClientResponseReader[Unit]): Future[Unit] = {
// create path and map variables // create path and map variables
val path = (addFmt("/pet/{petId}") val path = (addFmt("/pet/{petId}")
replaceAll ("\\{" + "petId" + "\\}",petId.toString)) replaceAll("\\{" + "petId" + "\\}", petId.toString))
// query params // query params
val queryParams = new mutable.HashMap[String, String] val queryParams = new mutable.HashMap[String, String]
@ -404,7 +422,7 @@ class PetApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends
)(implicit reader: ClientResponseReader[ApiResponse]): Future[ApiResponse] = { )(implicit reader: ClientResponseReader[ApiResponse]): Future[ApiResponse] = {
// create path and map variables // create path and map variables
val path = (addFmt("/pet/{petId}/uploadImage") val path = (addFmt("/pet/{petId}/uploadImage")
replaceAll ("\\{" + "petId" + "\\}",petId.toString)) replaceAll("\\{" + "petId" + "\\}", petId.toString))
// query params // query params
val queryParams = new mutable.HashMap[String, String] val queryParams = new mutable.HashMap[String, String]

View File

@ -41,6 +41,8 @@ import scala.concurrent._
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.util.{Failure, Success, Try} import scala.util.{Failure, Success, Try}
import org.json4s._
class StoreApi( class StoreApi(
val defBasePath: String = "http://petstore.swagger.io/v2", val defBasePath: String = "http://petstore.swagger.io/v2",
defApiInvoker: ApiInvoker = ApiInvoker defApiInvoker: ApiInvoker = ApiInvoker
@ -49,12 +51,12 @@ class StoreApi(
implicit val formats = new org.json4s.DefaultFormats { implicit val formats = new org.json4s.DefaultFormats {
override def dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+0000") override def dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+0000")
} }
implicit val stringReader = ClientResponseReaders.StringReader implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader
implicit val unitReader = ClientResponseReaders.UnitReader implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader
implicit val jvalueReader = ClientResponseReaders.JValueReader implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader
implicit val jsonReader = JsonFormatsReader implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader
implicit val stringWriter = RequestWriters.StringWriter implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter
implicit val jsonWriter = JsonFormatsWriter implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter
var basePath: String = defBasePath var basePath: String = defBasePath
var apiInvoker: ApiInvoker = defApiInvoker var apiInvoker: ApiInvoker = defApiInvoker
@ -63,13 +65,14 @@ class StoreApi(
apiInvoker.defaultHeaders += key -> value apiInvoker.defaultHeaders += key -> value
} }
val config = SwaggerConfig.forUrl(new URI(defBasePath)) val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath))
val client = new RestClient(config) val client = new RestClient(config)
val helper = new StoreApiAsyncHelper(client, config) val helper = new StoreApiAsyncHelper(client, config)
/** /**
* Delete purchase order by ID * Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors * For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
*
* @param orderId ID of the order that needs to be deleted * @param orderId ID of the order that needs to be deleted
* @return void * @return void
*/ */
@ -84,9 +87,10 @@ class StoreApi(
/** /**
* Delete purchase order by ID asynchronously * Delete purchase order by ID asynchronously
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors * For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
*
* @param orderId ID of the order that needs to be deleted * @param orderId ID of the order that needs to be deleted
* @return Future(void) * @return Future(void)
*/ */
def deleteOrderAsync(orderId: String) = { def deleteOrderAsync(orderId: String) = {
helper.deleteOrder(orderId) helper.deleteOrder(orderId)
} }
@ -94,6 +98,7 @@ class StoreApi(
/** /**
* Returns pet inventories by status * Returns pet inventories by status
* Returns a map of status codes to quantities * Returns a map of status codes to quantities
*
* @return Map[String, Integer] * @return Map[String, Integer]
*/ */
def getInventory(): Option[Map[String, Integer]] = { def getInventory(): Option[Map[String, Integer]] = {
@ -107,8 +112,9 @@ class StoreApi(
/** /**
* Returns pet inventories by status asynchronously * Returns pet inventories by status asynchronously
* Returns a map of status codes to quantities * Returns a map of status codes to quantities
*
* @return Future(Map[String, Integer]) * @return Future(Map[String, Integer])
*/ */
def getInventoryAsync(): Future[Map[String, Integer]] = { def getInventoryAsync(): Future[Map[String, Integer]] = {
helper.getInventory() helper.getInventory()
} }
@ -116,6 +122,7 @@ class StoreApi(
/** /**
* Find purchase order by ID * Find purchase order by ID
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions * For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions
*
* @param orderId ID of pet that needs to be fetched * @param orderId ID of pet that needs to be fetched
* @return Order * @return Order
*/ */
@ -130,9 +137,10 @@ class StoreApi(
/** /**
* Find purchase order by ID asynchronously * Find purchase order by ID asynchronously
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions * For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions
*
* @param orderId ID of pet that needs to be fetched * @param orderId ID of pet that needs to be fetched
* @return Future(Order) * @return Future(Order)
*/ */
def getOrderByIdAsync(orderId: Long): Future[Order] = { def getOrderByIdAsync(orderId: Long): Future[Order] = {
helper.getOrderById(orderId) helper.getOrderById(orderId)
} }
@ -140,6 +148,7 @@ class StoreApi(
/** /**
* Place an order for a pet * Place an order for a pet
* *
*
* @param body order placed for purchasing the pet * @param body order placed for purchasing the pet
* @return Order * @return Order
*/ */
@ -154,9 +163,10 @@ class StoreApi(
/** /**
* Place an order for a pet asynchronously * Place an order for a pet asynchronously
* *
*
* @param body order placed for purchasing the pet * @param body order placed for purchasing the pet
* @return Future(Order) * @return Future(Order)
*/ */
def placeOrderAsync(body: Order): Future[Order] = { def placeOrderAsync(body: Order): Future[Order] = {
helper.placeOrder(body) helper.placeOrder(body)
} }
@ -168,7 +178,7 @@ class StoreApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extend
def deleteOrder(orderId: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { def deleteOrder(orderId: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = {
// create path and map variables // create path and map variables
val path = (addFmt("/store/order/{orderId}") val path = (addFmt("/store/order/{orderId}")
replaceAll ("\\{" + "orderId" + "\\}",orderId.toString)) replaceAll("\\{" + "orderId" + "\\}", orderId.toString))
// query params // query params
val queryParams = new mutable.HashMap[String, String] val queryParams = new mutable.HashMap[String, String]
@ -201,7 +211,7 @@ class StoreApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extend
def getOrderById(orderId: Long)(implicit reader: ClientResponseReader[Order]): Future[Order] = { def getOrderById(orderId: Long)(implicit reader: ClientResponseReader[Order]): Future[Order] = {
// create path and map variables // create path and map variables
val path = (addFmt("/store/order/{orderId}") val path = (addFmt("/store/order/{orderId}")
replaceAll ("\\{" + "orderId" + "\\}",orderId.toString)) replaceAll("\\{" + "orderId" + "\\}", orderId.toString))
// query params // query params
val queryParams = new mutable.HashMap[String, String] val queryParams = new mutable.HashMap[String, String]

View File

@ -41,6 +41,8 @@ import scala.concurrent._
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.util.{Failure, Success, Try} import scala.util.{Failure, Success, Try}
import org.json4s._
class UserApi( class UserApi(
val defBasePath: String = "http://petstore.swagger.io/v2", val defBasePath: String = "http://petstore.swagger.io/v2",
defApiInvoker: ApiInvoker = ApiInvoker defApiInvoker: ApiInvoker = ApiInvoker
@ -49,12 +51,12 @@ class UserApi(
implicit val formats = new org.json4s.DefaultFormats { implicit val formats = new org.json4s.DefaultFormats {
override def dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+0000") override def dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+0000")
} }
implicit val stringReader = ClientResponseReaders.StringReader implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader
implicit val unitReader = ClientResponseReaders.UnitReader implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader
implicit val jvalueReader = ClientResponseReaders.JValueReader implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader
implicit val jsonReader = JsonFormatsReader implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader
implicit val stringWriter = RequestWriters.StringWriter implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter
implicit val jsonWriter = JsonFormatsWriter implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter
var basePath: String = defBasePath var basePath: String = defBasePath
var apiInvoker: ApiInvoker = defApiInvoker var apiInvoker: ApiInvoker = defApiInvoker
@ -63,13 +65,14 @@ class UserApi(
apiInvoker.defaultHeaders += key -> value apiInvoker.defaultHeaders += key -> value
} }
val config = SwaggerConfig.forUrl(new URI(defBasePath)) val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath))
val client = new RestClient(config) val client = new RestClient(config)
val helper = new UserApiAsyncHelper(client, config) val helper = new UserApiAsyncHelper(client, config)
/** /**
* Create user * Create user
* This can only be done by the logged in user. * This can only be done by the logged in user.
*
* @param body Created user object * @param body Created user object
* @return void * @return void
*/ */
@ -84,9 +87,10 @@ class UserApi(
/** /**
* Create user asynchronously * Create user asynchronously
* This can only be done by the logged in user. * This can only be done by the logged in user.
*
* @param body Created user object * @param body Created user object
* @return Future(void) * @return Future(void)
*/ */
def createUserAsync(body: User) = { def createUserAsync(body: User) = {
helper.createUser(body) helper.createUser(body)
} }
@ -94,6 +98,7 @@ class UserApi(
/** /**
* Creates list of users with given input array * Creates list of users with given input array
* *
*
* @param body List of user object * @param body List of user object
* @return void * @return void
*/ */
@ -108,9 +113,10 @@ class UserApi(
/** /**
* Creates list of users with given input array asynchronously * Creates list of users with given input array asynchronously
* *
*
* @param body List of user object * @param body List of user object
* @return Future(void) * @return Future(void)
*/ */
def createUsersWithArrayInputAsync(body: List[User]) = { def createUsersWithArrayInputAsync(body: List[User]) = {
helper.createUsersWithArrayInput(body) helper.createUsersWithArrayInput(body)
} }
@ -118,6 +124,7 @@ class UserApi(
/** /**
* Creates list of users with given input array * Creates list of users with given input array
* *
*
* @param body List of user object * @param body List of user object
* @return void * @return void
*/ */
@ -132,9 +139,10 @@ class UserApi(
/** /**
* Creates list of users with given input array asynchronously * Creates list of users with given input array asynchronously
* *
*
* @param body List of user object * @param body List of user object
* @return Future(void) * @return Future(void)
*/ */
def createUsersWithListInputAsync(body: List[User]) = { def createUsersWithListInputAsync(body: List[User]) = {
helper.createUsersWithListInput(body) helper.createUsersWithListInput(body)
} }
@ -142,6 +150,7 @@ class UserApi(
/** /**
* Delete user * Delete user
* This can only be done by the logged in user. * This can only be done by the logged in user.
*
* @param username The name that needs to be deleted * @param username The name that needs to be deleted
* @return void * @return void
*/ */
@ -156,9 +165,10 @@ class UserApi(
/** /**
* Delete user asynchronously * Delete user asynchronously
* This can only be done by the logged in user. * This can only be done by the logged in user.
*
* @param username The name that needs to be deleted * @param username The name that needs to be deleted
* @return Future(void) * @return Future(void)
*/ */
def deleteUserAsync(username: String) = { def deleteUserAsync(username: String) = {
helper.deleteUser(username) helper.deleteUser(username)
} }
@ -166,6 +176,7 @@ class UserApi(
/** /**
* Get user by user name * Get user by user name
* *
*
* @param username The name that needs to be fetched. Use user1 for testing. * @param username The name that needs to be fetched. Use user1 for testing.
* @return User * @return User
*/ */
@ -180,9 +191,10 @@ class UserApi(
/** /**
* Get user by user name asynchronously * Get user by user name asynchronously
* *
*
* @param username The name that needs to be fetched. Use user1 for testing. * @param username The name that needs to be fetched. Use user1 for testing.
* @return Future(User) * @return Future(User)
*/ */
def getUserByNameAsync(username: String): Future[User] = { def getUserByNameAsync(username: String): Future[User] = {
helper.getUserByName(username) helper.getUserByName(username)
} }
@ -190,6 +202,7 @@ class UserApi(
/** /**
* Logs user into the system * Logs user into the system
* *
*
* @param username The user name for login * @param username The user name for login
* @param password The password for login in clear text * @param password The password for login in clear text
* @return String * @return String
@ -205,10 +218,11 @@ class UserApi(
/** /**
* Logs user into the system asynchronously * Logs user into the system asynchronously
* *
*
* @param username The user name for login * @param username The user name for login
* @param password The password for login in clear text * @param password The password for login in clear text
* @return Future(String) * @return Future(String)
*/ */
def loginUserAsync(username: String, password: String): Future[String] = { def loginUserAsync(username: String, password: String): Future[String] = {
helper.loginUser(username, password) helper.loginUser(username, password)
} }
@ -216,6 +230,7 @@ class UserApi(
/** /**
* Logs out current logged in user session * Logs out current logged in user session
* *
*
* @return void * @return void
*/ */
def logoutUser() = { def logoutUser() = {
@ -229,8 +244,9 @@ class UserApi(
/** /**
* Logs out current logged in user session asynchronously * Logs out current logged in user session asynchronously
* *
*
* @return Future(void) * @return Future(void)
*/ */
def logoutUserAsync() = { def logoutUserAsync() = {
helper.logoutUser() helper.logoutUser()
} }
@ -238,6 +254,7 @@ class UserApi(
/** /**
* Updated user * Updated user
* This can only be done by the logged in user. * This can only be done by the logged in user.
*
* @param username name that need to be deleted * @param username name that need to be deleted
* @param body Updated user object * @param body Updated user object
* @return void * @return void
@ -253,10 +270,11 @@ class UserApi(
/** /**
* Updated user asynchronously * Updated user asynchronously
* This can only be done by the logged in user. * This can only be done by the logged in user.
*
* @param username name that need to be deleted * @param username name that need to be deleted
* @param body Updated user object * @param body Updated user object
* @return Future(void) * @return Future(void)
*/ */
def updateUserAsync(username: String, body: User) = { def updateUserAsync(username: String, body: User) = {
helper.updateUser(username, body) helper.updateUser(username, body)
} }
@ -316,7 +334,7 @@ class UserApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends
def deleteUser(username: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { def deleteUser(username: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = {
// create path and map variables // create path and map variables
val path = (addFmt("/user/{username}") val path = (addFmt("/user/{username}")
replaceAll ("\\{" + "username" + "\\}",username.toString)) replaceAll("\\{" + "username" + "\\}", username.toString))
// query params // query params
val queryParams = new mutable.HashMap[String, String] val queryParams = new mutable.HashMap[String, String]
@ -334,7 +352,7 @@ class UserApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends
def getUserByName(username: String)(implicit reader: ClientResponseReader[User]): Future[User] = { def getUserByName(username: String)(implicit reader: ClientResponseReader[User]): Future[User] = {
// create path and map variables // create path and map variables
val path = (addFmt("/user/{username}") val path = (addFmt("/user/{username}")
replaceAll ("\\{" + "username" + "\\}",username.toString)) replaceAll("\\{" + "username" + "\\}", username.toString))
// query params // query params
val queryParams = new mutable.HashMap[String, String] val queryParams = new mutable.HashMap[String, String]
@ -390,7 +408,7 @@ class UserApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends
body: User)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = { body: User)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = {
// create path and map variables // create path and map variables
val path = (addFmt("/user/{username}") val path = (addFmt("/user/{username}")
replaceAll ("\\{" + "username" + "\\}",username.toString)) replaceAll("\\{" + "username" + "\\}", username.toString))
// query params // query params
val queryParams = new mutable.HashMap[String, String] val queryParams = new mutable.HashMap[String, String]

View File

@ -19,7 +19,7 @@ case class Order (
petId: Option[Long] = None, petId: Option[Long] = None,
quantity: Option[Integer] = None, quantity: Option[Integer] = None,
shipDate: Option[Date] = None, shipDate: Option[Date] = None,
/* Order Status */ // Order Status
status: Option[String] = None, status: Option[String] = None,
complete: Option[Boolean] = None complete: Option[Boolean] = None
) )

View File

@ -19,7 +19,7 @@ case class Pet (
name: String, name: String,
photoUrls: List[String], photoUrls: List[String],
tags: Option[List[Tag]] = None, tags: Option[List[Tag]] = None,
/* pet status in the store */ // pet status in the store
status: Option[String] = None status: Option[String] = None
) )

View File

@ -21,7 +21,7 @@ case class User (
email: Option[String] = None, email: Option[String] = None,
password: Option[String] = None, password: Option[String] = None,
phone: Option[String] = None, phone: Option[String] = None,
/* User Status */ // User Status
userStatus: Option[Integer] = None userStatus: Option[Integer] = None
) )

View File

@ -13,7 +13,7 @@ To see how to make this your own, look here:
[README](https://github.com/swagger-api/swagger-codegen/blob/master/README.md) [README](https://github.com/swagger-api/swagger-codegen/blob/master/README.md)
- API version: 1.0.0 - API version: 1.0.0
- Build date: 2017-12-18T09:35:47.160Z - Build date: 2017-12-20T21:53:07.200Z
### Running the server ### Running the server