sync from origin master & do the parameters validation in model

This commit is contained in:
abcsun
2016-05-07 15:43:19 +08:00
689 changed files with 23671 additions and 9090 deletions

3
.gitignore vendored
View File

@@ -107,3 +107,6 @@ samples/client/petstore/python/swagger_client.egg-info/SOURCES.txt
samples/client/petstore/python/.coverage samples/client/petstore/python/.coverage
samples/client/petstore/python/.projectile samples/client/petstore/python/.projectile
samples/client/petstore/python/.venv/ samples/client/petstore/python/.venv/
# ts
samples/client/petstore/typescript-node/npm/node_modules

View File

@@ -763,6 +763,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [Acunetix](https://www.acunetix.com/) - [Acunetix](https://www.acunetix.com/)
- [Atlassian](https://www.atlassian.com/) - [Atlassian](https://www.atlassian.com/)
- [beemo](http://www.beemo.eu) - [beemo](http://www.beemo.eu)
- [bitly](https://bitly.com)
- [Cachet Financial](http://www.cachetfinancial.com/) - [Cachet Financial](http://www.cachetfinancial.com/)
- [CloudBoost](https://www.CloudBoost.io/) - [CloudBoost](https://www.CloudBoost.io/)
- [Cupix](http://www.cupix.com) - [Cupix](http://www.cupix.com)
@@ -779,9 +780,11 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [nViso](http://www.nviso.ch/) - [nViso](http://www.nviso.ch/)
- [Okiok](https://www.okiok.com) - [Okiok](https://www.okiok.com)
- [OSDN](https://osdn.jp) - [OSDN](https://osdn.jp)
- [Pepipost](https://www.pepipost.com)
- [Pixoneye](http://www.pixoneye.com/) - [Pixoneye](http://www.pixoneye.com/)
- [PostAffiliatePro](https://www.postaffiliatepro.com/) - [PostAffiliatePro](https://www.postaffiliatepro.com/)
- [Reload! A/S](https://reload.dk/) - [Reload! A/S](https://reload.dk/)
- [REstore](https://www.restore.eu)
- [Royal Bank of Canada (RBC)](http://www.rbc.com/canada.html) - [Royal Bank of Canada (RBC)](http://www.rbc.com/canada.html)
- [SmartRecruiters](https://www.smartrecruiters.com/) - [SmartRecruiters](https://www.smartrecruiters.com/)
- [StyleRecipe](http://stylerecipe.co.jp) - [StyleRecipe](http://stylerecipe.co.jp)

View File

@@ -49,5 +49,6 @@ cd $APP_DIR
./bin/tizen-petstore.sh ./bin/tizen-petstore.sh
./bin/typescript-angular-petstore.sh ./bin/typescript-angular-petstore.sh
./bin/typescript-angular2-petstore.sh ./bin/typescript-angular2-petstore.sh
./bin/typescript-angular2-petstore-with-npm.sh
./bin/typescript-node-petstore.sh ./bin/typescript-node-petstore.sh
./bin/lumen-petstore-server.sh ./bin/lumen-petstore-server.sh

View File

@@ -26,6 +26,6 @@ fi
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/go -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l go -o samples/client/petstore/go/go-petstore" ags="$@ generate -t modules/swagger-codegen/src/main/resources/go -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l go -o samples/client/petstore/go/go-petstore -DpackageName=petstore "
java $JAVA_OPTS -jar $executable $ags java $JAVA_OPTS -jar $executable $ags

30
bin/groovy-petstore.sh Executable file
View File

@@ -0,0 +1,30 @@
#!/bin/sh
SCRIPT="$0"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l groovy -o samples/client/petstore/groovy -DhideGenerationTimestamp=true"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -26,6 +26,6 @@ fi
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/Javascript -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l javascript -o samples/client/petstore/javascript" ags="$@ generate -t modules/swagger-codegen/src/main/resources/Javascript -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l javascript -o samples/client/petstore/javascript"
java -DappName=PetstoreClient $JAVA_OPTS -jar $executable $ags java -DappName=PetstoreClient $JAVA_OPTS -jar $executable $ags

View File

@@ -27,7 +27,7 @@ fi
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/Javascript \ ags="$@ generate -t modules/swagger-codegen/src/main/resources/Javascript \
-i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l javascript \ -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l javascript \
-o samples/client/petstore/javascript-promise \ -o samples/client/petstore/javascript-promise \
--additional-properties usePromises=true" --additional-properties usePromises=true"

View File

@@ -0,0 +1,31 @@
#!/bin/sh
SCRIPT="$0"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaSpringBoot -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l springboot -o samples/server/petstore/springboot"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -26,6 +26,6 @@ fi
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-angular2 -c bin/typescript-angular2-petstore-with-npm.json -o samples/client/petstore/typescript-angular2-with-npm" ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-angular2 -c bin/typescript-petstore-npm.json -o samples/client/petstore/typescript-angular2/npm"
java $JAVA_OPTS -jar $executable $ags java $JAVA_OPTS -jar $executable $ags

View File

@@ -26,6 +26,6 @@ fi
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-angular2 -o samples/client/petstore/typescript-angular2" ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-angular2 -o samples/client/petstore/typescript-angular2/default"
java $JAVA_OPTS -jar $executable $ags java $JAVA_OPTS -jar $executable $ags

View File

@@ -0,0 +1,31 @@
#!/bin/sh
SCRIPT="$0"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -o samples/client/petstore/typescript-fetch/"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -0,0 +1,31 @@
#!/bin/sh
SCRIPT="$0"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-node -c bin/typescript-petstore-npm.json -o samples/client/petstore/typescript-node/npm"
java $JAVA_OPTS -jar $executable $ags

View File

@@ -26,6 +26,6 @@ fi
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-node -o samples/client/petstore/typescript-node" ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-node -o samples/client/petstore/typescript-node/default"
java $JAVA_OPTS -jar $executable $ags java $JAVA_OPTS -jar $executable $ags

View File

@@ -0,0 +1,10 @@
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar
If Not Exist %executable% (
mvn clean package
)
set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -t modules\swagger-codegen\src\main\resources\JavaSpringMVC -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l spring-mvc -o samples/server/petstore/spring-mvc-j8-async -c bin/spring-mvc-petstore-j8-async.json
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -0,0 +1,10 @@
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar
If Not Exist %executable% (
mvn clean package
)
set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -t modules\swagger-codegen\src\main\resources\JavaSpringMVC -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l spring-mvc -o samples\server\petstore\spring-mvc
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -0,0 +1,10 @@
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar
If Not Exist %executable% (
mvn clean package
)
set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -t modules\swagger-codegen\src\main\resources\JavaSpringBoot -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l springboot -o samples\server\petstore\springboot
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -0,0 +1,10 @@
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar
If Not Exist %executable% (
mvn clean package
)
set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -t modules\swagger-codegen\src\main\resources\typescript-angular -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -c bin/typescript-petstore-npm.json -l typescript-angular2 -o samples\client\petstore\typescript-angular2\npm
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -5,6 +5,6 @@ If Not Exist %executable% (
) )
set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -t modules\swagger-codegen\src\main\resources\typescript-angular -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l typescript-angular2 -o samples\client\petstore\typescript-angular set ags=generate -t modules\swagger-codegen\src\main\resources\typescript-angular -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l typescript-angular2 -o samples\client\petstore\typescript-angular2\default
java %JAVA_OPTS% -jar %executable% %ags% java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -0,0 +1,10 @@
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar
If Not Exist %executable% (
mvn clean package
)
set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -t modules\swagger-codegen\src\main\resources\typescript-fetch -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l typescript-fetch -o samples\client\petstore\typescript-fetch
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -0,0 +1,10 @@
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar
If Not Exist %executable% (
mvn clean package
)
set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -t modules\swagger-codegen\src\main\resources\typescript-node -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -c bin/typescript-petstore-npm.json -l typescript-node -o samples\client\petstore\typescript-node\npm
java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -5,6 +5,6 @@ If Not Exist %executable% (
) )
set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -t modules\swagger-codegen\src\main\resources\typescript-node -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l typescript-node -o samples\client\petstore\typescript-node set ags=generate -t modules\swagger-codegen\src\main\resources\typescript-node -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l typescript-node -o samples\client\petstore\typescript-node\default
java %JAVA_OPTS% -jar %executable% %ags% java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -89,7 +89,7 @@ public class CodegenConstants {
public static final String MODEL_NAME_SUFFIX_DESC = "Suffix that will be appended to all model names. Default is the empty string."; public static final String MODEL_NAME_SUFFIX_DESC = "Suffix that will be appended to all model names. Default is the empty string.";
public static final String OPTIONAL_EMIT_DEFAULT_VALUES = "optionalEmitDefaultValues"; public static final String OPTIONAL_EMIT_DEFAULT_VALUES = "optionalEmitDefaultValues";
public static final String OPTIONAL_EMIT_DEFAULT_VALUES_DESC = "Set DataMember's EmitDefaultValue, default false."; public static final String OPTIONAL_EMIT_DEFAULT_VALUES_DESC = "Set DataMember's EmitDefaultValue.";
public static final String GIT_USER_ID = "gitUserId"; public static final String GIT_USER_ID = "gitUserId";
public static final String GIT_USER_ID_DESC = "Git user ID, e.g. swagger-api."; public static final String GIT_USER_ID_DESC = "Git user ID, e.g. swagger-api.";
@@ -103,4 +103,6 @@ public class CodegenConstants {
public static final String HTTP_USER_AGENT = "httpUserAgent"; public static final String HTTP_USER_AGENT = "httpUserAgent";
public static final String HTTP_USER_AGENT_DESC = "HTTP user agent, e.g. codegen_csharp_api_client, default to 'Swagger-Codegen/{packageVersion}}/{language}'"; public static final String HTTP_USER_AGENT_DESC = "HTTP user agent, e.g. codegen_csharp_api_client, default to 'Swagger-Codegen/{packageVersion}}/{language}'";
public static final String SUPPORTS_ES6 = "supportsES6";
public static final String SUPPORTS_ES6_DESC = "Generate code that conforms to ES6.";
} }

View File

@@ -20,7 +20,7 @@ public class CodegenModel {
public List<CodegenProperty> requiredVars = new ArrayList<CodegenProperty>(); // a list of required properties public List<CodegenProperty> requiredVars = new ArrayList<CodegenProperty>(); // a list of required properties
public List<CodegenProperty> optionalVars = new ArrayList<CodegenProperty>(); // a list of optional properties public List<CodegenProperty> optionalVars = new ArrayList<CodegenProperty>(); // a list of optional properties
public List<CodegenProperty> allVars; public List<CodegenProperty> allVars;
public List<String> allowableValues; public Map<String, Object> allowableValues;
// Sorted sets of required parameters. // Sorted sets of required parameters.
public Set<String> mandatory = new TreeSet<String>(); public Set<String> mandatory = new TreeSet<String>();

View File

@@ -97,10 +97,10 @@ public class DefaultCodegen {
@SuppressWarnings({ "static-method", "unchecked" }) @SuppressWarnings({ "static-method", "unchecked" })
public Map<String, Object> postProcessAllModels(Map<String, Object> objs) { public Map<String, Object> postProcessAllModels(Map<String, Object> objs) {
if (supportsInheritance) { if (supportsInheritance) {
// Index all CodegenModels by name. // Index all CodegenModels by model name.
Map<String, CodegenModel> allModels = new HashMap<String, CodegenModel>(); Map<String, CodegenModel> allModels = new HashMap<String, CodegenModel>();
for (Entry<String, Object> entry : objs.entrySet()) { for (Entry<String, Object> entry : objs.entrySet()) {
String modelName = entry.getKey(); String modelName = toModelName(entry.getKey());
Map<String, Object> inner = (Map<String, Object>) entry.getValue(); Map<String, Object> inner = (Map<String, Object>) entry.getValue();
List<Map<String, Object>> models = (List<Map<String, Object>>) inner.get("models"); List<Map<String, Object>> models = (List<Map<String, Object>>) inner.get("models");
for (Map<String, Object> mo : models) { for (Map<String, Object> mo : models) {
@@ -133,6 +133,161 @@ public class DefaultCodegen {
return objs; return objs;
} }
/**
* post process enum defined in model's properties
*
* @param objs Map of models
* @return maps of models with better enum support
*/
public Map<String, Object> postProcessModelsEnum(Map<String, Object> objs) {
List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
// for enum model
if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) {
Map<String, Object> allowableValues = cm.allowableValues;
List<Object> values = (List<Object>) allowableValues.get("values");
List<Map<String, String>> enumVars = new ArrayList<Map<String, String>>();
String commonPrefix = findCommonPrefixOfVars(values);
int truncateIdx = commonPrefix.length();
for (Object value : values) {
Map<String, String> enumVar = new HashMap<String, String>();
String enumName;
if (truncateIdx == 0) {
enumName = value.toString();
} else {
enumName = value.toString().substring(truncateIdx);
if ("".equals(enumName)) {
enumName = value.toString();
}
}
enumVar.put("name", toEnumVarName(enumName, cm.dataType));
enumVar.put("value", toEnumValue(value.toString(), cm.dataType));
enumVars.add(enumVar);
}
cm.allowableValues.put("enumVars", enumVars);
}
// for enum model's properties
for (CodegenProperty var : cm.vars) {
Map<String, Object> allowableValues = var.allowableValues;
// handle ArrayProperty
if (var.items != null) {
allowableValues = var.items.allowableValues;
}
if (allowableValues == null) {
continue;
}
//List<String> values = (List<String>) allowableValues.get("values");
List<Object> values = (List<Object>) allowableValues.get("values");
if (values == null) {
continue;
}
// put "enumVars" map into `allowableValues", including `name` and `value`
List<Map<String, String>> enumVars = new ArrayList<Map<String, String>>();
String commonPrefix = findCommonPrefixOfVars(values);
int truncateIdx = commonPrefix.length();
for (Object value : values) {
Map<String, String> enumVar = new HashMap<String, String>();
String enumName;
if (truncateIdx == 0) {
enumName = value.toString();
} else {
enumName = value.toString().substring(truncateIdx);
if ("".equals(enumName)) {
enumName = value.toString();
}
}
enumVar.put("name", toEnumVarName(enumName, var.datatype));
enumVar.put("value", toEnumValue(value.toString(), var.datatype));
enumVars.add(enumVar);
}
allowableValues.put("enumVars", enumVars);
// handle default value for enum, e.g. available => StatusEnum.AVAILABLE
if (var.defaultValue != null) {
String enumName = null;
for (Map<String, String> enumVar : enumVars) {
if (toEnumValue(var.defaultValue, var.datatype).equals(enumVar.get("value"))) {
enumName = enumVar.get("name");
break;
}
}
if (enumName != null) {
var.defaultValue = toEnumDefaultValue(enumName, var.datatypeWithEnum);
}
}
}
}
return objs;
}
/**
* Returns the common prefix of variables for enum naming
*
* @param vars List of variable names
* @return the common prefix for naming
*/
public String findCommonPrefixOfVars(List<Object> vars) {
try {
String[] listStr = vars.toArray(new String[vars.size()]);
String prefix = StringUtils.getCommonPrefix(listStr);
// exclude trailing characters that should be part of a valid variable
// e.g. ["status-on", "status-off"] => "status-" (not "status-o")
return prefix.replaceAll("[a-zA-Z0-9]+\\z", "");
} catch (ArrayStoreException e) {
return "";
}
}
/**
* Return the enum default value in the language specifed format
*
* @param value enum variable name
* @param datatype data type
* @return the default value for the enum
*/
public String toEnumDefaultValue(String value, String datatype) {
return datatype + "." + value;
}
/**
* Return the enum value in the language specifed format
* e.g. status becomes "status"
*
* @param value enum variable name
* @param datatype data type
* @return the sanitized value for enum
*/
public String toEnumValue(String value, String datatype) {
if ("number".equalsIgnoreCase(datatype)) {
return value;
} else {
return "\"" + escapeText(value) + "\"";
}
}
/**
* Return the sanitized variable name for enum
*
* @param value enum variable name
* @param datatype data type
* @return the sanitized variable name for enum
*/
public String toEnumVarName(String value, String datatype) {
String var = value.replaceAll("\\W+", "_").toUpperCase();
if (var.matches("\\d.*")) {
return "_" + var;
} else {
return var;
}
}
// override with any special post-processing // override with any special post-processing
@SuppressWarnings("static-method") @SuppressWarnings("static-method")
@@ -328,12 +483,12 @@ public class DefaultCodegen {
} }
/** /**
* Return the JSON schema pattern (http://json-schema.org/latest/json-schema-validation.html#anchor33) * Return the regular expression/JSON schema pattern (http://json-schema.org/latest/json-schema-validation.html#anchor33)
* *
* @param pattern the pattern (regular expression) * @param pattern the pattern (regular expression)
* @return properly-escaped pattern * @return properly-escaped pattern
*/ */
public String toJSONSchemaPattern(String pattern) { public String toRegularExpression(String pattern) {
return escapeText(pattern); return escapeText(pattern);
} }
@@ -456,7 +611,7 @@ public class DefaultCodegen {
/** /**
* Return the Enum name (e.g. StatusEnum given 'status') * Return the Enum name (e.g. StatusEnum given 'status')
* *
* @param property Codegen property object * @param property Codegen property
* @return the Enum name * @return the Enum name
*/ */
@SuppressWarnings("static-method") @SuppressWarnings("static-method")
@@ -986,7 +1141,7 @@ public class DefaultCodegen {
m.interfaces.add(interfaceRef); m.interfaces.add(interfaceRef);
addImport(m, interfaceRef); addImport(m, interfaceRef);
if (allDefinitions != null) { if (allDefinitions != null) {
final Model interfaceModel = allDefinitions.get(interfaceRef); final Model interfaceModel = allDefinitions.get(_interface.getSimpleRef());
if (supportsInheritance) { if (supportsInheritance) {
addProperties(allProperties, allRequired, interfaceModel, allDefinitions); addProperties(allProperties, allRequired, interfaceModel, allDefinitions);
} else { } else {
@@ -1012,7 +1167,9 @@ public class DefaultCodegen {
ModelImpl impl = (ModelImpl) model; ModelImpl impl = (ModelImpl) model;
if(impl.getEnum() != null && impl.getEnum().size() > 0) { if(impl.getEnum() != null && impl.getEnum().size() > 0) {
m.isEnum = true; m.isEnum = true;
m.allowableValues = impl.getEnum(); // comment out below as allowableValues is not set in post processing model enum
m.allowableValues = new HashMap<String, Object>();
m.allowableValues.put("values", impl.getEnum());
Property p = PropertyBuilder.build(impl.getType(), impl.getFormat(), null); Property p = PropertyBuilder.build(impl.getType(), impl.getFormat(), null);
m.dataType = getSwaggerType(p); m.dataType = getSwaggerType(p);
} }
@@ -1043,7 +1200,7 @@ public class DefaultCodegen {
required.addAll(mi.getRequired()); required.addAll(mi.getRequired());
} }
} else if (model instanceof RefModel) { } else if (model instanceof RefModel) {
String interfaceRef = toModelName(((RefModel) model).getSimpleRef()); String interfaceRef = ((RefModel) model).getSimpleRef();
Model interfaceModel = allDefinitions.get(interfaceRef); Model interfaceModel = allDefinitions.get(interfaceRef);
addProperties(properties, required, interfaceModel, allDefinitions); addProperties(properties, required, interfaceModel, allDefinitions);
} else if (model instanceof ComposedModel) { } else if (model instanceof ComposedModel) {
@@ -1125,7 +1282,7 @@ public class DefaultCodegen {
StringProperty sp = (StringProperty) p; StringProperty sp = (StringProperty) p;
property.maxLength = sp.getMaxLength(); property.maxLength = sp.getMaxLength();
property.minLength = sp.getMinLength(); property.minLength = sp.getMinLength();
property.pattern = toJSONSchemaPattern(sp.getPattern()); property.pattern = toRegularExpression(sp.getPattern());
// check if any validation rule defined // check if any validation rule defined
if (property.pattern != null || property.minLength != null || property.maxLength != null) if (property.pattern != null || property.minLength != null || property.maxLength != null)
@@ -1144,7 +1301,8 @@ public class DefaultCodegen {
} }
} }
if (p instanceof BaseIntegerProperty) { // type is integer and without format
if (p instanceof BaseIntegerProperty && !(p instanceof IntegerProperty) && !(p instanceof LongProperty)) {
BaseIntegerProperty sp = (BaseIntegerProperty) p; BaseIntegerProperty sp = (BaseIntegerProperty) p;
property.isInteger = true; property.isInteger = true;
/*if (sp.getEnum() != null) { /*if (sp.getEnum() != null) {
@@ -1210,7 +1368,8 @@ public class DefaultCodegen {
property.isByteArray = true; property.isByteArray = true;
} }
if (p instanceof DecimalProperty) { // type is number and without format
if (p instanceof DecimalProperty && !(p instanceof DoubleProperty) && !(p instanceof FloatProperty)) {
DecimalProperty sp = (DecimalProperty) p; DecimalProperty sp = (DecimalProperty) p;
property.isFloat = true; property.isFloat = true;
/*if (sp.getEnum() != null) { /*if (sp.getEnum() != null) {
@@ -1828,7 +1987,7 @@ public class DefaultCodegen {
p.exclusiveMinimum = qp.isExclusiveMinimum(); p.exclusiveMinimum = qp.isExclusiveMinimum();
p.maxLength = qp.getMaxLength(); p.maxLength = qp.getMaxLength();
p.minLength = qp.getMinLength(); p.minLength = qp.getMinLength();
p.pattern = toJSONSchemaPattern(qp.getPattern()); p.pattern = toRegularExpression(qp.getPattern());
p.maxItems = qp.getMaxItems(); p.maxItems = qp.getMaxItems();
p.minItems = qp.getMinItems(); p.minItems = qp.getMinItems();
p.uniqueItems = qp.isUniqueItems(); p.uniqueItems = qp.isUniqueItems();

View File

@@ -264,6 +264,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
String suffix = config.modelTemplateFiles().get(templateName); String suffix = config.modelTemplateFiles().get(templateName);
String filename = config.modelFileFolder() + File.separator + config.toModelFilename(name) + suffix; String filename = config.modelFileFolder() + File.separator + config.toModelFilename(name) + suffix;
if (!config.shouldOverwrite(filename)) { if (!config.shouldOverwrite(filename)) {
LOGGER.info("Skipped overwriting " + filename);
continue; continue;
} }
String templateFile = getFullTemplateFile(config, templateName); String templateFile = getFullTemplateFile(config, templateName);
@@ -286,6 +287,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
String suffix = config.modelTestTemplateFiles().get(templateName); String suffix = config.modelTestTemplateFiles().get(templateName);
String filename = config.modelTestFileFolder() + File.separator + config.toModelTestFilename(name) + suffix; String filename = config.modelTestFileFolder() + File.separator + config.toModelTestFilename(name) + suffix;
if (!config.shouldOverwrite(filename)) { if (!config.shouldOverwrite(filename)) {
LOGGER.info("Skipped overwriting " + filename);
continue; continue;
} }
String templateFile = getFullTemplateFile(config, templateName); String templateFile = getFullTemplateFile(config, templateName);
@@ -308,6 +310,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
String suffix = config.modelDocTemplateFiles().get(templateName); String suffix = config.modelDocTemplateFiles().get(templateName);
String filename = config.modelDocFileFolder() + File.separator + config.toModelDocFilename(name) + suffix; String filename = config.modelDocFileFolder() + File.separator + config.toModelDocFilename(name) + suffix;
if (!config.shouldOverwrite(filename)) { if (!config.shouldOverwrite(filename)) {
LOGGER.info("Skipped overwriting " + filename);
continue; continue;
} }
String templateFile = getFullTemplateFile(config, templateName); String templateFile = getFullTemplateFile(config, templateName);
@@ -393,6 +396,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
for (String templateName : config.apiTemplateFiles().keySet()) { for (String templateName : config.apiTemplateFiles().keySet()) {
String filename = config.apiFilename(templateName, tag); String filename = config.apiFilename(templateName, tag);
if (!config.shouldOverwrite(filename) && new File(filename).exists()) { if (!config.shouldOverwrite(filename) && new File(filename).exists()) {
LOGGER.info("Skipped overwriting " + filename);
continue; continue;
} }
@@ -416,6 +420,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
for (String templateName : config.apiTestTemplateFiles().keySet()) { for (String templateName : config.apiTestTemplateFiles().keySet()) {
String filename = config.apiTestFilename(templateName, tag); String filename = config.apiTestFilename(templateName, tag);
if (!config.shouldOverwrite(filename) && new File(filename).exists()) { if (!config.shouldOverwrite(filename) && new File(filename).exists()) {
LOGGER.info("Skipped overwriting " + filename);
continue; continue;
} }
@@ -439,6 +444,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
for (String templateName : config.apiDocTemplateFiles().keySet()) { for (String templateName : config.apiDocTemplateFiles().keySet()) {
String filename = config.apiDocFilename(templateName, tag); String filename = config.apiDocFilename(templateName, tag);
if (!config.shouldOverwrite(filename) && new File(filename).exists()) { if (!config.shouldOverwrite(filename) && new File(filename).exists()) {
LOGGER.info("Skipped overwriting " + filename);
continue; continue;
} }
@@ -521,6 +527,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
} }
String outputFilename = outputFolder + File.separator + support.destinationFilename; String outputFilename = outputFolder + File.separator + support.destinationFilename;
if (!config.shouldOverwrite(outputFilename)) { if (!config.shouldOverwrite(outputFilename)) {
LOGGER.info("Skipped overwriting " + outputFilename);
continue; continue;
} }

View File

@@ -60,8 +60,8 @@ public class CodegenConfigurator {
private Map<String, String> additionalProperties = new HashMap<String, String>(); private Map<String, String> additionalProperties = new HashMap<String, String>();
private Map<String, String> importMappings = new HashMap<String, String>(); private Map<String, String> importMappings = new HashMap<String, String>();
private Set<String> languageSpecificPrimitives = new HashSet<String>(); private Set<String> languageSpecificPrimitives = new HashSet<String>();
private String gitUserId="YOUR_GIT_USR_ID"; private String gitUserId="GIT_USER_ID";
private String gitRepoId="YOUR_GIT_REPO_ID"; private String gitRepoId="GIT_REPO_ID";
private String releaseNote="Minor update"; private String releaseNote="Minor update";
private String httpUserAgent; private String httpUserAgent;

View File

@@ -88,7 +88,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
"Int32", "Int32",
"Int64", "Int64",
"Float", "Float",
"Guid", "Guid?",
"System.IO.Stream", // not really a primitive, we include it to avoid model import "System.IO.Stream", // not really a primitive, we include it to avoid model import
"Object") "Object")
); );
@@ -115,7 +115,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
typeMapping.put("list", "List"); typeMapping.put("list", "List");
typeMapping.put("map", "Dictionary"); typeMapping.put("map", "Dictionary");
typeMapping.put("object", "Object"); typeMapping.put("object", "Object");
typeMapping.put("uuid", "Guid"); typeMapping.put("uuid", "Guid?");
} }
public void setReturnICollection(boolean returnICollection) { public void setReturnICollection(boolean returnICollection) {
@@ -203,11 +203,6 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
} }
} }
@Override
public String toEnumName(CodegenProperty property) {
return StringUtils.capitalize(property.name) + "Enum?";
}
@Override @Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) { public Map<String, Object> postProcessModels(Map<String, Object> objs) {
List<Object> models = (List<Object>) objs.get("models"); List<Object> models = (List<Object>) objs.get("models");
@@ -223,7 +218,8 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
} }
} }
} }
return objs; // process enum in models
return postProcessModelsEnum(objs);
} }
@Override @Override
@@ -544,4 +540,54 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
public void setSourceFolder(String sourceFolder) { public void setSourceFolder(String sourceFolder) {
this.sourceFolder = sourceFolder; this.sourceFolder = sourceFolder;
} }
@Override
public String toEnumVarName(String name, String datatype) {
String enumName = sanitizeName(name);
enumName = enumName.replaceFirst("^_", "");
enumName = enumName.replaceFirst("_$", "");
enumName = camelize(enumName) + "Enum";
LOGGER.info("toEnumVarName = " + enumName);
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
} else {
return enumName;
}
}
@Override
public String toEnumName(CodegenProperty property) {
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;
}
}
*/
} }

View File

@@ -11,6 +11,7 @@ import org.apache.commons.lang.StringUtils;
public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig { public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String modelPropertyNaming= "camelCase"; protected String modelPropertyNaming= "camelCase";
protected Boolean supportsES6 = true;
public AbstractTypeScriptClientCodegen() { public AbstractTypeScriptClientCodegen() {
super(); super();
@@ -60,18 +61,25 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
// mapped to String as a workaround // mapped to String as a workaround
typeMapping.put("binary", "string"); typeMapping.put("binary", "string");
typeMapping.put("ByteArray", "string"); typeMapping.put("ByteArray", "string");
typeMapping.put("UUID", "string");
cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase")); cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase"));
cliOptions.add(new CliOption(CodegenConstants.SUPPORTS_ES6, CodegenConstants.SUPPORTS_ES6_DESC).defaultValue("false"));
} }
@Override @Override
public void processOpts() { public void processOpts() {
super.processOpts(); super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) { if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) {
setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING)); setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING));
} }
if (additionalProperties.containsKey(CodegenConstants.SUPPORTS_ES6)) {
setSupportsES6(Boolean.valueOf((String)additionalProperties.get(CodegenConstants.SUPPORTS_ES6)));
additionalProperties.put("supportsES6", getSupportsES6());
}
} }
@@ -230,4 +238,66 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
} }
} }
@Override
public String toEnumValue(String value, String datatype) {
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {
return value;
} else {
return "\'" + escapeText(value) + "\'";
}
}
@Override
public String toEnumDefaultValue(String value, String datatype) {
return datatype + "_" + value;
}
@Override
public String toEnumVarName(String name, String datatype) {
// number
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {
String varName = new String(name);
varName = varName.replaceAll("-", "MINUS_");
varName = varName.replaceAll("\\+", "PLUS_");
varName = varName.replaceAll("\\.", "_DOT_");
return varName;
}
// string
String enumName = sanitizeName(underscore(name).toUpperCase());
enumName = enumName.replaceFirst("^_", "");
enumName = enumName.replaceFirst("_$", "");
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
} else {
return enumName;
}
}
@Override
public String toEnumName(CodegenProperty property) {
String enumName = toModelName(property.name) + "Enum";
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
} else {
return enumName;
}
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// process enum in models
return postProcessModelsEnum(objs);
}
public void setSupportsES6(Boolean value) {
supportsES6 = value;
}
public Boolean getSupportsES6() {
return supportsES6;
}
} }

View File

@@ -308,75 +308,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
@Override @Override
public Map<String, Object> postProcessModels(Map<String, Object> objMap) { public Map<String, Object> postProcessModels(Map<String, Object> objMap) {
Map<String, Object> objs = super.postProcessModels(objMap); return super.postProcessModels(objMap);
List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
for (CodegenProperty var : cm.vars) {
Map<String, Object> allowableValues = var.allowableValues;
// handle ArrayProperty
if (var.items != null) {
allowableValues = var.items.allowableValues;
}
if (allowableValues == null) {
continue;
}
List<String> values = (List<String>) allowableValues.get("values");
if (values == null) {
continue;
}
// put "enumVars" map into `allowableValues", including `name` and `value`
List<Map<String, String>> enumVars = new ArrayList<Map<String, String>>();
String commonPrefix = findCommonPrefixOfVars(values);
int truncateIdx = commonPrefix.length();
for (String value : values) {
Map<String, String> enumVar = new HashMap<String, String>();
String enumName;
if (truncateIdx == 0) {
enumName = value;
} else {
enumName = value.substring(truncateIdx);
if ("".equals(enumName)) {
enumName = value;
}
}
enumVar.put("name", toEnumVarName(enumName));
enumVar.put("jsonname", value);
enumVar.put("value", value);
enumVars.add(enumVar);
}
allowableValues.put("enumVars", enumVars);
// handle default value for enum, e.g. available => StatusEnum.AVAILABLE
// HACK: strip ? from enum
if (var.datatypeWithEnum != null) {
var.vendorExtensions.put(DATA_TYPE_WITH_ENUM_EXTENSION, var.datatypeWithEnum.substring(0, var.datatypeWithEnum.length() - 1));
}
if (var.defaultValue != null) {
String enumName = null;
for (Map<String, String> enumVar : enumVars) {
if (var.defaultValue.replace("\"", "").equals(enumVar.get("value"))) {
enumName = enumVar.get("name");
break;
}
}
if (enumName != null && var.vendorExtensions.containsKey(DATA_TYPE_WITH_ENUM_EXTENSION)) {
var.defaultValue = var.vendorExtensions.get(DATA_TYPE_WITH_ENUM_EXTENSION) + "." + enumName;
}
}
}
}
return objs;
} }
public void setTargetFramework(String dotnetFramework) { public void setTargetFramework(String dotnetFramework) {
@@ -436,18 +368,34 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
return codegenModel; return codegenModel;
} }
private String findCommonPrefixOfVars(List<String> vars) { @Override
String prefix = StringUtils.getCommonPrefix(vars.toArray(new String[vars.size()])); public String toEnumValue(String value, String datatype) {
// exclude trailing characters that should be part of a valid variable if ("int?".equalsIgnoreCase(datatype) || "long?".equalsIgnoreCase(datatype) ||
// e.g. ["status-on", "status-off"] => "status-" (not "status-o") "double?".equalsIgnoreCase(datatype) || "float?".equalsIgnoreCase(datatype)) {
return prefix.replaceAll("[a-zA-Z0-9]+\\z", ""); return value;
} else {
return "\"" + escapeText(value) + "\"";
}
} }
private String toEnumVarName(String value) { @Override
public String toEnumVarName(String value, String datatype) {
// number
if ("int?".equals(datatype) || "long?".equals(datatype) ||
"double?".equals(datatype) || "float?".equals(datatype)) {
String varName = "NUMBER_" + value;
varName = varName.replaceAll("-", "MINUS_");
varName = varName.replaceAll("\\+", "PLUS_");
varName = varName.replaceAll("\\.", "_DOT_");
return varName;
}
// string
String var = value.replaceAll("_", " "); String var = value.replaceAll("_", " ");
var = WordUtils.capitalizeFully(var); var = WordUtils.capitalizeFully(var);
var = var.replaceAll("\\W+", ""); var = var.replaceAll("\\W+", "");
if (var.matches("\\d.*")) { if (var.matches("\\d.*")) {
return "_" + var; return "_" + var;
} else { } else {

View File

@@ -375,6 +375,15 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
if (_import.startsWith(apiPackage())) if (_import.startsWith(apiPackage()))
iterator.remove(); iterator.remove();
} }
// if the return type is not primitive, import encoding/json
for (CodegenOperation operation : operations) {
if(operation.returnBaseType != null && needToImport(operation.returnBaseType)) {
Map<String, String> customImport = new HashMap<String, String>();
customImport.put("import", "encoding/json");
imports.add(customImport);
break; //just need to import once
}
}
// recursivly add import for mapping one type to multipe imports // recursivly add import for mapping one type to multipe imports
List<Map<String, String>> recursiveImports = (List<Map<String, String>>) objs.get("imports"); List<Map<String, String>> recursiveImports = (List<Map<String, String>>) objs.get("imports");

View File

@@ -11,6 +11,7 @@ import io.swagger.models.parameters.Parameter;
import io.swagger.models.properties.*; import io.swagger.models.properties.*;
import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -89,6 +90,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
instantiationTypes.put("map", "HashMap"); instantiationTypes.put("map", "HashMap");
typeMapping.put("date", "Date"); typeMapping.put("date", "Date");
typeMapping.put("file", "File"); typeMapping.put("file", "File");
typeMapping.put("UUID", "String");
cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC));
@@ -110,7 +112,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6");
supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1"); supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1");
supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)");
supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta4). Enable the RxJava adapter using '-DuseRxJava=true'."); supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.1). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.2)");
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setDefault(DEFAULT_LIBRARY); library.setDefault(DEFAULT_LIBRARY);
@@ -651,6 +653,28 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
return codegenModel; return codegenModel;
} }
@Override
public Map<String, Object> postProcessModelsEnum(Map<String, Object> objs) {
objs = super.postProcessModelsEnum(objs);
String lib = getLibrary();
if (StringUtils.isEmpty(lib) || "feign".equals(lib) || "jersey2".equals(lib)) {
List<Map<String, String>> imports = (List<Map<String, String>>)objs.get("imports");
List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
// for enum model
if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) {
cm.imports.add(importMapping.get("JsonValue"));
Map<String, String> item = new HashMap<String, String>();
item.put("import", importMapping.get("JsonValue"));
imports.add(item);
}
}
}
return objs;
}
@Override @Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
if(serializeBigDecimalAsString) { if(serializeBigDecimalAsString) {
@@ -696,63 +720,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) { public Map<String, Object> postProcessModels(Map<String, Object> objs) {
List<Object> models = (List<Object>) objs.get("models"); return postProcessModelsEnum(objs);
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
for (CodegenProperty var : cm.vars) {
Map<String, Object> allowableValues = var.allowableValues;
// handle ArrayProperty
if (var.items != null) {
allowableValues = var.items.allowableValues;
}
if (allowableValues == null) {
continue;
}
List<String> values = (List<String>) allowableValues.get("values");
if (values == null) {
continue;
}
// put "enumVars" map into `allowableValues", including `name` and `value`
List<Map<String, String>> enumVars = new ArrayList<Map<String, String>>();
String commonPrefix = findCommonPrefixOfVars(values);
int truncateIdx = commonPrefix.length();
for (String value : values) {
Map<String, String> enumVar = new HashMap<String, String>();
String enumName;
if (truncateIdx == 0) {
enumName = value;
} else {
enumName = value.substring(truncateIdx);
if ("".equals(enumName)) {
enumName = value;
}
}
enumVar.put("name", toEnumVarName(enumName));
enumVar.put("value", value);
enumVars.add(enumVar);
}
allowableValues.put("enumVars", enumVars);
// handle default value for enum, e.g. available => StatusEnum.AVAILABLE
if (var.defaultValue != null) {
String enumName = null;
for (Map<String, String> enumVar : enumVars) {
if (var.defaultValue.equals(enumVar.get("value"))) {
enumName = enumVar.get("name");
break;
}
}
if (enumName != null) {
var.defaultValue = var.datatypeWithEnum + "." + enumName;
}
}
}
}
return objs;
} }
@Override @Override
@@ -848,16 +816,35 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
protected boolean needToImport(String type) { protected boolean needToImport(String type) {
return super.needToImport(type) && type.indexOf(".") < 0; return super.needToImport(type) && type.indexOf(".") < 0;
} }
/*
private static String findCommonPrefixOfVars(List<String> vars) { @Override
public String findCommonPrefixOfVars(List<String> vars) {
String prefix = StringUtils.getCommonPrefix(vars.toArray(new String[vars.size()])); String prefix = StringUtils.getCommonPrefix(vars.toArray(new String[vars.size()]));
// exclude trailing characters that should be part of a valid variable // exclude trailing characters that should be part of a valid variable
// e.g. ["status-on", "status-off"] => "status-" (not "status-o") // e.g. ["status-on", "status-off"] => "status-" (not "status-o")
return prefix.replaceAll("[a-zA-Z0-9]+\\z", ""); return prefix.replaceAll("[a-zA-Z0-9]+\\z", "");
} }
*/
private static String toEnumVarName(String value) { @Override
String var = value.replaceAll("\\W+", "_").toUpperCase(); public String toEnumName(CodegenProperty property) {
return sanitizeName(camelize(property.name)) + "Enum";
}
@Override
public String toEnumVarName(String value, String datatype) {
// number
if ("Integer".equals(datatype) || "Long".equals(datatype) ||
"Float".equals(datatype) || "Double".equals(datatype)) {
String varName = "NUMBER_" + value;
varName = varName.replaceAll("-", "MINUS_");
varName = varName.replaceAll("\\+", "PLUS_");
varName = varName.replaceAll("\\.", "_DOT_");
return varName;
}
// string
String var = value.replaceAll("\\W+", "_").replaceAll("_+", "_").toUpperCase();
if (var.matches("\\d.*")) { if (var.matches("\\d.*")) {
return "_" + var; return "_" + var;
} else { } else {
@@ -865,6 +852,16 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
} }
} }
@Override
public String toEnumValue(String value, String datatype) {
if ("Integer".equals(datatype) || "Long".equals(datatype) ||
"Float".equals(datatype) || "Double".equals(datatype)) {
return value;
} else {
return "\"" + escapeText(value) + "\"";
}
}
private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) {
// This generator uses inline classes to define enums, which breaks when // This generator uses inline classes to define enums, which breaks when
// dealing with models that have subTypes. To clean this up, we will analyze // dealing with models that have subTypes. To clean this up, we will analyze

View File

@@ -12,9 +12,12 @@ import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.SupportingFile; import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.DefaultCodegen;
import io.swagger.models.ArrayModel;
import io.swagger.models.ComposedModel;
import io.swagger.models.Info; import io.swagger.models.Info;
import io.swagger.models.License; import io.swagger.models.License;
import io.swagger.models.Model; import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
import io.swagger.models.Operation; import io.swagger.models.Operation;
import io.swagger.models.Swagger; import io.swagger.models.Swagger;
import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.ArrayProperty;
@@ -63,6 +66,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
protected String projectVersion; protected String projectVersion;
protected String projectLicenseName; protected String projectLicenseName;
protected String invokerPackage;
protected String sourceFolder = "src"; protected String sourceFolder = "src";
protected String localVariablePrefix = ""; protected String localVariablePrefix = "";
protected boolean usePromises; protected boolean usePromises;
@@ -132,11 +136,13 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
// binary not supported in JavaScript client right now, using String as a workaround // binary not supported in JavaScript client right now, using String as a workaround
typeMapping.put("ByteArray", "String"); // I don't see ByteArray defined in the Swagger docs. typeMapping.put("ByteArray", "String"); // I don't see ByteArray defined in the Swagger docs.
typeMapping.put("binary", "String"); typeMapping.put("binary", "String");
typeMapping.put("UUID", "String");
importMapping.clear(); importMapping.clear();
cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC).defaultValue("src")); cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC).defaultValue("src"));
cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC)); cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC));
cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC));
cliOptions.add(new CliOption(PROJECT_NAME, cliOptions.add(new CliOption(PROJECT_NAME,
@@ -203,6 +209,9 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
} }
if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) {
setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE));
}
if (additionalProperties.containsKey(USE_PROMISES)) { if (additionalProperties.containsKey(USE_PROMISES)) {
setUsePromises(Boolean.parseBoolean((String)additionalProperties.get(USE_PROMISES))); setUsePromises(Boolean.parseBoolean((String)additionalProperties.get(USE_PROMISES)));
} }
@@ -265,6 +274,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
additionalProperties.put(PROJECT_DESCRIPTION, escapeText(projectDescription)); additionalProperties.put(PROJECT_DESCRIPTION, escapeText(projectDescription));
additionalProperties.put(PROJECT_VERSION, projectVersion); additionalProperties.put(PROJECT_VERSION, projectVersion);
additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage);
additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put(CodegenConstants.LOCAL_VARIABLE_PREFIX, localVariablePrefix); additionalProperties.put(CodegenConstants.LOCAL_VARIABLE_PREFIX, localVariablePrefix);
additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage); additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage);
additionalProperties.put(CodegenConstants.SOURCE_FOLDER, sourceFolder); additionalProperties.put(CodegenConstants.SOURCE_FOLDER, sourceFolder);
@@ -278,8 +288,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
additionalProperties.put("modelDocPath", modelDocPath); additionalProperties.put("modelDocPath", modelDocPath);
supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("index.mustache", sourceFolder, "index.js")); supportingFiles.add(new SupportingFile("index.mustache", createPath(sourceFolder, invokerPackage), "index.js"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", sourceFolder, "ApiClient.js")); supportingFiles.add(new SupportingFile("ApiClient.mustache", createPath(sourceFolder, invokerPackage), "ApiClient.js"));
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("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
} }
@@ -289,14 +299,41 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
return "_" + name; return "_" + name;
} }
/**
* Concatenates an array of path segments into a path string.
* @param segments The path segments to concatenate. A segment may contain either of the file separator characters '\' or '/'.
* A segment is ignored if it is <code>null</code>, empty or &quot;.&quot;.
* @return A path string using the correct platform-specific file separator character.
*/
private String createPath(String... segments) {
StringBuilder buf = new StringBuilder();
for (String segment : segments) {
if (!StringUtils.isEmpty(segment) && !segment.equals(".")) {
if (buf.length() != 0)
buf.append(File.separatorChar);
buf.append(segment);
}
}
for (int i = 0; i < buf.length(); i++) {
char c = buf.charAt(i);
if ((c == '/' || c == '\\') && c != File.separatorChar)
buf.setCharAt(i, File.separatorChar);
}
return buf.toString();
}
@Override @Override
public String apiFileFolder() { public String apiFileFolder() {
return outputFolder + '/' + sourceFolder + '/' + apiPackage().replace('.', '/'); return createPath(outputFolder, sourceFolder, invokerPackage, apiPackage());
} }
@Override @Override
public String modelFileFolder() { public String modelFileFolder() {
return outputFolder + '/' + sourceFolder + '/' + modelPackage().replace('.', '/'); return createPath(outputFolder, sourceFolder, invokerPackage, modelPackage());
}
public void setInvokerPackage(String invokerPackage) {
this.invokerPackage = invokerPackage;
} }
public void setSourceFolder(String sourceFolder) { public void setSourceFolder(String sourceFolder) {
@@ -345,12 +382,12 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
@Override @Override
public String apiDocFileFolder() { public String apiDocFileFolder() {
return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); return createPath(outputFolder, apiDocPath);
} }
@Override @Override
public String modelDocFileFolder() { public String modelDocFileFolder() {
return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); return createPath(outputFolder, modelDocPath);
} }
@Override @Override
@@ -654,10 +691,23 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
if (allDefinitions != null && codegenModel != null && codegenModel.parent != null && codegenModel.hasEnums) { if (allDefinitions != null && codegenModel != null && codegenModel.parent != null && codegenModel.hasEnums) {
final Model parentModel = allDefinitions.get(toModelName(codegenModel.parent)); final Model parentModel = allDefinitions.get(codegenModel.parentSchema);
final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel, allDefinitions);
codegenModel = JavascriptClientCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel); codegenModel = JavascriptClientCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel);
} }
if (model instanceof ArrayModel) {
ArrayModel am = (ArrayModel) model;
if (am.getItems() != null) {
codegenModel.vendorExtensions.put("x-isArray", true);
codegenModel.vendorExtensions.put("x-itemType", getSwaggerType(am.getItems()));
}
} else if (model instanceof ModelImpl) {
ModelImpl mm = (ModelImpl)model;
if (mm.getAdditionalProperties() != null) {
codegenModel.vendorExtensions.put("x-isMap", true);
codegenModel.vendorExtensions.put("x-itemType", getSwaggerType(mm.getAdditionalProperties()));
}
}
return codegenModel; return codegenModel;
} }
@@ -674,7 +724,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
} }
private String getModelledType(String dataType) { private String getModelledType(String dataType) {
return "module:" + (StringUtils.isEmpty(modelPackage) ? "" : (modelPackage + "/")) + dataType; return "module:" + (StringUtils.isEmpty(invokerPackage) ? "" : (invokerPackage + "/"))
+ (StringUtils.isEmpty(modelPackage) ? "" : (modelPackage + "/")) + dataType;
} }
private String getJSDocTypeWithBraces(CodegenModel cm, CodegenProperty cp) { private String getJSDocTypeWithBraces(CodegenModel cm, CodegenProperty cp) {
@@ -788,6 +839,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) { public Map<String, Object> postProcessModels(Map<String, Object> objs) {
objs = super.postProcessModelsEnum(objs);
List<Object> models = (List<Object>) objs.get("models"); List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) { for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo; Map<String, Object> mo = (Map<String, Object>) _mo;
@@ -802,8 +854,6 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
cm.vendorExtensions.put("x-all-required", allRequired); cm.vendorExtensions.put("x-all-required", allRequired);
for (CodegenProperty var : cm.vars) { for (CodegenProperty var : cm.vars) {
Map<String, Object> allowableValues = var.allowableValues;
// Add JSDoc @type value for this property. // Add JSDoc @type value for this property.
String jsDocType = getJSDocTypeWithBraces(cm, var); String jsDocType = getJSDocTypeWithBraces(cm, var);
var.vendorExtensions.put("x-jsdoc-type", jsDocType); var.vendorExtensions.put("x-jsdoc-type", jsDocType);
@@ -811,40 +861,6 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
if (Boolean.TRUE.equals(var.required)) { if (Boolean.TRUE.equals(var.required)) {
required.add(var.name); required.add(var.name);
} }
// handle ArrayProperty
if (var.items != null) {
allowableValues = var.items.allowableValues;
}
if (allowableValues == null) {
continue;
}
List<String> values = (List<String>) allowableValues.get("values");
if (values == null) {
continue;
}
// put "enumVars" map into `allowableValues", including `name` and `value`
List<Map<String, String>> enumVars = new ArrayList<Map<String, String>>();
String commonPrefix = findCommonPrefixOfVars(values);
int truncateIdx = commonPrefix.length();
for (String value : values) {
Map<String, String> enumVar = new HashMap<String, String>();
String enumName;
if (truncateIdx == 0) {
enumName = value;
} else {
enumName = value.substring(truncateIdx);
if ("".equals(enumName)) {
enumName = value;
}
}
enumVar.put("name", toEnumVarName(enumName));
enumVar.put("value", value);
enumVars.add(enumVar);
}
allowableValues.put("enumVars", enumVars);
} }
if (supportsInheritance) { if (supportsInheritance) {
@@ -878,22 +894,15 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
return !defaultIncludes.contains(type) return !defaultIncludes.contains(type)
&& !languageSpecificPrimitives.contains(type); && !languageSpecificPrimitives.contains(type);
} }
/*
private static String findCommonPrefixOfVars(List<String> vars) { @Override
public String findCommonPrefixOfVars(List<String> vars) {
String prefix = StringUtils.getCommonPrefix(vars.toArray(new String[vars.size()])); String prefix = StringUtils.getCommonPrefix(vars.toArray(new String[vars.size()]));
// exclude trailing characters that should be part of a valid variable // exclude trailing characters that should be part of a valid variable
// e.g. ["status-on", "status-off"] => "status-" (not "status-o") // e.g. ["status-on", "status-off"] => "status-" (not "status-o")
return prefix.replaceAll("[a-zA-Z0-9]+\\z", ""); return prefix.replaceAll("[a-zA-Z0-9]+\\z", "");
} }
*/
private static String toEnumVarName(String value) {
String var = value.replaceAll("\\W+", "_").toUpperCase();
if (var.matches("\\d.*")) {
return "_" + var;
} else {
return var;
}
}
private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) {
// This generator uses inline classes to define enums, which breaks when // This generator uses inline classes to define enums, which breaks when
@@ -952,4 +961,41 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
return packageName; return packageName;
} }
@Override
public String toEnumName(CodegenProperty property) {
return sanitizeName(camelize(property.name)) + "Enum";
}
@Override
public String toEnumVarName(String value, String datatype) {
return value;
/*
// number
if ("Integer".equals(datatype) || "Number".equals(datatype)) {
String varName = "NUMBER_" + value;
varName = varName.replaceAll("-", "MINUS_");
varName = varName.replaceAll("\\+", "PLUS_");
varName = varName.replaceAll("\\.", "_DOT_");
return varName;
}
// string
String var = value.replaceAll("\\W+", "_").replaceAll("_+", "_").toUpperCase();
if (var.matches("\\d.*")) {
return "_" + var;
} else {
return var;
}
*/
}
@Override
public String toEnumValue(String value, String datatype) {
if ("Integer".equals(datatype) || "Number".equals(datatype)) {
return value;
} else {
return "\"" + escapeText(value) + "\"";
}
}
} }

View File

@@ -4,6 +4,7 @@ import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenParameter; import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType; import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile; import io.swagger.codegen.SupportingFile;
@@ -12,6 +13,7 @@ import io.swagger.models.properties.*;
import java.io.File; import java.io.File;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map;
import java.util.HashSet; import java.util.HashSet;
import java.util.regex.Matcher; import java.util.regex.Matcher;
@@ -111,6 +113,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("object", "object"); typeMapping.put("object", "object");
typeMapping.put("binary", "string"); typeMapping.put("binary", "string");
typeMapping.put("ByteArray", "string"); typeMapping.put("ByteArray", "string");
typeMapping.put("UUID", "string");
cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC));
@@ -566,4 +569,57 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
p.example = example; p.example = example;
} }
@Override
public String toEnumValue(String value, String datatype) {
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {
return value;
} else {
return "\'" + escapeText(value) + "\'";
}
}
@Override
public String toEnumDefaultValue(String value, String datatype) {
return datatype + "_" + value;
}
@Override
public String toEnumVarName(String name, String datatype) {
// number
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {
String varName = new String(name);
varName = varName.replaceAll("-", "MINUS_");
varName = varName.replaceAll("\\+", "PLUS_");
varName = varName.replaceAll("\\.", "_DOT_");
return varName;
}
// string
String enumName = sanitizeName(underscore(name).toUpperCase());
enumName = enumName.replaceFirst("^_", "");
enumName = enumName.replaceFirst("_$", "");
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
} else {
return enumName;
}
}
@Override
public String toEnumName(CodegenProperty property) {
String enumName = underscore(toModelName(property.name)).toUpperCase();
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
} else {
return enumName;
}
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// process enum in models
return postProcessModelsEnum(objs);
}
} }

View File

@@ -20,6 +20,8 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
protected String packageVersion; protected String packageVersion;
protected String apiDocPath = "docs/"; protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/"; protected String modelDocPath = "docs/";
private String testFolder;
public PythonClientCodegen() { public PythonClientCodegen() {
super(); super();
@@ -27,12 +29,19 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
modelPackage = "models"; modelPackage = "models";
apiPackage = "api"; apiPackage = "api";
outputFolder = "generated-code" + File.separatorChar + "python"; outputFolder = "generated-code" + File.separatorChar + "python";
modelTemplateFiles.put("model.mustache", ".py"); modelTemplateFiles.put("model.mustache", ".py");
apiTemplateFiles.put("api.mustache", ".py"); apiTemplateFiles.put("api.mustache", ".py");
modelTestTemplateFiles.put("model_test.mustache", ".py");
apiTestTemplateFiles.put("api_test.mustache", ".py");
embeddedTemplateDir = templateDir = "python"; embeddedTemplateDir = templateDir = "python";
modelDocTemplateFiles.put("model_doc.mustache", ".md"); modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md");
testFolder = "test";
languageSpecificPrimitives.clear(); languageSpecificPrimitives.clear();
languageSpecificPrimitives.add("int"); languageSpecificPrimitives.add("int");
@@ -58,10 +67,12 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
typeMapping.put("DateTime", "datetime"); typeMapping.put("DateTime", "datetime");
typeMapping.put("object", "object"); typeMapping.put("object", "object");
typeMapping.put("file", "file"); typeMapping.put("file", "file");
//TODO binary should be mapped to byte array // TODO binary should be mapped to byte array
// mapped to String as a workaround // mapped to String as a workaround
typeMapping.put("binary", "str"); typeMapping.put("binary", "str");
typeMapping.put("ByteArray", "str"); typeMapping.put("ByteArray", "str");
// map uuid to string for the time being
typeMapping.put("UUID", "str");
// from https://docs.python.org/release/2.5.4/ref/keywords.html // from https://docs.python.org/release/2.5.4/ref/keywords.html
setReservedWordsLowerCase( setReservedWordsLowerCase(
@@ -124,6 +135,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
supportingFiles.add(new SupportingFile("__init__package.mustache", swaggerFolder, "__init__.py")); supportingFiles.add(new SupportingFile("__init__package.mustache", swaggerFolder, "__init__.py"));
supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage, "__init__.py")); supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage, "__init__.py"));
supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py")); supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py"));
supportingFiles.add(new SupportingFile("__init__test.mustache", testFolder, "__init__.py"));
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"));
} }
@@ -182,6 +194,16 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
public String modelFileFolder() { public String modelFileFolder() {
return outputFolder + File.separatorChar + modelPackage().replace('.', File.separatorChar); return outputFolder + File.separatorChar + modelPackage().replace('.', File.separatorChar);
} }
@Override
public String apiTestFileFolder() {
return outputFolder + File.separatorChar + testFolder;
}
@Override
public String modelTestFileFolder() {
return outputFolder + File.separatorChar + testFolder;
}
@Override @Override
public String getTypeDeclaration(Property p) { public String getTypeDeclaration(Property p) {
@@ -308,6 +330,11 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
// PhoneNumber => phone_number // PhoneNumber => phone_number
return underscore(dropDots(name)); return underscore(dropDots(name));
} }
@Override
public String toModelTestFilename(String name) {
return "test_" + toModelFilename(name);
};
@Override @Override
public String toApiFilename(String name) { public String toApiFilename(String name) {
@@ -317,6 +344,11 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
// e.g. PhoneNumberApi.rb => phone_number_api.rb // e.g. PhoneNumberApi.rb => phone_number_api.rb
return underscore(name) + "_api"; return underscore(name) + "_api";
} }
@Override
public String toApiTestFilename(String name) {
return "test_" + toApiFilename(name);
}
@Override @Override
public String toApiName(String name) { public String toApiName(String name) {

View File

@@ -117,6 +117,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("file", "File"); typeMapping.put("file", "File");
typeMapping.put("binary", "String"); typeMapping.put("binary", "String");
typeMapping.put("ByteArray", "String"); typeMapping.put("ByteArray", "String");
typeMapping.put("UUID", "String");
// remove modelPackage and apiPackage added by default // remove modelPackage and apiPackage added by default
Iterator<CliOption> itr = cliOptions.iterator(); Iterator<CliOption> itr = cliOptions.iterator();
@@ -642,4 +643,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
public void setGemAuthorEmail(String gemAuthorEmail) { public void setGemAuthorEmail(String gemAuthorEmail) {
this.gemAuthorEmail = gemAuthorEmail; this.gemAuthorEmail = gemAuthorEmail;
} }
@Override
public boolean shouldOverwrite(String filename) {
// skip spec file as the file might have been updated with new test cases
return super.shouldOverwrite(filename) && !filename.endsWith("_spec.rb");
}
} }

View File

@@ -0,0 +1,281 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import java.io.File;
import java.util.*;
public class SpringBootServerCodegen extends JavaClientCodegen implements CodegenConfig{
public static final String CONFIG_PACKAGE = "configPackage";
public static final String BASE_PACKAGE = "basePackage";
protected String title = "Petstore Server";
protected String configPackage = "";
protected String basePackage = "";
protected String templateFileName = "api.mustache";
public SpringBootServerCodegen() {
super();
outputFolder = "generated-code/javaSpringBoot";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put(templateFileName, ".java");
embeddedTemplateDir = templateDir = "JavaSpringBoot";
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";
configPackage = "io.swagger.configuration";
invokerPackage = "io.swagger.api";
basePackage = "io.swagger";
artifactId = "swagger-springboot-server";
additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
additionalProperties.put("title", title);
additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage);
additionalProperties.put(CONFIG_PACKAGE, configPackage);
additionalProperties.put(BASE_PACKAGE, basePackage);
cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code"));
cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code"));
supportedLibraries.clear();
supportedLibraries.put(DEFAULT_LIBRARY, "Default Spring Boot server stub.");
supportedLibraries.put("j8-async", "Use async servlet feature and Java 8's default interface. Generating interface with service " +
"declaration is useful when using Maven plugin. Just provide a implementation with @Controller to instantiate service.");
}
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
@Override
public String getName() {
return "springboot";
}
@Override
public String getHelp() {
return "Generates a Java SpringBoot Server application using the SpringFox integration.";
}
@Override
public void processOpts() {
super.processOpts();
// clear model and api doc template as this codegen
// does not support auto-generated markdown doc at the moment
modelDocTemplateFiles.remove("model_doc.mustache");
apiDocTemplateFiles.remove("api_doc.mustache");
if (additionalProperties.containsKey(CONFIG_PACKAGE)) {
this.setConfigPackage((String) additionalProperties.get(CONFIG_PACKAGE));
}
if (additionalProperties.containsKey(BASE_PACKAGE)) {
this.setBasePackage((String) additionalProperties.get(BASE_PACKAGE));
}
supportingFiles.clear();
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("apiException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java"));
supportingFiles.add(new SupportingFile("apiOriginFilter.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java"));
supportingFiles.add(new SupportingFile("apiResponseMessage.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java"));
supportingFiles.add(new SupportingFile("notFoundException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java"));
supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java"));
supportingFiles.add(new SupportingFile("homeController.mustache",
(sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java"));
supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache",
(sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java"));
supportingFiles.add(new SupportingFile("application.properties",
("src.main.resources").replace(".", java.io.File.separator), "application.properties"));
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) {
String basePath = resourcePath;
if (basePath.startsWith("/")) {
basePath = basePath.substring(1);
}
int pos = basePath.indexOf("/");
if (pos > 0) {
basePath = basePath.substring(0, pos);
}
if (basePath == "") {
basePath = "default";
} else {
if (co.path.startsWith("/" + basePath)) {
co.path = co.path.substring(("/" + basePath).length());
}
co.subresourceOperation = !co.path.isEmpty();
}
List<CodegenOperation> opList = operations.get(basePath);
if (opList == null) {
opList = new ArrayList<CodegenOperation>();
operations.put(basePath, opList);
}
opList.add(co);
co.baseName = basePath;
}
@Override
public void preprocessSwagger(Swagger swagger) {
System.out.println("preprocessSwagger");
if ("/".equals(swagger.getBasePath())) {
swagger.setBasePath("");
}
String host = swagger.getHost();
String port = "8080";
if (host != null) {
String[] parts = host.split(":");
if (parts.length > 1) {
port = parts[1];
}
}
this.additionalProperties.put("serverPort", port);
if (swagger != null && swagger.getPaths() != null) {
for (String pathname : swagger.getPaths().keySet()) {
Path path = swagger.getPath(pathname);
if (path.getOperations() != null) {
for (Operation operation : path.getOperations()) {
if (operation.getTags() != null) {
List<Map<String, String>> tags = new ArrayList<Map<String, String>>();
for (String tag : operation.getTags()) {
Map<String, String> value = new HashMap<String, String>();
value.put("tag", tag);
value.put("hasMore", "true");
tags.add(value);
}
if (tags.size() > 0) {
tags.get(tags.size() - 1).remove("hasMore");
}
if (operation.getTags().size() > 0) {
String tag = operation.getTags().get(0);
operation.setTags(Arrays.asList(tag));
}
operation.setVendorExtension("x-tags", tags);
}
}
}
}
}
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
List<CodegenResponse> responses = operation.responses;
if (responses != null) {
for (CodegenResponse resp : responses) {
if ("0".equals(resp.code)) {
resp.code = "200";
}
}
}
if (operation.returnType == null) {
operation.returnType = "Void";
} else if (operation.returnType.startsWith("List")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("List<".length(), end).trim();
operation.returnContainer = "List";
}
} else if (operation.returnType.startsWith("Map")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Map<".length(), end).split(",")[1].trim();
operation.returnContainer = "Map";
}
} else if (operation.returnType.startsWith("Set")) {
String rt = operation.returnType;
int end = rt.lastIndexOf(">");
if (end > 0) {
operation.returnType = rt.substring("Set<".length(), end).trim();
operation.returnContainer = "Set";
}
}
}
}
if("j8-async".equals(getLibrary())) {
apiTemplateFiles.remove(this.templateFileName);
this.templateFileName = "api-j8-async.mustache";
apiTemplateFiles.put(this.templateFileName, ".java");
int originalPomFileIdx = -1;
for (int i = 0; i < supportingFiles.size(); i++) {
if ("pom.xml".equals(supportingFiles.get(i).destinationFilename)) {
originalPomFileIdx = i;
break;
}
}
if (originalPomFileIdx > -1) {
supportingFiles.remove(originalPomFileIdx);
}
supportingFiles.add(new SupportingFile("pom-j8-async.mustache", "", "pom.xml"));
}
return objs;
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "DefaultApi";
}
name = sanitizeName(name);
return camelize(name) + "Api";
}
public void setConfigPackage(String configPackage) {
this.configPackage = configPackage;
}
public void setBasePackage(String configPackage) {
this.basePackage = configPackage;
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// remove the import of "Object" to avoid compilation error
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
Iterator<Map<String, String>> iterator = imports.iterator();
while (iterator.hasNext()) {
String _import = iterator.next().get("import");
if (_import.endsWith(".Object")) iterator.remove();
}
List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
for (CodegenProperty var : cm.vars) {
// handle default value for enum, e.g. available => StatusEnum.available
if (var.isEnum && var.defaultValue != null && !"null".equals(var.defaultValue)) {
var.defaultValue = var.datatypeWithEnum + "." + var.defaultValue;
}
}
}
return objs;
}
}

View File

@@ -2,11 +2,12 @@ package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.*;
import io.swagger.models.Operation; import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import java.io.File; import java.io.File;
import java.util.*; import java.util.*;
public class SpringMVCServerCodegen extends JavaClientCodegen { public class SpringMVCServerCodegen extends JavaClientCodegen implements CodegenConfig{
public static final String CONFIG_PACKAGE = "configPackage"; public static final String CONFIG_PACKAGE = "configPackage";
protected String title = "Petstore Server"; protected String title = "Petstore Server";
protected String configPackage = ""; protected String configPackage = "";
@@ -120,6 +121,51 @@ public class SpringMVCServerCodegen extends JavaClientCodegen {
opList.add(co); opList.add(co);
co.baseName = basePath; co.baseName = basePath;
} }
@Override
public void preprocessSwagger(Swagger swagger) {
System.out.println("preprocessSwagger");
if ("/".equals(swagger.getBasePath())) {
swagger.setBasePath("");
}
String host = swagger.getHost();
String port = "8080";
if (host != null) {
String[] parts = host.split(":");
if (parts.length > 1) {
port = parts[1];
}
}
this.additionalProperties.put("serverPort", port);
if (swagger != null && swagger.getPaths() != null) {
for (String pathname : swagger.getPaths().keySet()) {
Path path = swagger.getPath(pathname);
if (path.getOperations() != null) {
for (Operation operation : path.getOperations()) {
if (operation.getTags() != null) {
List<Map<String, String>> tags = new ArrayList<Map<String, String>>();
for (String tag : operation.getTags()) {
Map<String, String> value = new HashMap<String, String>();
value.put("tag", tag);
value.put("hasMore", "true");
tags.add(value);
}
if (tags.size() > 0) {
tags.get(tags.size() - 1).remove("hasMore");
}
if (operation.getTags().size() > 0) {
String tag = operation.getTags().get(0);
operation.setTags(Arrays.asList(tag));
}
operation.setVendorExtension("x-tags", tags);
}
}
}
}
}
}
@Override @Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) { public Map<String, Object> postProcessOperations(Map<String, Object> objs) {

View File

@@ -335,8 +335,10 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
swiftEnums.add(map); swiftEnums.add(map);
} }
codegenProperty.allowableValues.put("values", swiftEnums); codegenProperty.allowableValues.put("values", swiftEnums);
codegenProperty.datatypeWithEnum = codegenProperty.datatypeWithEnum = toEnumName(codegenProperty);
StringUtils.left(codegenProperty.datatypeWithEnum, codegenProperty.datatypeWithEnum.length() - "Enum".length()); //codegenProperty.datatypeWithEnum =
// StringUtils.left(codegenProperty.datatypeWithEnum, codegenProperty.datatypeWithEnum.length() - "Enum".length());
// Ensure that the enum type doesn't match a reserved word or // Ensure that the enum type doesn't match a reserved word or
// the variable name doesn't match the generated enum type or the // the variable name doesn't match the generated enum type or the
// Swift compiler will generate an error // Swift compiler will generate an error
@@ -483,4 +485,59 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
public void setResponseAs(String[] responseAs) { public void setResponseAs(String[] responseAs) {
this.responseAs = responseAs; this.responseAs = responseAs;
} }
@Override
public String toEnumValue(String value, String datatype) {
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {
return value;
} else {
return "\'" + escapeText(value) + "\'";
}
}
@Override
public String toEnumDefaultValue(String value, String datatype) {
return datatype + "_" + value;
}
@Override
public String toEnumVarName(String name, String datatype) {
// number
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {
String varName = new String(name);
varName = varName.replaceAll("-", "MINUS_");
varName = varName.replaceAll("\\+", "PLUS_");
varName = varName.replaceAll("\\.", "_DOT_");
return varName;
}
// string
String enumName = sanitizeName(underscore(name).toUpperCase());
enumName = enumName.replaceFirst("^_", "");
enumName = enumName.replaceFirst("_$", "");
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
} else {
return enumName;
}
}
@Override
public String toEnumName(CodegenProperty property) {
String enumName = underscore(toModelName(property.name)).toUpperCase();
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
} else {
return enumName;
}
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// process enum in models
return postProcessModelsEnum(objs);
}
} }

View File

@@ -30,7 +30,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode
outputFolder = "generated-code/typescript-angular"; outputFolder = "generated-code/typescript-angular";
modelTemplateFiles.put("model.mustache", ".ts"); modelTemplateFiles.put("model.mustache", ".ts");
apiTemplateFiles.put("api.mustache", ".ts"); apiTemplateFiles.put("api.mustache", ".ts");
embeddedTemplateDir = templateDir = "TypeScript-Angular"; embeddedTemplateDir = templateDir = "typescript-angular";
apiPackage = "API.Client"; apiPackage = "API.Client";
modelPackage = "API.Client"; modelPackage = "API.Client";
} }

View File

@@ -0,0 +1,38 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.SupportingFile;
import java.io.File;
public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodegen {
@Override
public String getName() {
return "typescript-fetch";
}
@Override
public String getHelp() {
return "Generates a TypeScript client library using Fetch API (beta).";
}
@Override
public void processOpts() {
super.processOpts();
final String defaultFolder = apiPackage().replace('.', File.separatorChar);
supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("assign.ts", defaultFolder, "assign.ts"));
supportingFiles.add(new SupportingFile("package.json", "", "package.json"));
supportingFiles.add(new SupportingFile("typings.json", "", "typings.json"));
supportingFiles.add(new SupportingFile("tsconfig.json", "", "tsconfig.json"));
}
public TypeScriptFetchClientCodegen() {
super();
outputFolder = "generated-code/typescript-fetch";
embeddedTemplateDir = templateDir = "TypeScript-Fetch";
}
}

View File

@@ -1,8 +1,81 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.SupportingFile; import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.BooleanProperty;
public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen { public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptNodeClientCodegen.class);
private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm");
public static final String NPM_NAME = "npmName";
public static final String NPM_VERSION = "npmVersion";
public static final String NPM_REPOSITORY = "npmRepository";
public static final String SNAPSHOT = "snapshot";
protected String npmName = null;
protected String npmVersion = "1.0.0";
protected String npmRepository = null;
public TypeScriptNodeClientCodegen() {
super();
outputFolder = "generated-code/typescript-node";
embeddedTemplateDir = templateDir = "typescript-node";
this.cliOptions.add(new CliOption(NPM_NAME, "The name under which you want to publish generated npm package"));
this.cliOptions.add(new CliOption(NPM_VERSION, "The version of your npm package"));
this.cliOptions.add(new CliOption(NPM_REPOSITORY, "Use this property to set an url your private npmRepo in the package.json"));
this.cliOptions.add(new CliOption(SNAPSHOT, "When setting this property to true the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm", BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString()));
}
@Override
public void processOpts() {
super.processOpts();
supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
LOGGER.warn("check additionals: " + additionalProperties.get(NPM_NAME));
if(additionalProperties.containsKey(NPM_NAME)) {
addNpmPackageGeneration();
}
}
private void addNpmPackageGeneration() {
if(additionalProperties.containsKey(NPM_NAME)) {
this.setNpmName(additionalProperties.get(NPM_NAME).toString());
}
if (additionalProperties.containsKey(NPM_VERSION)) {
this.setNpmVersion(additionalProperties.get(NPM_VERSION).toString());
}
if (additionalProperties.containsKey(SNAPSHOT) && Boolean.valueOf(additionalProperties.get(SNAPSHOT).toString())) {
this.setNpmVersion(npmVersion + "-SNAPSHOT." + SNAPSHOT_SUFFIX_FORMAT.format(new Date()));
}
additionalProperties.put(NPM_VERSION, npmVersion);
if (additionalProperties.containsKey(NPM_REPOSITORY)) {
this.setNpmRepository(additionalProperties.get(NPM_REPOSITORY).toString());
}
//Files for building our lib
supportingFiles.add(new SupportingFile("package.mustache", getPackageRootDirectory(), "package.json"));
supportingFiles.add(new SupportingFile("typings.mustache", getPackageRootDirectory(), "typings.json"));
supportingFiles.add(new SupportingFile("tsconfig.mustache", getPackageRootDirectory(), "tsconfig.json"));
}
private String getPackageRootDirectory() {
String indexPackage = modelPackage.substring(0, Math.max(0, modelPackage.lastIndexOf('.')));
return indexPackage.replace('.', File.separatorChar);
}
@Override @Override
public String getName() { public String getName() {
@@ -14,18 +87,24 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen
return "Generates a TypeScript nodejs client library."; return "Generates a TypeScript nodejs client library.";
} }
@Override
public void processOpts() { public void setNpmName(String npmName) {
super.processOpts(); this.npmName = npmName;
supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
//supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
}
public TypeScriptNodeClientCodegen() {
super();
outputFolder = "generated-code/typescript-node";
embeddedTemplateDir = templateDir = "TypeScript-node";
} }
public void setNpmVersion(String npmVersion) {
this.npmVersion = npmVersion;
}
public String getNpmVersion() {
return npmVersion;
}
public String getNpmRepository() {
return npmRepository;
}
public void setNpmRepository(String npmRepository) {
this.npmRepository = npmRepository;
}
} }

View File

@@ -1,17 +0,0 @@
public enum {{{datatypeWithEnum}}} {
{{#allowableValues}}{{#enumVars}}{{{name}}}("{{{value}}}"){{^-last}},
{{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}}
private String value;
{{{datatypeWithEnum}}}(String value) {
this.value = value;
}
@Override
@JsonValue
public String toString() {
return value;
}
}

View File

@@ -1,3 +0,0 @@
public enum {{classname}} {
{{#allowableValues}}{{.}}{{^-last}}, {{/-last}}{{/allowableValues}}
}

View File

@@ -2,6 +2,6 @@
## Enum ## Enum
{{#allowableValues}} {{#allowableValues}}{{#enumVars}}
* `{{.}}` * `{{name}}` (value: `{{{value}}}`)
{{/allowableValues}} {{/enumVars}}{{/allowableValues}}

View File

@@ -0,0 +1,20 @@
/**
* {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}}
*/
public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} {
{{#allowableValues}}{{#enumVars}}@SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}})
{{{name}}}({{{value}}}){{^-last}},
{{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}}
private {{datatype}} value;
{{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{datatype}} value) {
this.value = value;
}
@Override
public String toString() {
return String.valueOf(value);
}
}

View File

@@ -1,17 +0,0 @@
public enum {{{datatypeWithEnum}}} {
{{#allowableValues}}{{#enumVars}}@SerializedName("{{{value}}}")
{{{name}}}("{{{value}}}"){{^-last}},
{{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}}
private String value;
{{{datatypeWithEnum}}}(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}

View File

@@ -3,5 +3,5 @@
## Enum ## Enum
{{#allowableValues}}{{#enumVars}} {{#allowableValues}}{{#enumVars}}
* `{{name}}` (value: `{{value}}`) * `{{name}}` (value: `{{{value}}}`)
{{#enumVars}}{{/allowableValues}} {{/enumVars}}{{/allowableValues}}

View File

@@ -8,78 +8,7 @@ import com.google.gson.annotations.SerializedName;
{{#serializableModel}}import java.io.Serializable;{{/serializableModel}} {{#serializableModel}}import java.io.Serializable;{{/serializableModel}}
{{#models}} {{#models}}
{{#model}}
{{#model}}{{#description}} {{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{>pojo}}{{/isEnum}}
/**
* {{description}}
**/{{/description}}
{{#description}}@ApiModel(description = "{{{description}}}"){{/description}}
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} {
{{#vars}}{{#isEnum}}
{{>libraries/okhttp-gson/enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}}
{{>libraries/okhttp-gson/enumClass}}{{/items}}{{/items.isEnum}}
@SerializedName("{{baseName}}")
private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};
{{/vars}}
{{#vars}}
/**{{#description}}
* {{{description}}}{{/description}}{{#minimum}}
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
* maximum: {{maximum}}{{/maximum}}
**/
@ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
public {{{datatypeWithEnum}}} {{getter}}() {
return {{name}};
}{{^isReadOnly}}
public void {{setter}}({{{datatypeWithEnum}}} {{name}}) {
this.{{name}} = {{name}};
}{{/isReadOnly}}
{{/vars}}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}{{#hasVars}}
{{classname}} {{classVarName}} = ({{classname}}) o;
return {{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{#hasMore}} &&
{{/hasMore}}{{/vars}}{{#parent}} &&
super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}}
return true;{{/hasVars}}
}
@Override
public int hashCode() {
return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}});
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class {{classname}} {\n");
{{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}}
{{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n");
{{/vars}}sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
{{/model}} {{/model}}
{{/models}} {{/models}}

View File

@@ -0,0 +1,20 @@
/**
* {{^description}}Gets or Sets {{name}}{{/description}}{{#description}}{{description}}{{/description}}
*/
public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} {
{{#allowableValues}}{{#enumVars}}@SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}})
{{{name}}}({{{value}}}){{^-last}},
{{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}}
private {{dataType}} value;
{{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{dataType}} value) {
this.value = value;
}
@Override
public String toString() {
return String.valueOf(value);
}
}

View File

@@ -0,0 +1,20 @@
/**
* {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}}
*/
public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} {
{{#allowableValues}}{{#enumVars}}@SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}})
{{{name}}}({{{value}}}){{^-last}},
{{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}}
private {{datatype}} value;
{{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{datatype}} value) {
this.value = value;
}
@Override
public String toString() {
return String.valueOf(value);
}
}

View File

@@ -0,0 +1,71 @@
/**
* {{#description}}{{description}}{{/description}}{{^description}}{{classname}}{{/description}}
*/{{#description}}
@ApiModel(description = "{{{description}}}"){{/description}}
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} {
{{#vars}}{{#isEnum}}
{{>libraries/common/modelInnerEnum}}{{/isEnum}}{{#items.isEnum}}{{#items}}
{{>libraries/common/modelInnerEnum}}{{/items}}{{/items.isEnum}}
@SerializedName("{{baseName}}")
private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};
{{/vars}}
{{#vars}}
/**{{#description}}
* {{{description}}}{{/description}}{{#minimum}}
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
* maximum: {{maximum}}{{/maximum}}
**/
@ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
public {{{datatypeWithEnum}}} {{getter}}() {
return {{name}};
}{{^isReadOnly}}
public void {{setter}}({{{datatypeWithEnum}}} {{name}}) {
this.{{name}} = {{name}};
}{{/isReadOnly}}
{{/vars}}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}{{#hasVars}}
{{classname}} {{classVarName}} = ({{classname}}) o;
return {{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{#hasMore}} &&
{{/hasMore}}{{/vars}}{{#parent}} &&
super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}}
return true;{{/hasVars}}
}
@Override
public int hashCode() {
return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}});
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class {{classname}} {\n");
{{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}}
{{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n");
{{/vars}}sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}

View File

@@ -17,9 +17,9 @@ import com.google.gson.annotations.SerializedName;
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} {
{{#vars}}{{#isEnum}} {{#vars}}{{#isEnum}}
{{>libraries/okhttp-gson/enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} {{>libraries/common/modelInnerEnum}}{{/isEnum}}{{#items.isEnum}}{{#items}}
{{>libraries/okhttp-gson/enumClass}}{{/items}}{{/items.isEnum}} {{>libraries/common/modelInnerEnum}}{{/items}}{{/items.isEnum}}
@SerializedName("{{baseName}}") @SerializedName("{{baseName}}")
private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}}; private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};
{{/vars}} {{/vars}}

View File

@@ -95,8 +95,7 @@ if(hasProperty('target') && target == 'android') {
ext { ext {
oltu_version = "1.0.1" oltu_version = "1.0.1"
retrofit_version = "2.0.0-beta4" retrofit_version = "2.0.2"
gson_version = "2.6.2"
swagger_annotations_version = "1.5.8" swagger_annotations_version = "1.5.8"
junit_version = "4.12" junit_version = "4.12"
{{#useRxJava}} {{#useRxJava}}

View File

@@ -17,9 +17,9 @@ import com.google.gson.annotations.SerializedName;
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} {
{{#vars}}{{#isEnum}} {{#vars}}{{#isEnum}}
{{>libraries/okhttp-gson/enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} {{>libraries/common/modelInnerEnum}}{{/isEnum}}{{#items.isEnum}}{{#items}}
{{>libraries/okhttp-gson/enumClass}}{{/items}}{{/items.isEnum}} {{>libraries/common/modelInnerEnum}}{{/items}}{{/items.isEnum}}
@SerializedName("{{baseName}}") @SerializedName("{{baseName}}")
private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}}; private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};
{{/vars}} {{/vars}}

View File

@@ -112,6 +112,11 @@
<artifactId>swagger-annotations</artifactId> <artifactId>swagger-annotations</artifactId>
<version>${swagger-core-version}</version> <version>${swagger-core-version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version>${retrofit-version}</version>
</dependency>
<dependency> <dependency>
<groupId>com.squareup.retrofit2</groupId> <groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId> <artifactId>retrofit</artifactId>
@@ -122,11 +127,6 @@
<artifactId>converter-scalars</artifactId> <artifactId>converter-scalars</artifactId>
<version>${retrofit-version}</version> <version>${retrofit-version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version>${retrofit-version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.apache.oltu.oauth2</groupId> <groupId>org.apache.oltu.oauth2</groupId>
<artifactId>org.apache.oltu.oauth2.client</artifactId> <artifactId>org.apache.oltu.oauth2.client</artifactId>
@@ -153,8 +153,9 @@
</dependencies> </dependencies>
<properties> <properties>
<swagger-core-version>1.5.8</swagger-core-version> <swagger-core-version>1.5.8</swagger-core-version>
<retrofit-version>2.0.0-beta4</retrofit-version>{{#useRxJava}} <retrofit-version>2.0.2</retrofit-version>
<rxjava-version>1.1.3</rxjava-version>{{/useRxJava}} {{#useRxJava}}<rxjava-version>1.1.3</rxjava-version>{{/useRxJava}}
<okhttp-version>3.2.0</okhttp-version>
<oltu-version>1.0.1</oltu-version> <oltu-version>1.0.1</oltu-version>
<maven-plugin-version>1.0.0</maven-plugin-version> <maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.12</junit-version> <junit-version>4.12</junit-version>

View File

@@ -6,11 +6,7 @@ import java.util.Objects;
{{#serializableModel}}import java.io.Serializable;{{/serializableModel}} {{#serializableModel}}import java.io.Serializable;{{/serializableModel}}
{{#models}} {{#models}}
{{#model}}{{#description}} {{#model}}
/** {{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{>pojo}}{{/isEnum}}
* {{description}}
**/{{/description}}
{{#isEnum}}{{>enumOuterClass}}{{/isEnum}}
{{^isEnum}}{{>pojo}}{{/isEnum}}
{{/model}} {{/model}}
{{/models}} {{/models}}

View File

@@ -0,0 +1,19 @@
/**
* {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}}
*/
public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} {
{{#allowableValues}}{{#enumVars}}{{{name}}}({{{value}}}){{^-last}},
{{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}}
private {{dataType}} value;
{{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{dataType}} value) {
this.value = value;
}
@Override
@JsonValue
public String toString() {
return String.valueOf(value);
}
}

View File

@@ -0,0 +1,19 @@
/**
* {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}}
*/
public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} {
{{#allowableValues}}{{#enumVars}}{{{name}}}({{{value}}}){{^-last}},
{{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}}
private {{datatype}} value;
{{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{datatype}} value) {
this.value = value;
}
@Override
@JsonValue
public String toString() {
return String.valueOf(value);
}
}

View File

@@ -1,11 +1,14 @@
{{#description}}@ApiModel(description = "{{{description}}}"){{/description}} /**
* {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}}
*/{{#description}}
@ApiModel(description = "{{{description}}}"){{/description}}
{{>generatedAnnotation}} {{>generatedAnnotation}}
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} {
{{#vars}}{{#isEnum}} {{#vars}}{{#isEnum}}
{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} {{>modelInnerEnum}}{{/isEnum}}{{#items.isEnum}}{{#items}}
{{>enumClass}}{{/items}}{{/items.isEnum}} {{>modelInnerEnum}}{{/items}}{{/items.isEnum}}
private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}}
{{#vars}}{{^isReadOnly}} {{#vars}}{{^isReadOnly}}

View File

@@ -1,17 +1,24 @@
/**
* {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}}
*/
public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} {
{{#allowableValues}}
{{#enumVars}}
{{{name}}}({{{value}}}){{^-last}},
public enum {{{datatypeWithEnum}}} { {{/-last}}{{#-last}};
{{#allowableValues}}{{#enumVars}}{{{name}}}("{{{value}}}"){{^-last}}, {{/-last}}
{{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} {{/enumVars}}
{{/allowableValues}}
private {{datatype}} value;
private String value; {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{datatype}} value) {
{{{datatypeWithEnum}}}(String value) {
this.value = value; this.value = value;
} }
@Override @Override
@JsonValue @JsonValue
public String toString() { public String toString() {
return value; return String.valueOf(value);
} }
} }

View File

@@ -1,17 +1,24 @@
/**
* {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}}
*/
public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} {
{{#allowableValues}}
{{#enumVars}}
{{{name}}}({{{value}}}){{^-last}},
public enum {{{datatypeWithEnum}}} { {{/-last}}{{#-last}};
{{#allowableValues}}{{#enumVars}}{{{name}}}("{{{value}}}"){{^-last}}, {{/-last}}
{{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} {{/enumVars}}
{{/allowableValues}}
private {{datatype}} value;
private String value; {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{datatype}} value) {
{{{datatypeWithEnum}}}(String value) {
this.value = value; this.value = value;
} }
@Override @Override
@JsonValue @JsonValue
public String toString() { public String toString() {
return value; return String.valueOf(value);
} }
} }

View File

@@ -0,0 +1,18 @@
# Swagger generated server
Spring Boot Server
## Overview
This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project.
By using the [OpenAPI-Spec](https://github.com/swagger-api/swagger-core), you can easily generate a server stub.
This is an example of building a swagger-enabled server in Java using the SpringBoot framework.
The underlying library integrating swagger to SpringBoot is [springfox](https://github.com/springfox/springfox)
Start your server as an simple java application
You can view the api documentation in swagger-ui by pointing to
http://localhost:8080/
Change default port value in application.properties

View File

@@ -0,0 +1,56 @@
package {{apiPackage}};
import {{modelPackage}}.*;
{{#imports}}import {{import}};
{{/imports}}
import io.swagger.annotations.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import static org.springframework.http.MediaType.*;
@Controller
@RequestMapping(value = "/{{{baseName}}}", produces = {APPLICATION_JSON_VALUE})
@Api(value = "/{{{baseName}}}", description = "the {{{baseName}}} API")
{{>generatedAnnotation}}
{{#operations}}
public class {{classname}} {
{{#operation}}
@ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = {
{{#authMethods}}@Authorization(value = "{{name}}"{{#isOAuth}}, scopes = {
{{#scopes}}@AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{#hasMore}},
{{/hasMore}}{{/scopes}}
}{{/isOAuth}}){{#hasMore}},
{{/hasMore}}{{/authMethods}}
}{{/hasAuthMethods}})
@ApiResponses(value = { {{#responses}}
@ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class){{#hasMore}},{{/hasMore}}{{/responses}} })
@RequestMapping(value = "{{{path}}}",
{{#hasProduces}}produces = { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}}
{{#hasConsumes}}consumes = { {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}}
method = RequestMethod.{{httpMethod}})
public ResponseEntity<{{>returnTypes}}> {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},
{{/hasMore}}{{/allParams}})
throws NotFoundException {
// do some magic!
return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK);
}
{{/operation}}
}
{{/operations}}

View File

@@ -0,0 +1,10 @@
package {{apiPackage}};
{{>generatedAnnotation}}
public class ApiException extends Exception{
private int code;
public ApiException (int code, String msg) {
super(msg);
this.code = code;
}
}

View File

@@ -0,0 +1,27 @@
package {{apiPackage}};
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
{{>generatedAnnotation}}
public class ApiOriginFilter implements javax.servlet.Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.addHeader("Access-Control-Allow-Headers", "Content-Type");
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}

View File

@@ -0,0 +1,69 @@
package {{apiPackage}};
import javax.xml.bind.annotation.XmlTransient;
@javax.xml.bind.annotation.XmlRootElement
{{>generatedAnnotation}}
public class ApiResponseMessage {
public static final int ERROR = 1;
public static final int WARNING = 2;
public static final int INFO = 3;
public static final int OK = 4;
public static final int TOO_BUSY = 5;
int code;
String type;
String message;
public ApiResponseMessage(){}
public ApiResponseMessage(int code, String message){
this.code = code;
switch(code){
case ERROR:
setType("error");
break;
case WARNING:
setType("warning");
break;
case INFO:
setType("info");
break;
case OK:
setType("ok");
break;
case TOO_BUSY:
setType("too busy");
break;
default:
setType("unknown");
break;
}
this.message = message;
}
@XmlTransient
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

View File

@@ -0,0 +1,2 @@
springfox.documentation.swagger.v2.path=/api-docs
#server.port=8090

View File

@@ -0,0 +1 @@
{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestBody {{{dataType}}} {{paramName}}{{/isBodyParam}}

View File

@@ -0,0 +1,2 @@
{{#isFormParam}}{{#notFile}}
@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestPart(value="{{paramName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile {{baseName}}{{/isFile}}{{/isFormParam}}

View File

@@ -0,0 +1 @@
@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}")

View File

@@ -0,0 +1 @@
{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestHeader(value="{{baseName}}", required={{#required}}true{{/required}}{{^required}}false{{/required}}) {{{dataType}}} {{paramName}}{{/isHeaderParam}}

View File

@@ -0,0 +1,16 @@
package {{configPackage}};
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Home redirection to swagger api documentation
*/
@Controller
public class HomeController {
@RequestMapping(value = "/")
public String index() {
System.out.println("swagger-ui.html");
return "redirect:swagger-ui.html";
}
}

View File

@@ -0,0 +1,77 @@
package {{package}};
{{#imports}}import {{import}};
{{/imports}}
import io.swagger.annotations.*;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
{{#models}}
{{#model}}{{#description}}
/**
* {{description}}
**/{{/description}}
@ApiModel(description = "{{{description}}}")
{{>generatedAnnotation}}
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
{{#vars}}{{#isEnum}}
public enum {{datatypeWithEnum}} {
{{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}}
};
{{/isEnum}}{{#items}}{{#isEnum}}
public enum {{datatypeWithEnum}} {
{{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}}
};
{{/isEnum}}{{/items}}
private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}}
{{#vars}}
/**{{#description}}
* {{{description}}}{{/description}}{{#minimum}}
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
* maximum: {{maximum}}{{/maximum}}
**/
@ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
@JsonProperty("{{baseName}}")
public {{{datatypeWithEnum}}} {{getter}}() {
return {{name}};
}
public void {{setter}}({{{datatypeWithEnum}}} {{name}}) {
this.{{name}} = {{name}};
}
{{/vars}}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
{{classname}} {{classVarName}} = ({{classname}}) o;{{#hasVars}}
return {{#vars}}Objects.equals({{name}}, {{classVarName}}.{{name}}){{#hasMore}} &&
{{/hasMore}}{{^hasMore}};{{/hasMore}}{{/vars}}{{/hasVars}}{{^hasVars}}
return true;{{/hasVars}}
}
@Override
public int hashCode() {
return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}});
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class {{classname}} {\n");
{{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}}
{{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n");
{{/vars}}sb.append("}\n");
return sb.toString();
}
}
{{/model}}
{{/models}}

View File

@@ -0,0 +1,10 @@
package {{apiPackage}};
{{>generatedAnnotation}}
public class NotFoundException extends ApiException {
private int code;
public NotFoundException (int code, String msg) {
super(code, msg);
this.code = code;
}
}

View File

@@ -0,0 +1 @@
{{#isPathParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}} {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathVariable("{{paramName}}") {{{dataType}}} {{paramName}}{{/isPathParam}}

View File

@@ -0,0 +1,54 @@
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>{{groupId}}</groupId>
<artifactId>{{artifactId}}</artifactId>
<packaging>jar</packaging>
<name>{{artifactId}}</name>
<version>{{artifactVersion}}</version>
<properties>
<springfox-version>2.4.0</springfox-version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
</parent>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!--SpringFox dependencies -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox-version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${springfox-version}</version>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1 @@
sbt.version=0.12.0

View File

@@ -0,0 +1,9 @@
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.8.4")
libraryDependencies <+= sbtVersion(v => v match {
case "0.11.0" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.0-0.2.8"
case "0.11.1" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.1-0.2.10"
case "0.11.2" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.2-0.2.11"
case "0.11.3" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.3-0.2.11.1"
case x if (x.startsWith("0.12")) => "com.github.siasia" %% "xsbt-web-plugin" % "0.12.0-0.2.11.1"
})

View File

@@ -0,0 +1 @@
{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value = "{{paramName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isQueryParam}}

View File

@@ -0,0 +1 @@
{{#returnContainer}}{{#isMapContainer}}Map<String, {{{returnType}}}>{{/isMapContainer}}{{#isListContainer}}List<{{{returnType}}}>{{/isListContainer}}{{/returnContainer}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}}

View File

@@ -0,0 +1,36 @@
package {{basePackage}};
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
@ComponentScan(basePackages = "{{basePackage}}")
public class Swagger2SpringBoot implements CommandLineRunner {
@Override
public void run(String... arg0) throws Exception {
if (arg0.length > 0 && arg0[0].equals("exitcode")) {
throw new ExitException();
}
}
public static void main(String[] args) throws Exception {
new SpringApplication(Swagger2SpringBoot.class).run(args);
}
class ExitException extends RuntimeException implements ExitCodeGenerator {
private static final long serialVersionUID = 1L;
@Override
public int getExitCode() {
return 10;
}
}
}

View File

@@ -0,0 +1,40 @@
package {{configPackage}};
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
{{>generatedAnnotation}}
public class SwaggerDocumentationConfig {
ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("{{appName}}")
.description("{{{appDescription}}}")
.license("{{licenseInfo}}")
.licenseUrl("{{licenseUrl}}")
.termsOfServiceUrl("{{infoUrl}}")
.version("{{appVersion}}")
.contact(new Contact("","", "{{infoEmail}}"))
.build();
}
@Bean
public Docket customImplementation(){
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("{{apiPackage}}"))
.build()
.apiInfo(apiInfo());
}
}

View File

@@ -11,7 +11,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId> <artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version> <version>2.6</version>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-failsafe-plugin</artifactId> <artifactId>maven-failsafe-plugin</artifactId>
@@ -119,12 +119,12 @@
</dependencies> </dependencies>
<properties> <properties>
<swagger-core-version>1.5.8</swagger-core-version> <swagger-core-version>1.5.8</swagger-core-version>
<jetty-version>9.2.9.v20150224</jetty-version> <jetty-version>9.2.15.v20160210</jetty-version>
<jersey-version>1.13</jersey-version> <jersey-version>1.13</jersey-version>
<slf4j-version>1.6.3</slf4j-version> <slf4j-version>1.7.21</slf4j-version>
<junit-version>4.8.1</junit-version> <junit-version>4.12</junit-version>
<servlet-api-version>2.5</servlet-api-version> <servlet-api-version>2.5</servlet-api-version>
<springfox-version>2.3.1</springfox-version> <springfox-version>2.4.0</springfox-version>
<spring-version>4.1.8.RELEASE</spring-version> <spring-version>4.2.5.RELEASE</spring-version>
</properties> </properties>
</project> </project>

View File

@@ -6,7 +6,9 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo; import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; import springfox.documentation.swagger2.annotations.EnableSwagger2;
@@ -22,15 +24,15 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2;
public class SwaggerConfig { public class SwaggerConfig {
@Bean @Bean
ApiInfo apiInfo() { ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo( return new ApiInfoBuilder()
"{{appName}}", .title("{{appName}}")
"{{{appDescription}}}", .description("{{{appDescription}}}")
"{{appVersion}}", .license("{{licenseInfo}}")
"{{infoUrl}}", .licenseUrl("{{licenseUrl}}")
"{{infoEmail}}", .termsOfServiceUrl("{{infoUrl}}")
"{{licenseInfo}}", .version("{{appVersion}}")
"{{licenseUrl}}" ); .contact(new Contact("","", "{{infoEmail}}"))
return apiInfo; .build();
} }
@Bean @Bean
@@ -38,4 +40,4 @@ public class SwaggerConfig {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()); return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
} }
} }

View File

@@ -47,8 +47,8 @@ goog.require('{{import}}');
/** @private {!angular.$http} */ /** @private {!angular.$http} */
this.http_ = $http; this.http_ = $http;
/** @private {!Object} */ /** @package {!Object} */
this.httpParamSerializer_ = $injector.get('$httpParamSerializer'); this.httpParamSerializer = $injector.get('$httpParamSerializer');
} }
{{package}}.{{classname}}.$inject = ['$http', '$httpParamSerializer', '$injector']; {{package}}.{{classname}}.$inject = ['$http', '$httpParamSerializer', '$injector'];
{{#operation}} {{#operation}}
@@ -69,7 +69,7 @@ goog.require('{{import}}');
var queryParameters = {}; var queryParameters = {};
/** @type {!Object} */ /** @type {!Object} */
var headerParams = angular.extend({}, this.defaultHeaders); var headerParams = angular.extend({}, this.defaultHeaders_);
{{#hasFormParams}} {{#hasFormParams}}
/** @type {!Object} */ /** @type {!Object} */
var formParams = {}; var formParams = {};
@@ -108,7 +108,7 @@ goog.require('{{import}}');
json: {{#hasFormParams}}false{{/hasFormParams}}{{^hasFormParams}}true{{/hasFormParams}}, json: {{#hasFormParams}}false{{/hasFormParams}}{{^hasFormParams}}true{{/hasFormParams}},
{{#bodyParam}}data: {{^required}}opt_{{/required}}{{paramName}}, {{#bodyParam}}data: {{^required}}opt_{{/required}}{{paramName}},
{{/bodyParam}} {{/bodyParam}}
{{#hasFormParams}}data: this.httpParamSerializer_(formParams), {{#hasFormParams}}data: this.httpParamSerializer(formParams),
{{/hasFormParams}} {{/hasFormParams}}
params: queryParameters, params: queryParameters,
headers: headerParams headers: headerParams
@@ -118,7 +118,7 @@ goog.require('{{import}}');
httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams); httpRequestParams = angular.extend(httpRequestParams, opt_extraHttpRequestParams);
} }
return this.http_(httpRequestParams); return (/** @type {?} */ (this.http_))(httpRequestParams);
} }
{{/operation}} {{/operation}}
{{/operations}} {{/operations}}

View File

@@ -16,7 +16,7 @@
'use strict'; 'use strict';
{{#emitJSDoc}} /** {{#emitJSDoc}} /**
* @module ApiClient * @module {{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient
* @version {{projectVersion}} * @version {{projectVersion}}
*/ */
@@ -24,7 +24,7 @@
* Manages low level client-server communications, parameter marshalling, etc. There should not be any need for an * Manages low level client-server communications, parameter marshalling, etc. There should not be any need for an
* application to use this class directly - the *Api and model classes provide the public API for the service. The * application to use this class directly - the *Api and model classes provide the public API for the service. The
* contents of this file should be regarded as internal but are documented for completeness. * contents of this file should be regarded as internal but are documented for completeness.
* @alias module:ApiClient * @alias module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient
* @class * @class
*/ */
{{/emitJSDoc}} var exports = function() { {{/emitJSDoc}} var exports = function() {
@@ -218,7 +218,7 @@
/** /**
* Builds a string representation of an array-type actual parameter, according to the given collection format. * Builds a string representation of an array-type actual parameter, according to the given collection format.
* @param {Array} param An array parameter. * @param {Array} param An array parameter.
* @param {module:ApiClient.CollectionFormatEnum} collectionFormat The array element separator strategy. * @param {module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient.CollectionFormatEnum} collectionFormat The array element separator strategy.
* @returns {String|Array} A string representation of the supplied collection, using the specified delimiter. Returns * @returns {String|Array} A string representation of the supplied collection, using the specified delimiter. Returns
* <code>param</code> as is if <code>collectionFormat</code> is <code>multi</code>. * <code>param</code> as is if <code>collectionFormat</code> is <code>multi</code>.
*/ */
@@ -309,7 +309,7 @@
{{#emitJSDoc}}{{^usePromises}} /** {{#emitJSDoc}}{{^usePromises}} /**
* Callback function to receive the result of the operation. * Callback function to receive the result of the operation.
* @callback module:ApiClient~callApiCallback * @callback module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient~callApiCallback
* @param {String} error Error message, if any. * @param {String} error Error message, if any.
* @param data The data returned by the service call. * @param data The data returned by the service call.
* @param {String} response The complete HTTP response. * @param {String} response The complete HTTP response.
@@ -329,7 +329,7 @@
* @param {Array.<String>} accepts An array of acceptable response MIME types. * @param {Array.<String>} accepts An array of acceptable response MIME types.
* @param {(String|Array|ObjectFunction)} returnType The required type to return; can be a string for simple types or the * @param {(String|Array|ObjectFunction)} returnType The required type to return; can be a string for simple types or the
* constructor for a complex type.{{^usePromises}} * constructor for a complex type.{{^usePromises}}
* @param {module:ApiClient~callApiCallback} callback The callback function. * @param {module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient~callApiCallback} callback The callback function.
{{/usePromises}} * @returns {{#usePromises}}{Promise} A Promise object{{/usePromises}}{{^usePromises}}{Object} The SuperAgent request object{{/usePromises}}. {{/usePromises}} * @returns {{#usePromises}}{Promise} A Promise object{{/usePromises}}{{^usePromises}}{Object} The SuperAgent request object{{/usePromises}}.
*/ */
{{/emitJSDoc}} exports.prototype.callApi = function callApi(path, httpMethod, pathParams, {{/emitJSDoc}} exports.prototype.callApi = function callApi(path, httpMethod, pathParams,
@@ -474,9 +474,28 @@
} }
}; };
{{#emitJSDoc}} /**
* Constructs a new map or array model from REST data.
* @param data {Object|Array} The REST data.
* @param obj {Object|Array} The target object or array.
*/
{{/emitJSDoc}} exports.constructFromObject = function(data, obj, itemType) {
if (Array.isArray(data)) {
for (var i = 0; i < data.length; i++) {
if (data.hasOwnProperty(i))
obj[i] = exports.convertToType(data[i], itemType);
}
} else {
for (var k in data) {
if (data.hasOwnProperty(k))
result[k] = exports.convertToType(data[k], itemType);
}
}
};
{{#emitJSDoc}} /** {{#emitJSDoc}} /**
* The default API client implementation. * The default API client implementation.
* @type {module:ApiClient} * @type {module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient}
*/ */
{{/emitJSDoc}} exports.instance = new exports(); {{/emitJSDoc}} exports.instance = new exports();

View File

@@ -32,11 +32,11 @@ npm install {{{projectName}}} --save
#### git #### git
# #
If the library is hosted at a git repository, e.g. If the library is hosted at a git repository, e.g.
https://github.com/{{#gitUserName}}{{.}}{{/gitUserName}}{{^gitUserName}}YOUR_USERNAME{{/gitUserName}}/{{#gitRepoId}}{{.}}{{/gitRepoId}}{{^gitRepoId}}{{projectName}}{{/gitRepoId}} https://github.com/{{#gitUserId}}{{.}}{{/gitUserId}}{{^gitUserId}}YOUR_USERNAME{{/gitUserId}}/{{#gitRepoId}}{{.}}{{/gitRepoId}}{{^gitRepoId}}{{projectName}}{{/gitRepoId}}
then install it via: then install it via:
```shell ```shell
npm install {{#gitUserName}}{{.}}{{/gitUserName}}{{^gitUserName}}YOUR_USERNAME{{/gitUserName}}/{{#gitRepoId}}{{.}}{{/gitRepoId}}{{^gitRepoId}}{{projectName}}{{/gitRepoId}} --save npm install {{#gitUserId}}{{.}}{{/gitUserId}}{{^gitUserId}}YOUR_USERNAME{{/gitUserId}}/{{#gitRepoId}}{{.}}{{/gitRepoId}}{{^gitRepoId}}{{projectName}}{{/gitRepoId}} --save
``` ```
### For browser ### For browser

View File

@@ -1,7 +1,7 @@
{{=< >=}}(function(root, factory) { {{=< >=}}(function(root, factory) {
if (typeof define === 'function' && define.amd) { if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module. // AMD. Register as an anonymous module.
define(['../ApiClient'<#imports>, '../<#modelPackage><modelPackage>/</modelPackage><import>'</imports>], factory); define(['<#invokerPackage><invokerPackage>/</invokerPackage>ApiClient'<#imports>, '<#invokerPackage><invokerPackage>/</invokerPackage><#modelPackage><modelPackage>/</modelPackage><import>'</imports>], factory);
} else if (typeof module === 'object' && module.exports) { } else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node. // CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient')<#imports>, require('../<#modelPackage><modelPackage>/</modelPackage><import>')</imports>); module.exports = factory(require('../ApiClient')<#imports>, require('../<#modelPackage><modelPackage>/</modelPackage><import>')</imports>);
@@ -17,17 +17,17 @@
<#emitJSDoc> /** <#emitJSDoc> /**
* <baseName> service. * <baseName> service.
* @module <#apiPackage><apiPackage>/</apiPackage><classname> * @module <#invokerPackage><invokerPackage>/</invokerPackage><#apiPackage><apiPackage>/</apiPackage><classname>
* @version <projectVersion> * @version <projectVersion>
*/ */
/** /**
* Constructs a new <classname>. <#description> * Constructs a new <classname>. <#description>
* <description></description> * <description></description>
* @alias module:<#apiPackage><apiPackage>/</apiPackage><classname> * @alias module:<#invokerPackage><invokerPackage>/</invokerPackage><#apiPackage><apiPackage>/</apiPackage><classname>
* @class * @class
* @param {module:ApiClient} apiClient Optional API client implementation to use, default to {@link module:ApiClient#instance} * @param {module:<#invokerPackage><invokerPackage>/</invokerPackage>ApiClient} apiClient Optional API client implementation to use,
* if unspecified. * default to {@link module:<#invokerPackage><invokerPackage>/</invokerPackage>ApiClient#instance} if unspecified.
*/ */
</emitJSDoc> var exports = function(apiClient) { </emitJSDoc> var exports = function(apiClient) {
this.apiClient = apiClient || ApiClient.instance; this.apiClient = apiClient || ApiClient.instance;
@@ -35,7 +35,7 @@
<#operations><#operation><#emitJSDoc><^usePromises> <#operations><#operation><#emitJSDoc><^usePromises>
/** /**
* Callback function to receive the result of the <nickname> operation. * Callback function to receive the result of the <nickname> operation.
* @callback module:<#apiPackage><apiPackage>/</apiPackage><classname>~<nickname>Callback * @callback module:<#invokerPackage><invokerPackage>/</invokerPackage><#apiPackage><apiPackage>/</apiPackage><classname>~<nickname>Callback
* @param {String} error Error message, if any. * @param {String} error Error message, if any.
* @param <#vendorExtensions.x-jsdoc-type><&vendorExtensions.x-jsdoc-type> data The data returned by the service call.</vendorExtensions.x-jsdoc-type><^vendorExtensions.x-jsdoc-type>data This operation does not return a value.</vendorExtensions.x-jsdoc-type> * @param <#vendorExtensions.x-jsdoc-type><&vendorExtensions.x-jsdoc-type> data The data returned by the service call.</vendorExtensions.x-jsdoc-type><^vendorExtensions.x-jsdoc-type>data This operation does not return a value.</vendorExtensions.x-jsdoc-type>
* @param {String} response The complete HTTP response. * @param {String} response The complete HTTP response.
@@ -47,7 +47,7 @@
* @param <&vendorExtensions.x-jsdoc-type> <paramName> <description></required></allParams><#hasOptionalParams> * @param <&vendorExtensions.x-jsdoc-type> <paramName> <description></required></allParams><#hasOptionalParams>
* @param {Object} opts Optional parameters<#allParams><^required> * @param {Object} opts Optional parameters<#allParams><^required>
* @param <&vendorExtensions.x-jsdoc-type> opts.<paramName> <description><#defaultValue> (default to <.>)</defaultValue></required></allParams></hasOptionalParams><^usePromises> * @param <&vendorExtensions.x-jsdoc-type> opts.<paramName> <description><#defaultValue> (default to <.>)</defaultValue></required></allParams></hasOptionalParams><^usePromises>
* @param {module:<#apiPackage><apiPackage>/</apiPackage><classname>~<nickname>Callback} callback The callback function, accepting three arguments: error, data, response</usePromises><#returnType> * @param {module:<#invokerPackage><invokerPackage>/</invokerPackage><#apiPackage><apiPackage>/</apiPackage><classname>~<nickname>Callback} callback The callback function, accepting three arguments: error, data, response</usePromises><#returnType>
* data is of type: <&vendorExtensions.x-jsdoc-type></returnType> * data is of type: <&vendorExtensions.x-jsdoc-type></returnType>
*/ */
</emitJSDoc> this.<nickname> = function(<vendorExtensions.x-codegen-argList>) {<#hasOptionalParams> </emitJSDoc> this.<nickname> = function(<vendorExtensions.x-codegen-argList>) {<#hasOptionalParams>

View File

@@ -3,11 +3,17 @@
* @enum {{=<% %>=}}{<%datatype%>}<%={{ }}=%> * @enum {{=<% %>=}}{<%datatype%>}<%={{ }}=%>
* @readonly * @readonly
*/{{/emitJSDoc}} */{{/emitJSDoc}}
exports.{{datatypeWithEnum}} = { {{#allowableValues}}{{#enumVars}} exports.{{datatypeWithEnum}} = {
{{#emitJSDoc}} /** {{#allowableValues}}
* value: {{value}} {{#enumVars}}
{{#emitJSDoc}}
/**
* value: {{{value}}}
* @const * @const
*/ */
{{/emitJSDoc}} {{name}}: "{{value}}"{{^-last}}, {{/emitJSDoc}}
{{/-last}}{{/enumVars}}{{/allowableValues}} "{{name}}": {{{value}}}{{^-last}},
}; {{/-last}}
{{/enumVars}}
{{/allowableValues}}
};

View File

@@ -36,7 +36,7 @@ git_remote=`git remote`
if [ "$git_remote" = "" ]; then # git remote not defined if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the Git credential in your environment."
git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git
else else
git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git

View File

@@ -1,7 +1,7 @@
(function(factory) { (function(factory) {
if (typeof define === 'function' && define.amd) { if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module. // AMD. Register as an anonymous module.
define(['./ApiClient'{{#models}}, './{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{importPath}}'{{/models}}{{#apiInfo}}{{#apis}}, './{{#apiPackage}}{{apiPackage}}/{{/apiPackage}}{{importPath}}'{{/apis}}{{/apiInfo}}], factory); define(['{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient'{{#models}}, '{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{importPath}}'{{/models}}{{#apiInfo}}{{#apis}}, '{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}{{#apiPackage}}{{apiPackage}}/{{/apiPackage}}{{importPath}}'{{/apis}}{{/apiInfo}}], factory);
} else if (typeof module === 'object' && module.exports) { } else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node. // CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('./ApiClient'){{#models}}, require('./{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{importPath}}'){{/models}}{{#apiInfo}}{{#apis}}, require('./{{#apiPackage}}{{apiPackage}}/{{/apiPackage}}{{importPath}}'){{/apis}}{{/apiInfo}}); module.exports = factory(require('./ApiClient'){{#models}}, require('./{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{importPath}}'){{/models}}{{#apiInfo}}{{#apis}}, require('./{{#apiPackage}}{{apiPackage}}/{{/apiPackage}}{{importPath}}'){{/apis}}{{/apiInfo}});
@@ -15,7 +15,7 @@
* <p> * <p>
* An AMD (recommended!) or CommonJS application will generally do something equivalent to the following: * An AMD (recommended!) or CommonJS application will generally do something equivalent to the following:
* <pre> * <pre>
* var {{moduleName}} = require('./index'); // See note below*. * var {{moduleName}} = require('{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}index'); // See note below*.
* var xxxSvc = new {{moduleName}}.XxxApi(); // Allocate the API class we're going to use. * var xxxSvc = new {{moduleName}}.XxxApi(); // Allocate the API class we're going to use.
* var yyyModel = new {{moduleName}}.Yyy(); // Construct a model instance. * var yyyModel = new {{moduleName}}.Yyy(); // Construct a model instance.
* yyyModel.someProperty = 'someValue'; * yyyModel.someProperty = 'someValue';
@@ -23,8 +23,8 @@
* var zzz = xxxSvc.doSomething(yyyModel); // Invoke the service. * var zzz = xxxSvc.doSomething(yyyModel); // Invoke the service.
* ... * ...
* </pre> * </pre>
* <em>*NOTE: For a top-level AMD script, use require(['./index'], function(){...}) and put the application logic within the * <em>*NOTE: For a top-level AMD script, use require(['{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}index'], function(){...})
* callback function.</em> * and put the application logic within the callback function.</em>
* </p> * </p>
* <p> * <p>
* A non-AMD browser application (discouraged) might do something like this: * A non-AMD browser application (discouraged) might do something like this:
@@ -37,23 +37,23 @@
* ... * ...
* </pre> * </pre>
* </p> * </p>
* @module index * @module {{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}index
* @version {{projectVersion}} * @version {{projectVersion}}
*/{{/emitJSDoc}} */{{/emitJSDoc}}
{{=< >=}} var exports = {<#emitJSDoc> {{=< >=}} var exports = {<#emitJSDoc>
/** /**
* The ApiClient constructor. * The ApiClient constructor.
* @property {module:ApiClient} * @property {module:<#invokerPackage><invokerPackage>/</invokerPackage>ApiClient}
*/</emitJSDoc> */</emitJSDoc>
ApiClient: ApiClient<#models>,<#emitJSDoc> ApiClient: ApiClient<#models>,<#emitJSDoc>
/** /**
* The <importPath> model constructor. * The <importPath> model constructor.
* @property {module:<#modelPackage><modelPackage>/</modelPackage><importPath>} * @property {module:<#invokerPackage><invokerPackage>/</invokerPackage><#modelPackage><modelPackage>/</modelPackage><importPath>}
*/</emitJSDoc> */</emitJSDoc>
<importPath>: <importPath></models><#apiInfo><#apis>,<#emitJSDoc> <importPath>: <importPath></models><#apiInfo><#apis>,<#emitJSDoc>
/** /**
* The <importPath> service constructor. * The <importPath> service constructor.
* @property {module:<#apiPackage><apiPackage>/</apiPackage><importPath>} * @property {module:<#invokerPackage><invokerPackage>/</invokerPackage><#apiPackage><apiPackage>/</apiPackage><importPath>}
*/</emitJSDoc> */</emitJSDoc>
<importPath>: <importPath></apis></apiInfo> <importPath>: <importPath></apis></apiInfo>
}; };

View File

@@ -1,7 +1,7 @@
(function(root, factory) { (function(root, factory) {
if (typeof define === 'function' && define.amd) { if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module. // AMD. Register as an anonymous module.
define(['../ApiClient'{{#imports}}, './{{import}}'{{/imports}}], factory); define(['{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient'{{#imports}}, '{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{import}}'{{/imports}}], factory);
} else if (typeof module === 'object' && module.exports) { } else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node. // CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'){{#imports}}, require('./{{import}}'){{/imports}}); module.exports = factory(require('../ApiClient'){{#imports}}, require('./{{import}}'){{/imports}});
@@ -15,86 +15,6 @@
}(this, function(ApiClient{{#imports}}, {{import}}{{/imports}}) { }(this, function(ApiClient{{#imports}}, {{import}}{{/imports}}) {
'use strict'; 'use strict';
{{#models}}{{#model}}{{#emitJSDoc}} /** {{#models}}{{#model}}
* The {{classname}} model module. {{#isEnum}}{{>partial_model_enum_class}}{{/isEnum}}{{^isEnum}}{{>partial_model_generic}}{{/isEnum}}
* @module {{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{classname}} {{/model}}{{/models}}
* @version {{projectVersion}}
*/
/**
* Constructs a new <code>{{classname}}</code>.{{#description}}
* {{description}}{{/description}}
* @alias module:{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{classname}}
* @class{{#useInheritance}}{{#parent}}
* @extends module:{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{parent}}{{/parent}}{{#interfaces}}
* @implements module:{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{.}}{{/interfaces}}{{/useInheritance}}{{#vendorExtensions.x-all-required}}
* @param {{.}}{{/vendorExtensions.x-all-required}}
*/{{/emitJSDoc}}
var exports = function({{#vendorExtensions.x-all-required}}{{.}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-all-required}}) {
{{#useInheritance}}{{#parentModel}} {{classname}}.call(this{{#vendorExtensions.x-all-required}}, {{.}}{{/vendorExtensions.x-all-required}});{{/parentModel}}
{{#interfaceModels}} {{classname}}.call(this{{#vendorExtensions.x-all-required}}, {{.}}{{/vendorExtensions.x-all-required}});
{{/interfaceModels}}{{/useInheritance}}{{#vars}}{{#required}} this['{{baseName}}'] = {{name}};{{/required}}
{{/vars}} };
{{#emitJSDoc}} /**
* Constructs a <code>{{classname}}</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {{=< >=}}{module:<#modelPackage><modelPackage>/</modelPackage><classname>}<={{ }}=> obj Optional instance to populate.
* @return {{=< >=}}{module:<#modelPackage><modelPackage>/</modelPackage><classname>}<={{ }}=> The populated <code>{{classname}}</code> instance.
*/
{{/emitJSDoc}} exports.constructFromObject = function(data, obj) {
if (data) { {{!// TODO: support polymorphism: discriminator property on data determines class to instantiate.}}
obj = obj || new exports();
{{#useInheritance}}{{#parent}} {{.}}.constructFromObject(data, obj);{{/parent}}
{{#interfaces}} {{.}}.constructFromObject(data, obj);
{{/interfaces}}{{/useInheritance}}{{#vars}} if (data.hasOwnProperty('{{baseName}}')) {
obj['{{baseName}}']{{{defaultValueWithParam}}}
}
{{/vars}} }
return obj;
}
{{#useInheritance}}{{#parent}}
exports.prototype = Object.create({{parent}}.prototype);
exports.prototype.constructor = exports;
{{/parent}}{{/useInheritance}}
{{#vars}}{{#emitJSDoc}}
/**{{#description}}
* {{{description}}}{{/description}}
* @member {{{vendorExtensions.x-jsdoc-type}}} {{baseName}}{{#defaultValue}}
* @default {{{defaultValue}}}{{/defaultValue}}
*/
{{/emitJSDoc}} exports.prototype['{{baseName}}'] = {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}undefined{{/defaultValue}};
{{/vars}}{{#useInheritance}}{{#interfaceModels}}
// Implement {{classname}} interface:{{#allVars}}{{#emitJSDoc}}
/**{{#description}}
* {{{description}}}{{/description}}
* @member {{{vendorExtensions.x-jsdoc-type}}} {{baseName}}{{#defaultValue}}
* @default {{{defaultValue}}}{{/defaultValue}}
*/
{{/emitJSDoc}} exports.prototype['{{baseName}}'] = {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}undefined{{/defaultValue}};
{{/allVars}}{{/interfaceModels}}{{/useInheritance}}
{{#emitModelMethods}}{{#vars}}{{#emitJSDoc}} /**{{#description}}
* Returns {{{description}}}{{/description}}{{#minimum}}
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
* maximum: {{maximum}}{{/maximum}}
* @return {{{vendorExtensions.x-jsdoc-type}}}
*/
{{/emitJSDoc}} exports.prototype.{{getter}} = function() {
return this['{{baseName}}'];
}
{{#emitJSDoc}} /**{{#description}}
* Sets {{{description}}}{{/description}}
* @param {{{vendorExtensions.x-jsdoc-type}}} {{name}}{{#description}} {{{description}}}{{/description}}
*/
{{/emitJSDoc}} exports.prototype.{{setter}} = function({{name}}) {
this['{{baseName}}'] = {{name}};
}
{{/vars}}{{/emitModelMethods}}
{{#vars}}{{#isEnum}}{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}}
{{>enumClass}}{{/items}}*/{{/items.isEnum}}{{/vars}}
return exports;
{{/model}}{{/models}}}));

View File

@@ -1,9 +1,25 @@
{{#models}}{{#model}}# {{moduleName}}.{{classname}} {{#models}}{{#model}}{{#isEnum}}# {{moduleName}}.{{classname}}
## Enum
{{#allowableValues}}{{#enumVars}}
* `{{name}}` (value: `{{{value}}}`)
{{/enumVars}}{{/allowableValues}}
{{/isEnum}}{{^isEnum}}# {{moduleName}}.{{classname}}
## Properties ## Properties
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{datatype}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} {{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{datatype}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}
{{/vars}} {{/vars}}
{{#vars}}{{#isEnum}}
{{/model}}{{/models}} <a name="{{{datatypeWithEnum}}}"></a>
## Enum: {{datatypeWithEnum}}
{{#allowableValues}}{{#enumVars}}
* `{{name}}` (value: `{{{value}}}`)
{{/enumVars}}{{/allowableValues}}
{{/isEnum}}{{/vars}}
{{/isEnum}}{{/model}}{{/models}}

View File

@@ -3,7 +3,7 @@
"version": "{{{projectVersion}}}", "version": "{{{projectVersion}}}",
"description": "{{{projectDescription}}}",{{#projectLicenseName}} "description": "{{{projectDescription}}}",{{#projectLicenseName}}
"license": "{{{projectLicenseName}}}",{{/projectLicenseName}} "license": "{{{projectLicenseName}}}",{{/projectLicenseName}}
"main": "{{sourceFolder}}/index.js", "main": "{{sourceFolder}}{{#invokerPackage}}/{{invokerPackage}}{{/invokerPackage}}/index.js",
"scripts": { "scripts": {
"test": "./node_modules/mocha/bin/mocha --recursive" "test": "./node_modules/mocha/bin/mocha --recursive"
}, },

View File

@@ -0,0 +1,24 @@
{{#emitJSDoc}}
/**
* Enum class {{classname}}.
* @enum {{=<% %>=}}{<%datatype%>}<%={{ }}=%>
* @readonly
*/
{{/emitJSDoc}}
var exports = {
{{#allowableValues}}
{{#enumVars}}
{{#emitJSDoc}}
/**
* value: {{{value}}}
* @const
*/
{{/emitJSDoc}}
"{{name}}": {{{value}}}{{^-last}},
{{/-last}}
{{/enumVars}}
{{/allowableValues}}
};
return exports;
}));

View File

@@ -0,0 +1,103 @@
{{#models}}{{#model}}
{{#emitJSDoc}}
/**
* The {{classname}} model module.
* @module {{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{classname}}
* @version {{projectVersion}}
*/
/**
* Constructs a new <code>{{classname}}</code>.{{#description}}
* {{description}}{{/description}}
* @alias module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{classname}}
* @class{{#useInheritance}}{{#parent}}
* @extends {{#parentModel}}module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{classname}}{{/parentModel}}{{^parentModel}}{{#vendorExtensions.x-isArray}}Array{{/vendorExtensions.x-isArray}}{{#vendorExtensions.x-isMap}}Object{{/vendorExtensions.x-isMap}}{{/parentModel}}{{/parent}}{{#interfaces}}
* @implements module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{.}}{{/interfaces}}{{/useInheritance}}{{#vendorExtensions.x-all-required}}
* @param {{.}}{{/vendorExtensions.x-all-required}}
*/
{{/emitJSDoc}}
var exports = function({{#vendorExtensions.x-all-required}}{{.}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-all-required}}) {
var _this = this;
{{#parent}}{{^parentModel}}{{#vendorExtensions.x-isArray}} _this = new Array();
Object.setPrototypeOf(_this, exports);
{{/vendorExtensions.x-isArray}}{{/parentModel}}{{/parent}}{{#useInheritance}}{{#parentModel}} {{classname}}.call(_this{{#vendorExtensions.x-all-required}}, {{.}}{{/vendorExtensions.x-all-required}});{{/parentModel}}
{{#interfaceModels}} {{classname}}.call(_this{{#vendorExtensions.x-all-required}}, {{.}}{{/vendorExtensions.x-all-required}});
{{/interfaceModels}}{{/useInheritance}}{{#vars}}{{#required}} _this['{{baseName}}'] = {{name}};{{/required}}
{{/vars}}{{#parent}}{{^parentModel}} return _this;
{{/parentModel}}{{/parent}} };
{{#emitJSDoc}}
/**
* Constructs a <code>{{classname}}</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {{=< >=}}{module:<#invokerPackage><invokerPackage>/</invokerPackage><#modelPackage><modelPackage>/</modelPackage><classname>}<={{ }}=> obj Optional instance to populate.
* @return {{=< >=}}{module:<#invokerPackage><invokerPackage>/</invokerPackage><#modelPackage><modelPackage>/</modelPackage><classname>}<={{ }}=> The populated <code>{{classname}}</code> instance.
*/
{{/emitJSDoc}}
exports.constructFromObject = function(data, obj) {
if (data){{! TODO: support polymorphism: discriminator property on data determines class to instantiate.}} {
obj = obj || new exports();
{{#parent}}{{^parentModel}} ApiClient.constructFromObject(data, obj, {{vendorExtensions.x-itemType}});
{{/parentModel}}{{/parent}}{{#useInheritance}}{{#parentModel}} {{classname}}.constructFromObject(data, obj);{{/parentModel}}
{{#interfaces}} {{.}}.constructFromObject(data, obj);
{{/interfaces}}{{/useInheritance}}{{#vars}} if (data.hasOwnProperty('{{baseName}}')) {
obj['{{baseName}}']{{{defaultValueWithParam}}}
}
{{/vars}} }
return obj;
}
{{#useInheritance}}{{#parentModel}}
exports.prototype = Object.create({{classname}}.prototype);
exports.prototype.constructor = exports;
{{/parentModel}}{{/useInheritance}}
{{#vars}}
{{#emitJSDoc}}
/**{{#description}}
* {{{description}}}{{/description}}
* @member {{{vendorExtensions.x-jsdoc-type}}} {{baseName}}{{#defaultValue}}
* @default {{{defaultValue}}}{{/defaultValue}}
*/
{{/emitJSDoc}}
exports.prototype['{{baseName}}'] = {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}undefined{{/defaultValue}};
{{/vars}}{{#useInheritance}}{{#interfaceModels}}
// Implement {{classname}} interface:{{#allVars}}
{{#emitJSDoc}}
/**{{#description}}
* {{{description}}}{{/description}}
* @member {{{vendorExtensions.x-jsdoc-type}}} {{baseName}}{{#defaultValue}}
* @default {{{defaultValue}}}{{/defaultValue}}
*/
{{/emitJSDoc}}
exports.prototype['{{baseName}}'] = {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}undefined{{/defaultValue}};
{{/allVars}}{{/interfaceModels}}{{/useInheritance}}
{{#emitModelMethods}}{{#vars}}
{{#emitJSDoc}}
/**{{#description}}
* Returns {{{description}}}{{/description}}{{#minimum}}
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
* maximum: {{maximum}}{{/maximum}}
* @return {{{vendorExtensions.x-jsdoc-type}}}
*/
{{/emitJSDoc}}
exports.prototype.{{getter}} = function() {
return this['{{baseName}}'];
}
{{#emitJSDoc}}
/**{{#description}}
* Sets {{{description}}}{{/description}}
* @param {{{vendorExtensions.x-jsdoc-type}}} {{name}}{{#description}} {{{description}}}{{/description}}
*/
{{/emitJSDoc}}
exports.prototype.{{setter}} = function({{name}}) {
this['{{baseName}}'] = {{name}};
}
{{/vars}}{{/emitModelMethods}}
{{#vars}}{{#isEnum}}{{>partial_model_inner_enum}}{{/isEnum}}{{#items.isEnum}}{{#items}}
{{>partial_model_inner_enum}}{{/items}}*/{{/items.isEnum}}{{/vars}}
return exports;
{{/model}}{{/models}}}));

View File

@@ -0,0 +1,21 @@
{{#emitJSDoc}}
/**
* Allowed values for the <code>{{baseName}}</code> property.
* @enum {{=<% %>=}}{<%datatype%>}<%={{ }}=%>
* @readonly
*/
{{/emitJSDoc}}
exports.{{datatypeWithEnum}} = {
{{#allowableValues}}
{{#enumVars}}
{{#emitJSDoc}}
/**
* value: {{{value}}}
* @const
*/
{{/emitJSDoc}}
"{{name}}": {{{value}}}{{^-last}},
{{/-last}}
{{/enumVars}}
{{/allowableValues}}
};

View File

@@ -28,6 +28,7 @@ io.swagger.codegen.languages.ScalatraServerCodegen
io.swagger.codegen.languages.SilexServerCodegen io.swagger.codegen.languages.SilexServerCodegen
io.swagger.codegen.languages.SinatraServerCodegen io.swagger.codegen.languages.SinatraServerCodegen
io.swagger.codegen.languages.SlimFrameworkServerCodegen io.swagger.codegen.languages.SlimFrameworkServerCodegen
io.swagger.codegen.languages.SpringBootServerCodegen
io.swagger.codegen.languages.SpringMVCServerCodegen io.swagger.codegen.languages.SpringMVCServerCodegen
io.swagger.codegen.languages.StaticDocCodegen io.swagger.codegen.languages.StaticDocCodegen
io.swagger.codegen.languages.StaticHtmlGenerator io.swagger.codegen.languages.StaticHtmlGenerator
@@ -38,6 +39,7 @@ io.swagger.codegen.languages.TizenClientCodegen
io.swagger.codegen.languages.TypeScriptAngular2ClientCodegen io.swagger.codegen.languages.TypeScriptAngular2ClientCodegen
io.swagger.codegen.languages.TypeScriptAngularClientCodegen io.swagger.codegen.languages.TypeScriptAngularClientCodegen
io.swagger.codegen.languages.TypeScriptNodeClientCodegen io.swagger.codegen.languages.TypeScriptNodeClientCodegen
io.swagger.codegen.languages.TypeScriptFetchClientCodegen
io.swagger.codegen.languages.AkkaScalaClientCodegen io.swagger.codegen.languages.AkkaScalaClientCodegen
io.swagger.codegen.languages.CsharpDotNet2ClientCodegen io.swagger.codegen.languages.CsharpDotNet2ClientCodegen
io.swagger.codegen.languages.ClojureClientCodegen io.swagger.codegen.languages.ClojureClientCodegen

View File

@@ -0,0 +1,133 @@
import * as querystring from 'querystring';
import * as fetch from 'isomorphic-fetch';
import {assign} from './assign';
{{#models}}
{{#model}}
{{#description}}
/**
* {{{description}}}
*/
{{/description}}
export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{
{{#vars}}
{{#description}}
/**
* {{{description}}}
*/
{{/description}}
"{{name}}"{{^required}}?{{/required}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}};
{{/vars}}
}
{{#hasEnums}}
{{#vars}}
{{#isEnum}}
export enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}}
{{.}} = <any> '{{.}}'{{^-last}},{{/-last}}{{/values}}{{/allowableValues}}
}
{{/isEnum}}
{{/vars}}
{{/hasEnums}}
{{/model}}
{{/models}}
{{#apiInfo}}
{{#apis}}
{{#operations}}
//export namespace {{package}} {
'use strict';
{{#description}}
/**
* {{&description}}
*/
{{/description}}
export class {{classname}} {
protected basePath = '{{basePath}}';
public defaultHeaders : any = {};
constructor(basePath?: string) {
if (basePath) {
this.basePath = basePath;
}
}
{{#operation}}
/**
* {{summary}}
* {{notes}}
{{#allParams}}* @param {{paramName}} {{description}}
{{/allParams}}*/
public {{nickname}} (params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> {
const localVarPath = this.basePath + '{{path}}'{{#pathParams}}
.replace('{' + '{{baseName}}' + '}', String(params.{{paramName}})){{/pathParams}};
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
{{#hasFormParams}}
let formParams: any = {};
headerParams['Content-Type'] = 'application/x-www-form-urlencoded';
{{/hasFormParams}}
{{#hasBodyParam}}
headerParams['Content-Type'] = 'application/json';
{{/hasBodyParam}}
{{#allParams}}
{{#required}}
// verify required parameter '{{paramName}}' is set
if (params.{{paramName}} == null) {
throw new Error('Missing required parameter {{paramName}} when calling {{nickname}}');
}
{{/required}}
{{/allParams}}
{{#queryParams}}
if (params.{{paramName}} !== undefined) {
queryParameters['{{baseName}}'] = params.{{paramName}};
}
{{/queryParams}}
{{#headerParams}}
headerParams['{{baseName}}'] = params.{{paramName}};
{{/headerParams}}
{{#formParams}}
formParams['{{baseName}}'] = params.{{paramName}};
{{/formParams}}
let fetchParams = {
method: '{{httpMethod}}',
headers: headerParams,
{{#bodyParam}}body: JSON.stringify(params.{{paramName}}),
{{/bodyParam}}
{{#hasFormParams}}body: querystring.stringify(formParams),
{{/hasFormParams}}
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
{{/operation}}
}
//}
{{/operations}}
{{/apis}}
{{/apiInfo}}

Some files were not shown because too many files have changed in this diff Show More