Merge remote-tracking branch 'refs/remotes/swagger-api/master' into JSR310-Clients

This commit is contained in:
ant3 2016-06-17 21:25:35 +01:00
commit c1a5839d44
489 changed files with 21300 additions and 2346 deletions

View File

@ -28,15 +28,19 @@ For a list of variables available in the template, please refer to this [page](h
### Style guide ### Style guide
Code change should conform to the programming style guide of the respective langauages: Code change should conform to the programming style guide of the respective langauages:
- Android: https://source.android.com/source/code-style.html
- C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx - C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx
- Haskell: https://github.com/tibbe/haskell-style-guide/blob/master/haskell-style.md
- Java: https://google.github.io/styleguide/javaguide.html - Java: https://google.github.io/styleguide/javaguide.html
- JavaScript: https://github.com/airbnb/javascript/tree/master/es5 - JavaScript: https://github.com/airbnb/javascript/tree/master/es5
- Groovy: http://groovy-lang.org/style-guide.html
- Go: https://github.com/golang/go/wiki/CodeReviewComments - Go: https://github.com/golang/go/wiki/CodeReviewComments
- ObjC: https://github.com/NYTimes/objective-c-style-guide - ObjC: https://github.com/NYTimes/objective-c-style-guide
- Perl: http://perldoc.perl.org/perlstyle.html - Perl: http://perldoc.perl.org/perlstyle.html
- PHP: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md - PHP: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md
- Python: https://www.python.org/dev/peps/pep-0008/ - Python: https://www.python.org/dev/peps/pep-0008/
- Ruby: https://github.com/bbatsov/ruby-style-guide - Ruby: https://github.com/bbatsov/ruby-style-guide
- Scala: http://docs.scala-lang.org/style/
- Swift: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html - Swift: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html
- TypeScript: https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines - TypeScript: https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines

152
README.md
View File

@ -641,155 +641,7 @@ open index.html
### To build a server stub ### To build a server stub
You can also use the codegen to generate a server for a couple different frameworks. Take a look here: Please refer to https://github.com/swagger-api/swagger-codegen/wiki/Server-stub-generator-HOWTO for more information.
### Node.js
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l nodejs-server \
-o samples/server/petstore/nodejs
```
### PHP Slim
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l slim \
-o samples/server/petstore/slim
```
### PHP Silex
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l silex-PHP \
-o samples/server/petstore/silex
```
### Python Flask (Connexion)
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l python-flask \
-o samples/server/petstore/flaskConnexion
```
### Ruby Sinatra
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l sinatra \
-o samples/server/petstore/sinatra
```
### Scala Scalatra
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l scalatra \
-o samples/server/petstore/scalatra
```
### Java JAX-RS (Jersey v1.18)
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l jaxrs \
-o samples/server/petstore/jaxrs-jersey
```
### Java JAX-RS (Apache CXF 2 / 3)
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l jaxrs-cxf \
-o samples/server/petstore/jaxrs-cxf
```
This Codegen only generate a minimalist server stub. You must add the CXF dependency to your classpath (eg: with Maven)
If you are using CXF v2.x, you must provided a custom ```ResourceComparator``` class. This class will help CXF to choose the good resource interface for mapping an incomming request. The default behavior of CXF v2.x is not correct when many resources interface have the same global path.
See: See http://cxf.apache.org/docs/jax-rs-basics.html#JAX-RSBasics-Customselectionbetweenmultipleresources
You can found this class here: https://github.com/hiveship/CXF2-resource-comparator/blob/master/src/main/java/CXFInterfaceComparator.java
TODO: This class could be directly generated by the Codegen.
You must register this class into your JAX-RS configuration file:
```xml
<jaxrs:resourceComparator>
<bean class="your.package.CXFInterfaceComparator"/>
</jaxrs:resourceComparator>
```
This is no longer necessary if you are using CXF >=v3.x
### Java JAX-RS (Resteasy)
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l jaxrs-resteasy \
-o samples/server/petstore/jaxrs-resteasy
```
### Java Spring MVC
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l spring-mvc \
-o samples/server/petstore/spring-mvc
```
### Java SpringBoot
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l springboot \
-o samples/server/petstore/springboot
```
You can also set a Json file with basePackage & configPackage properties :
Example :
```
{
"basePackage":"io.swagger",
"configPackage":"io.swagger.config"
}
```
For use it add option ```-c myOptions.json``` to the generation command
To Use-it :
in the generated folder try ``` mvn package ``` for build jar.
Start your server ``` java -jar target/swagger-springboot-server-1.0.0.jar ```
SpringBoot listening on default port 8080
### Haskell Servant
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l haskell-servant \
-o samples/server/petstore/haskell-servant
```
### ASP.NET 5 Web API
```
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l aspnet5 \
-o samples/server/petstore/aspnet5
```
### To build the codegen library ### To build the codegen library
@ -864,6 +716,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you
- [IMS Health](http://www.imshealth.com/en/solution-areas/technology-and-applications) - [IMS Health](http://www.imshealth.com/en/solution-areas/technology-and-applications)
- [Interactive Intelligence](http://developer.mypurecloud.com/) - [Interactive Intelligence](http://developer.mypurecloud.com/)
- [LANDR Audio](https://www.landr.com/) - [LANDR Audio](https://www.landr.com/)
- [Lascaux](http://www.lascaux.it/)
- [LiveAgent](https://www.ladesk.com/) - [LiveAgent](https://www.ladesk.com/)
- [Kabuku](http://www.kabuku.co.jp/en) - [Kabuku](http://www.kabuku.co.jp/en)
- [Kuary](https://kuary.com/) - [Kuary](https://kuary.com/)
@ -935,6 +788,7 @@ Swaagger Codegen core team members are contributors who have been making signfic
Here is a list of template creators: Here is a list of template creators:
* API Clients: * API Clients:
* Akka-Scala: @cchafer * Akka-Scala: @cchafer
* C++ REST: @Danielku15
* C# (.NET 2.0): @who * C# (.NET 2.0): @who
* Clojure: @xhh * Clojure: @xhh
* Dart: @yissachar * Dart: @yissachar

31
bin/cpprest-petstore.sh Executable file
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/cpprest -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l cpprest -o samples/client/petstore/cpprest"
java $JAVA_OPTS -jar $executable $ags

31
bin/go-petstore-server.sh Executable file
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.yaml -l go-server -o samples/server/petstore/go-api-server -DpackageName=petstoreserver "
java $JAVA_OPTS -Dservice -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/lumen -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l lumen -o samples/server/petstore/lumen" ags="$@ generate -t modules/swagger-codegen/src/main/resources/lumen -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l lumen -o samples/server/petstore/lumen"
java $JAVA_OPTS -jar $executable $ags java $JAVA_OPTS -jar $executable $ags

36
bin/swift-petstore-all.sh Executable file
View File

@ -0,0 +1,36 @@
#!/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/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore.json -o samples/client/petstore/swift/default"
echo "#### Petstore Swift API client (default) ####"
java $JAVA_OPTS -jar $executable $ags
ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore-promisekit.json -o samples/client/petstore/swift/promisekit"
echo "#### Petstore Swift API client (promisekit) ####"
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\cpprest -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l cpprest -o samples\client\petstore\cpprest
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -22,6 +22,7 @@ public class CodegenModel {
public String unescapedDescription; public String unescapedDescription;
public String discriminator; public String discriminator;
public String defaultValue; public String defaultValue;
public String arrayModelType;
public List<CodegenProperty> vars = new ArrayList<CodegenProperty>(); public List<CodegenProperty> vars = new ArrayList<CodegenProperty>();
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
@ -35,7 +36,7 @@ public class CodegenModel {
public Set<String> allMandatory; public Set<String> allMandatory;
public Set<String> imports = new TreeSet<String>(); public Set<String> imports = new TreeSet<String>();
public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired; public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired, isArrayModel;
public ExternalDocs externalDocs; public ExternalDocs externalDocs;
public Map<String, Object> vendorExtensions; public Map<String, Object> vendorExtensions;

View File

@ -1198,6 +1198,8 @@ public class DefaultCodegen {
ArrayModel am = (ArrayModel) model; ArrayModel am = (ArrayModel) model;
ArrayProperty arrayProperty = new ArrayProperty(am.getItems()); ArrayProperty arrayProperty = new ArrayProperty(am.getItems());
m.hasEnums = false; // Otherwise there will be a NullPointerException in JavaClientCodegen.fromModel m.hasEnums = false; // Otherwise there will be a NullPointerException in JavaClientCodegen.fromModel
m.isArrayModel = true;
m.arrayModelType = fromProperty(name, arrayProperty).complexType;
addParentContainer(m, name, arrayProperty); addParentContainer(m, name, arrayProperty);
} else if (model instanceof RefModel) { } else if (model instanceof RefModel) {
// TODO // TODO
@ -1465,7 +1467,9 @@ public class DefaultCodegen {
if (p instanceof BinaryProperty) { if (p instanceof BinaryProperty) {
property.isBinary = true; property.isBinary = true;
} }
if (p instanceof UUIDProperty) {
property.isString = true;
}
if (p instanceof ByteArrayProperty) { if (p instanceof ByteArrayProperty) {
property.isByteArray = true; property.isByteArray = true;
} }

View File

@ -0,0 +1,380 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.codegen.examples.ExampleGenerator;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Response;
import io.swagger.models.Swagger;
import io.swagger.models.properties.*;
import java.util.*;
import java.io.File;
public class CppRestClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String DECLSPEC = "declspec";
public static final String DEFAULT_INCLUDE = "defaultInclude";
protected String packageVersion = "1.0.0";
protected String declspec = "";
protected String defaultInclude = "";
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see io.swagger.codegen.CodegenType
*/
public CodegenType getTag() {
return CodegenType.CLIENT;
}
/**
* Configures a friendly name for the generator. This will be used by the
* generator to select the library with the -l flag.
*
* @return the friendly name for the generator
*/
public String getName() {
return "cpprest";
}
/**
* Returns human-friendly help for the generator. Provide the consumer with
* help tips, parameters here
*
* @return A string value for the help message
*/
public String getHelp() {
return "Generates a C++ API client with C++ REST SDK (https://github.com/Microsoft/cpprestsdk).";
}
public CppRestClientCodegen() {
super();
apiPackage = "io.swagger.client.api";
modelPackage = "io.swagger.client.model";
modelTemplateFiles.put("model-header.mustache", ".h");
modelTemplateFiles.put("model-source.mustache", ".cpp");
apiTemplateFiles.put("api-header.mustache", ".h");
apiTemplateFiles.put("api-source.mustache", ".cpp");
templateDir = "cpprest";
cliOptions.clear();
// CLI options
addOption(CodegenConstants.MODEL_PACKAGE, "C++ namespace for models (convention: name.space.model).",
this.modelPackage);
addOption(CodegenConstants.API_PACKAGE, "C++ namespace for apis (convention: name.space.api).",
this.apiPackage);
addOption(CodegenConstants.PACKAGE_VERSION, "C++ package version.", this.packageVersion);
addOption(DECLSPEC, "C++ preprocessor to place before the class name for handling dllexport/dllimport.",
this.declspec);
addOption(DEFAULT_INCLUDE,
"The default include statement that should be placed in all headers for including things like the declspec (convention: #include \"Commons.h\" ",
this.defaultInclude);
reservedWords = new HashSet<String>();
supportingFiles.add(new SupportingFile("modelbase-header.mustache", "", "ModelBase.h"));
supportingFiles.add(new SupportingFile("modelbase-source.mustache", "", "ModelBase.cpp"));
supportingFiles.add(new SupportingFile("apiclient-header.mustache", "", "ApiClient.h"));
supportingFiles.add(new SupportingFile("apiclient-source.mustache", "", "ApiClient.cpp"));
supportingFiles.add(new SupportingFile("apiconfiguration-header.mustache", "", "ApiConfiguration.h"));
supportingFiles.add(new SupportingFile("apiconfiguration-source.mustache", "", "ApiConfiguration.cpp"));
supportingFiles.add(new SupportingFile("apiexception-header.mustache", "", "ApiException.h"));
supportingFiles.add(new SupportingFile("apiexception-source.mustache", "", "ApiException.cpp"));
supportingFiles.add(new SupportingFile("ihttpbody-header.mustache", "", "IHttpBody.h"));
supportingFiles.add(new SupportingFile("jsonbody-header.mustache", "", "JsonBody.h"));
supportingFiles.add(new SupportingFile("jsonbody-source.mustache", "", "JsonBody.cpp"));
supportingFiles.add(new SupportingFile("httpcontent-header.mustache", "", "HttpContent.h"));
supportingFiles.add(new SupportingFile("httpcontent-source.mustache", "", "HttpContent.cpp"));
supportingFiles.add(new SupportingFile("multipart-header.mustache", "", "MultipartFormData.h"));
supportingFiles.add(new SupportingFile("multipart-source.mustache", "", "MultipartFormData.cpp"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList("int", "char", "bool", "long", "float", "double", "int32_t", "int64_t"));
typeMapping = new HashMap<String, String>();
typeMapping.put("date", "utility::datetime");
typeMapping.put("DateTime", "utility::datetime");
typeMapping.put("string", "utility::string_t");
typeMapping.put("integer", "int32_t");
typeMapping.put("long", "int64_t");
typeMapping.put("boolean", "bool");
typeMapping.put("array", "std::vector");
typeMapping.put("map", "std::map");
typeMapping.put("file", "HttpContent");
typeMapping.put("object", "Object");
typeMapping.put("binary", "std::string");
super.importMapping = new HashMap<String, String>();
importMapping.put("std::vector", "#include <vector>");
importMapping.put("std::map", "#include <map>");
importMapping.put("std::string", "#include <string>");
importMapping.put("HttpContent", "#include \"HttpContent.h\"");
importMapping.put("Object", "#include \"Object.h\"");
importMapping.put("utility::string_t", "#include <cpprest/details/basic_types.h>");
importMapping.put("utility::datetime", "#include <cpprest/details/basic_types.h>");
}
protected void addOption(String key, String description, String defaultValue) {
CliOption option = new CliOption(key, description);
if (defaultValue != null)
option.defaultValue(defaultValue);
cliOptions.add(option);
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(DECLSPEC)) {
declspec = additionalProperties.get(DECLSPEC).toString();
}
if (additionalProperties.containsKey(DEFAULT_INCLUDE)) {
defaultInclude = additionalProperties.get(DEFAULT_INCLUDE).toString();
}
additionalProperties.put("modelNamespaceDeclarations", modelPackage.split("\\."));
additionalProperties.put("modelNamespace", modelPackage.replaceAll("\\.", "::"));
additionalProperties.put("apiNamespaceDeclarations", apiPackage.split("\\."));
additionalProperties.put("apiNamespace", apiPackage.replaceAll("\\.", "::"));
additionalProperties.put("declspec", declspec);
additionalProperties.put("defaultInclude", defaultInclude);
}
/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle
* escaping those terms here. This logic is only called if a variable
* matches the reseved words
*
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
}
/**
* Location to write model files. You can use the modelPackage() as defined
* when the class is instantiated
*/
public String modelFileFolder() {
return outputFolder + "/model";
}
/**
* Location to write api files. You can use the apiPackage() as defined when
* the class is instantiated
*/
@Override
public String apiFileFolder() {
return outputFolder + "/api";
}
@Override
public String toModelImport(String name) {
if (importMapping.containsKey(name)) {
return importMapping.get(name);
} else {
return "#include \"" + name + ".h\"";
}
}
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
Set<String> oldImports = codegenModel.imports;
codegenModel.imports = new HashSet<String>();
for (String imp : oldImports) {
String newImp = toModelImport(imp);
if (!newImp.isEmpty()) {
codegenModel.imports.add(newImp);
}
}
return codegenModel;
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation,
Map<String, Model> definitions, Swagger swagger) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger);
if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
Response methodResponse = findMethodResponse(operation.getResponses());
if (methodResponse != null) {
if (methodResponse.getSchema() != null) {
CodegenProperty cm = fromProperty("response", methodResponse.getSchema());
op.vendorExtensions.put("x-codegen-response", cm);
}
}
}
return op;
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
if (isFileProperty(property)) {
property.vendorExtensions.put("x-codegen-file", true);
}
}
protected boolean isFileProperty(CodegenProperty property) {
return property.baseType.equals("HttpContent");
}
@Override
public String toModelFilename(String name) {
return initialCaps(name);
}
@Override
public String toApiFilename(String name) {
return initialCaps(name) + "Api";
}
/**
* Optional - type declaration. This is a String which is used by the
* templates to instantiate your types. There is typically special handling
* for different property types
*
* @return a string value used as the `dataType` field for model templates,
* `returnType` for api templates
*/
@Override
public String getTypeDeclaration(Property p) {
String swaggerType = getSwaggerType(p);
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
}
if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<utility::string_t, " + getTypeDeclaration(inner) + ">";
}
if (p instanceof StringProperty || p instanceof DateProperty || p instanceof DateTimeProperty
|| languageSpecificPrimitives.contains(swaggerType)) {
return toModelName(swaggerType);
}
return "std::shared_ptr<" + swaggerType + ">";
}
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
return "U(\"\")";
} else if (p instanceof BooleanProperty) {
return "false";
} else if (p instanceof DateProperty) {
return "utility::datetime()";
} else if (p instanceof DateTimeProperty) {
return "utility::datetime()";
} else if (p instanceof DoubleProperty) {
return "0.0";
} else if (p instanceof FloatProperty) {
return "0.0f";
} else if (p instanceof IntegerProperty) {
return "0";
} else if (p instanceof LongProperty) {
return "0L";
} else if (p instanceof DecimalProperty) {
return "0.0";
} else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "std::map<utility::string_t, " + inner + ">()";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
if (!languageSpecificPrimitives.contains(inner)) {
inner = "std::shared_ptr<" + inner + ">";
}
return "std::vector<" + inner + ">()";
} else if (p instanceof RefProperty) {
RefProperty rp = (RefProperty) p;
return "new " + toModelName(rp.getSimpleRef()) + "()";
}
return "nullptr";
}
@Override
public void postProcessParameter(CodegenParameter parameter) {
super.postProcessParameter(parameter);
boolean isPrimitiveType = parameter.isPrimitiveType == Boolean.TRUE;
boolean isListContainer = parameter.isListContainer == Boolean.TRUE;
boolean isString = parameter.isString == Boolean.TRUE;
if (!isPrimitiveType && !isListContainer && !isString && !parameter.dataType.startsWith("std::shared_ptr")) {
parameter.dataType = "std::shared_ptr<" + parameter.dataType + ">";
}
}
/**
* Optional - swagger type conversion. This is used to map swagger types in
* a `Property` into either language specific types via `typeMapping` or
* into complex models if there is not a mapping.
*
* @return a string value of the type or complex model for this property
* @see io.swagger.models.properties.Property
*/
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type))
return toModelName(type);
} else
type = swaggerType;
return toModelName(type);
}
@Override
public String toModelName(String type) {
if (typeMapping.keySet().contains(type) || typeMapping.values().contains(type)
|| importMapping.values().contains(type) || defaultIncludes.contains(type)
|| languageSpecificPrimitives.contains(type)) {
return type;
} else {
return Character.toUpperCase(type.charAt(0)) + type.substring(1);
}
}
@Override
public String toVarName(String name) {
if (typeMapping.keySet().contains(name) || typeMapping.values().contains(name)
|| importMapping.values().contains(name) || defaultIncludes.contains(name)
|| languageSpecificPrimitives.contains(name)) {
return name;
}
if (name.length() > 1) {
return Character.toUpperCase(name.charAt(0)) + name.substring(1);
}
return name;
}
@Override
public String toApiName(String type) {
return Character.toUpperCase(type.charAt(0)) + type.substring(1) + "Api";
}
}

View File

@ -0,0 +1,266 @@
package io.swagger.codegen.languages;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import io.swagger.codegen.*;
import io.swagger.models.*;
import io.swagger.util.Yaml;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;
public class GoServerCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(GoServerCodegen.class);
protected String apiVersion = "1.0.0";
protected int serverPort = 8080;
protected String projectName = "swagger-server";
protected String apiPath = "go";
public GoServerCodegen() {
super();
// set the output folder here
outputFolder = "generated-code/go";
/**
* Models. You can write model files using the modelTemplateFiles map.
* if you want to create one template for file, you can do so here.
* for multiple files for model, just put another entry in the `modelTemplateFiles` with
* a different extension
*/
modelTemplateFiles.clear();
/**
* Api classes. You can write classes for each Api file with the apiTemplateFiles map.
* as with models, add multiple entries with different extensions for multiple files per
* class
*/
apiTemplateFiles.put(
"controller.mustache", // the template to use
".go"); // the extension for each file to write
/**
* Template Location. This is the location which templates will be read from. The generator
* will use the resource stream to attempt to read the templates.
*/
embeddedTemplateDir = templateDir = "go-server";
/**
* Reserved words. Override this with reserved words specific to your language
*/
setReservedWordsLowerCase(
Arrays.asList(
"break", "default", "func", "interface", "select",
"case", "defer", "go", "map", "struct",
"chan", "else", "goto", "package", "switch",
"const", "fallthrough", "if", "range", "type",
"continue", "for", "import", "return", "var", "error", "ApiResponse")
// Added "error" as it's used so frequently that it may as well be a keyword
);
defaultIncludes = new HashSet<String>(
Arrays.asList(
"map",
"array")
);
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"string",
"bool",
"uint",
"uint32",
"uint64",
"int",
"int32",
"int64",
"float32",
"float64",
"complex64",
"complex128",
"rune",
"byte")
);
instantiationTypes.clear();
/*instantiationTypes.put("array", "GoArray");
instantiationTypes.put("map", "GoMap");*/
typeMapping.clear();
typeMapping.put("integer", "int32");
typeMapping.put("long", "int64");
typeMapping.put("number", "float32");
typeMapping.put("float", "float32");
typeMapping.put("double", "float64");
typeMapping.put("boolean", "bool");
typeMapping.put("string", "string");
typeMapping.put("date", "time.Time");
typeMapping.put("DateTime", "time.Time");
typeMapping.put("password", "string");
typeMapping.put("File", "*os.File");
typeMapping.put("file", "*os.File");
// map binary to string as a workaround
// the correct solution is to use []byte
typeMapping.put("binary", "string");
typeMapping.put("ByteArray", "string");
importMapping = new HashMap<String, String>();
importMapping.put("time.Time", "time");
importMapping.put("*os.File", "os");
importMapping.put("os", "io/ioutil");
cliOptions.clear();
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Go package name (convention: lowercase).")
.defaultValue("swagger"));
/**
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files
*/
additionalProperties.put("apiVersion", apiVersion);
additionalProperties.put("serverPort", serverPort);
additionalProperties.put("apiPath", apiPath);
/**
* Supporting Files. You can write single files for the generator with the
* entire object tree available. If the input file has a suffix of `.mustache
* it will be processed by the template engine. Otherwise, it will be copied
*/
supportingFiles.add(new SupportingFile("swagger.mustache",
"api",
"swagger.yaml")
);
supportingFiles.add(new SupportingFile("main.mustache", "", "main.go"));
supportingFiles.add(new SupportingFile("routers.mustache", apiPath, "routers.go"));
supportingFiles.add(new SupportingFile("logger.mustache", apiPath, "logger.go"));
supportingFiles.add(new SupportingFile("app.mustache", apiPath, "app.yaml"));
writeOptional(outputFolder, new SupportingFile("README.mustache", apiPath, "README.md"));
}
@Override
public String apiPackage() {
return apiPath;
}
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see io.swagger.codegen.CodegenType
*/
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -l flag.
*
* @return the friendly name for the generator
*/
@Override
public String getName() {
return "go-server";
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
@Override
public String getHelp() {
return "Generates a Go server library using the swagger-tools project. By default, " +
"it will also generate service classes--which you can disable with the `-Dnoservice` environment variable.";
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "DefaultController";
}
return initialCaps(name);
}
/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
* those terms here. This logic is only called if a variable matches the reseved words
*
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
}
/**
* Location to write api files. You can use the apiPackage() as defined when the class is
* instantiated
*/
@Override
public String apiFileFolder() {
return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar);
}
@Override
public String toModelName(String name) {
// camelize the model name
// phone_number => PhoneNumber
return camelize(toModelFilename(name));
}
@Override
public String toOperationId(String operationId) {
// method name cannot use reserved keyword, e.g. return
if (isReservedWord(operationId)) {
LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId)));
operationId = "call_" + operationId;
}
return camelize(operationId);
}
@Override
public String toModelFilename(String name) {
if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
name = name + "_" + modelNameSuffix;
}
name = sanitizeName(name);
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) {
LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name));
name = "model_" + name; // e.g. return => ModelReturn (after camelize)
}
return underscore(name);
}
@Override
public String toApiFilename(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// e.g. PetApi.go => pet_api.go
return underscore(name);
}
}

View File

@ -127,6 +127,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
CliOption dateLibrary = new CliOption(DATE_LIBRARY, "Option. Date library to use"); CliOption dateLibrary = new CliOption(DATE_LIBRARY, "Option. Date library to use");
Map<String, String> dateOptions = new HashMap<String, String>(); Map<String, String> dateOptions = new HashMap<String, String>();
dateOptions.put("java8", "Java 8 native"); dateOptions.put("java8", "Java 8 native");
dateOptions.put("java8-localdatetime", "Java 8 using LocalDateTime (for legacy app only)");
dateOptions.put("joda", "Joda"); dateOptions.put("joda", "Joda");
dateOptions.put("legacy", "Legacy java.util.Date"); dateOptions.put("legacy", "Legacy java.util.Date");
dateLibrary.setEnum(dateOptions); dateLibrary.setEnum(dateOptions);
@ -262,6 +263,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
writeOptional(outputFolder, new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); writeOptional(outputFolder, new SupportingFile("settings.gradle.mustache", "", "settings.gradle"));
writeOptional(outputFolder, new SupportingFile("gradle.properties.mustache", "", "gradle.properties")); writeOptional(outputFolder, new SupportingFile("gradle.properties.mustache", "", "gradle.properties"));
writeOptional(outputFolder, new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); writeOptional(outputFolder, new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml"));
supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java"));
supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java"));
@ -362,7 +364,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
} }
if(additionalProperties.containsKey(DATE_LIBRARY)) { if(additionalProperties.containsKey(DATE_LIBRARY)) {
this.dateLibrary = additionalProperties.get(DATE_LIBRARY).toString(); setDateLibrary(additionalProperties.get(DATE_LIBRARY).toString());
additionalProperties.put(dateLibrary, "true");
} }
if("joda".equals(dateLibrary)) { if("joda".equals(dateLibrary)) {
@ -372,13 +375,17 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
importMapping.put("LocalDate", "org.joda.time.LocalDate"); importMapping.put("LocalDate", "org.joda.time.LocalDate");
importMapping.put("DateTime", "org.joda.time.DateTime"); importMapping.put("DateTime", "org.joda.time.DateTime");
} }
else if ("java8".equals(dateLibrary)) { else if (dateLibrary.startsWith("java8")) {
additionalProperties.put("java8", "true"); additionalProperties.put("java8", "true");
additionalProperties.put("javaVersion", "1.8");
typeMapping.put("date", "LocalDate"); typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "LocalDateTime");
importMapping.put("LocalDate", "java.time.LocalDate"); importMapping.put("LocalDate", "java.time.LocalDate");
importMapping.put("LocalDateTime", "java.time.LocalDateTime"); if ("java8-localdatetime".equals(dateLibrary)) {
typeMapping.put("DateTime", "LocalDateTime");
importMapping.put("LocalDateTime", "java.time.LocalDateTime");
} else {
typeMapping.put("DateTime", "OffsetDateTime");
importMapping.put("OffsetDateTime", "java.time.OffsetDateTime");
}
} }
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
@ -1031,7 +1038,5 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
this.useRxJava = useRxJava; this.useRxJava = useRxJava;
} }
public void setDateLibrary(String library) { public void setDateLibrary(String library) { this.dateLibrary = library; }
this.dateLibrary = library;
}
} }

View File

@ -89,16 +89,11 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER); implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER);
} }
if (additionalProperties.containsKey("dateLibrary")) {
setDateLibrary(additionalProperties.get("dateLibrary").toString());
additionalProperties.put(dateLibrary, "true");
}
if ("joda".equals(dateLibrary)) { if ("joda".equals(dateLibrary)) {
supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java")); supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java"));
supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaLocalDateProvider.java")); supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaLocalDateProvider.java"));
} else if ( "java8".equals(dateLibrary) ) { } else if ( dateLibrary.startsWith("java8") ) {
supportingFiles.add(new SupportingFile("LocalDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateTimeProvider.java")); supportingFiles.add(new SupportingFile("OffsetDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "OffsetDateTimeProvider.java"));
supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java")); supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java"));
} }

View File

@ -47,14 +47,6 @@ public class JavaResteasyServerCodegen extends JavaClientCodegen implements Code
} }
} }
CliOption dateLibrary = new CliOption(DATE_LIBRARY, "Option. Date library to use");
Map<String, String> dateOptions = new HashMap<String, String>();
dateOptions.put("java8", "Java 8 native");
dateOptions.put("joda", "Joda");
dateLibrary.setEnum(dateOptions);
cliOptions.add(dateLibrary);
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);
@ -117,35 +109,16 @@ public class JavaResteasyServerCodegen extends JavaClientCodegen implements Code
supportingFiles.add(new SupportingFile("StringUtil.mustache", supportingFiles.add(new SupportingFile("StringUtil.mustache",
(sourceFolder + '/' + invokerPackage).replace(".", "/"), "StringUtil.java")); (sourceFolder + '/' + invokerPackage).replace(".", "/"), "StringUtil.java"));
if (additionalProperties.containsKey("dateLibrary")) {
setDateLibrary(additionalProperties.get("dateLibrary").toString());
additionalProperties.put(dateLibrary, "true");
}
if ("joda".equals(dateLibrary)) { if ("joda".equals(dateLibrary)) {
typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "DateTime");
importMapping.put("LocalDate", "org.joda.time.LocalDate");
importMapping.put("DateTime", "org.joda.time.DateTime");
supportingFiles.add(new SupportingFile("JacksonConfig.mustache", supportingFiles.add(new SupportingFile("JacksonConfig.mustache",
(sourceFolder + '/' + invokerPackage).replace(".", "/"), "JacksonConfig.java")); (sourceFolder + '/' + invokerPackage).replace(".", "/"), "JacksonConfig.java"));
supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache",
(sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java")); (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java"));
supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache",
(sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaLocalDateProvider.java")); (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaLocalDateProvider.java"));
} else if ("java8".equals(dateLibrary)) { } else if (dateLibrary.startsWith("java8")) {
additionalProperties.put("java8", "true"); supportingFiles.add(new SupportingFile("OffsetDateTimeProvider.mustache",
additionalProperties.put("javaVersion", "1.8"); (sourceFolder + '/' + apiPackage).replace(".", "/"), "OffsetDateTimeProvider.java"));
typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "LocalDateTime");
importMapping.put("LocalDate", "java.time.LocalDate");
importMapping.put("LocalDateTime", "java.time.LocalDateTime");
supportingFiles.add(new SupportingFile("LocalDateTimeProvider.mustache",
(sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateTimeProvider.java"));
supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", supportingFiles.add(new SupportingFile("LocalDateProvider.mustache",
(sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java")); (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java"));
} }

View File

@ -74,12 +74,16 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
protected boolean emitJSDoc = true; protected boolean emitJSDoc = true;
protected String apiDocPath = "docs/"; protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/"; protected String modelDocPath = "docs/";
protected String apiTestPath = "api/";
protected String modelTestPath = "model/";
public JavascriptClientCodegen() { public JavascriptClientCodegen() {
super(); super();
outputFolder = "generated-code/js"; outputFolder = "generated-code/js";
modelTemplateFiles.put("model.mustache", ".js"); modelTemplateFiles.put("model.mustache", ".js");
modelTestTemplateFiles.put("model_test.mustache", ".js");
apiTemplateFiles.put("api.mustache", ".js"); apiTemplateFiles.put("api.mustache", ".js");
apiTestTemplateFiles.put("api_test.mustache", ".js");
templateDir = "Javascript"; templateDir = "Javascript";
apiPackage = "api"; apiPackage = "api";
modelPackage = "model"; modelPackage = "model";
@ -292,6 +296,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
supportingFiles.add(new SupportingFile("ApiClient.mustache", createPath(sourceFolder, invokerPackage), "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"));
supportingFiles.add(new SupportingFile("mocha.opts", "", "mocha.opts"));
supportingFiles.add(new SupportingFile("travis.yml", "", ".travis.yml"));
} }
@Override @Override
@ -322,6 +328,16 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
return buf.toString(); return buf.toString();
} }
@Override
public String apiTestFileFolder() {
return (outputFolder + "/test/" + apiTestPath).replace('/', File.separatorChar);
}
@Override
public String modelTestFileFolder() {
return (outputFolder + "/test/" + modelTestPath).replace('/', File.separatorChar);
}
@Override @Override
public String apiFileFolder() { public String apiFileFolder() {
return createPath(outputFolder, sourceFolder, invokerPackage, apiPackage()); return createPath(outputFolder, sourceFolder, invokerPackage, apiPackage());
@ -400,6 +416,16 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
return toModelName(name); return toModelName(name);
} }
@Override
public String toApiTestFilename(String name) {
return toApiName(name) + ".spec";
}
@Override
public String toModelTestFilename(String name) {
return toModelName(name) + ".spec";
}
@Override @Override
public String toVarName(String name) { public String toVarName(String name) {
// sanitize name // sanitize name

View File

@ -9,8 +9,19 @@ import java.io.File;
public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig { public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig {
// source folder where to write the files // source folder where to write the files
protected String sourceFolder = "src"; protected String sourceFolder = "";
public static final String SRC_BASE_PATH = "srcBasePath";
public static final String COMPOSER_VENDOR_NAME = "composerVendorName";
public static final String COMPOSER_PROJECT_NAME = "composerProjectName";
protected String invokerPackage = "Swagger\\Client";
protected String composerVendorName = null;
protected String composerProjectName = null;
protected String packagePath = "SwaggerClient-php";
protected String artifactVersion = null;
protected String srcBasePath = "lib";
protected String apiVersion = "1.0.0"; protected String apiVersion = "1.0.0";
protected String apiDirName = "Api";
/** /**
* Configures the type of generator. * Configures the type of generator.
@ -46,13 +57,8 @@ public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig
super(); super();
// set the output folder here // set the output folder here
outputFolder = "generated-code/lumen"; outputFolder = "lumen";
String packagePath = "lumen"; String packagePath = "";
// modelPackage = packagePath + "\\lib\\Models";
// apiPackage = packagePath + "\\lib";
// // outputFolder = "generated-code" + File.separator + "slim";
// modelTemplateFiles.put("model.mustache", ".php");
/** /**
* Models. You can write model files using the modelTemplateFiles map. * Models. You can write model files using the modelTemplateFiles map.
@ -75,7 +81,8 @@ public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig
// no api files // no api files
apiTemplateFiles.clear(); // apiTemplateFiles.clear();
apiTemplateFiles.put("api.mustache", ".php");
// embeddedTemplateDir = templateDir = "slim"; // embeddedTemplateDir = templateDir = "slim";
@ -115,42 +122,17 @@ public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig
* entire object tree available. If the input file has a suffix of `.mustache * entire object tree available. If the input file has a suffix of `.mustache
* it will be processed by the template engine. Otherwise, it will be copied * it will be processed by the template engine. Otherwise, it will be copied
*/ */
// supportingFiles.add(new SupportingFile("index.mustache", packagePath, "index.php")); supportingFiles.add(new SupportingFile("composer.mustache", packagePath, "composer.json"));
// supportingFiles.add(new SupportingFile("routes.mustache", packagePath, "routes.php"));
supportingFiles.add(new SupportingFile("composer.json", packagePath, "composer.json"));
supportingFiles.add(new SupportingFile("readme.md", packagePath, "readme.md")); supportingFiles.add(new SupportingFile("readme.md", packagePath, "readme.md"));
supportingFiles.add(new SupportingFile("artisan", packagePath, "artisan")); supportingFiles.add(new SupportingFile("app.php", packagePath + File.separator + "bootstrap", "app.php"));
// supportingFiles.add(new SupportingFile("server.php", packagePath, "server.php")); supportingFiles.add(new SupportingFile("index.php", packagePath + File.separator + "public", "index.php"));
supportingFiles.add(new SupportingFile("User.php", packagePath + File.separator + "app", "User.php"));
supportingFiles.add(new SupportingFile("Kernel.php", packagePath + File.separator + "app" + File.separator + "Console", "Kernel.php"));
supportingFiles.add(new SupportingFile("Handler.php", packagePath + File.separator + "app" + File.separator + "Exceptions", "Handler.php"));
supportingFiles.add(new SupportingFile("routes.mustache", packagePath + File.separator + "app" + File.separator + "Http", "routes.php"));
supportingFiles.add(new SupportingFile("bootstrap" + File.separator + "app.php", packagePath + File.separator + "bootstrap", "app.php")); supportingFiles.add(new SupportingFile("Controller.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Controllers" + File.separator, "Controller.php"));
supportingFiles.add(new SupportingFile("Authenticate.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Middleware" + File.separator, "Authenticate.php"));
supportingFiles.add(new SupportingFile("public" + File.separator + "index.php", packagePath + File.separator + "public", "index.php"));
supportingFiles.add(new SupportingFile("app" + File.separator + "User.php", packagePath + File.separator + "app", "User.php"));
supportingFiles.add(new SupportingFile("app" + File.separator + "Console" + File.separator + "Kernel.php", packagePath + File.separator + "app" + File.separator + "Console", "Kernel.php"));
supportingFiles.add(new SupportingFile("app" + File.separator + "Exceptions" + File.separator + "Handler.php", packagePath + File.separator + "app" + File.separator + "Exceptions", "Handler.php"));
// supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "Kernel.php", packagePath + File.separator + "app" + File.separator + "Http", "Kernel.php"));
supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "routes.mustache", packagePath + File.separator + "app" + File.separator + "Http", "routes.php"));
supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "Controllers" + File.separator + "Controller.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Controllers" + File.separator, "Controller.php"));
supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "Controllers" + File.separator + "ExampleController.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Controllers" + File.separator, "ExampleController.php"));
// supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "Controllers" + File.separator + "Auth" + File.separator + "AuthController.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Controllers" + File.separator + "Auth" + File.separator, "AuthController.php"));
// supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "Controllers" + File.separator + "Auth" + File.separator + "PasswordController.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Controllers" + File.separator + "Auth" + File.separator, "PasswordController.php"));
supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "Middleware" + File.separator + "Authenticate.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Middleware" + File.separator, "Authenticate.php"));
supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "Middleware" + File.separator + "ExampleMiddleware.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Middleware" + File.separator, "ExampleMiddleware.php"));
// supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "Middleware" + File.separator + "RedirectIfAuthenticated.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Middleware" + File.separator, "RedirectIfAuthenticated.php"));
// supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "Middleware" + File.separator + "VerifyCsrfToken.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Middleware" + File.separator, "VerifyCsrfToken.php"));
// supportingFiles.add(new SupportingFile("app" + File.separator + "Http" + File.separator + "Requests" + File.separator + "Request.php", packagePath + File.separator + "app" + File.separator + "Http" + File.separator + "Requests" + File.separator, "Request.php"));
supportingFiles.add(new SupportingFile("app" + File.separator + "Providers" + File.separator + "AppServiceProvider.php", packagePath + File.separator + "app" + File.separator + "Providers", "AppServiceProvider.php"));
supportingFiles.add(new SupportingFile("app" + File.separator + "Providers" + File.separator + "AuthServiceProvider.php", packagePath + File.separator + "app" + File.separator + "Providers", "AuthServiceProvider.php"));
supportingFiles.add(new SupportingFile("app" + File.separator + "Providers" + File.separator + "EventServiceProvider.php", packagePath + File.separator + "app" + File.separator + "Providers", "EventServiceProvider.php"));
// supportingFiles.add(new SupportingFile("app" + File.separator + "Providers" + File.separator + "RouteServiceProvider.php", packagePath + File.separator + "app" + File.separator + "Providers", "RouteServiceProvider.php"));
// supportingFiles.add(new SupportingFile("config" + File.separator + "app.php", packagePath + File.separator + "config" + File.separator, "app.php"));
/** /**
* Language Specific Primitives. These types will not trigger imports by * Language Specific Primitives. These types will not trigger imports by
@ -188,7 +170,8 @@ public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig
*/ */
@Override @Override
public String apiFileFolder() { public String apiFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); return outputFolder + "/app/Http/controllers";
// return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar);
} }
/** /**

View File

@ -1,6 +1,7 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import io.swagger.codegen.*; import io.swagger.codegen.*;
import io.swagger.models.ArrayModel;
import io.swagger.models.Model; import io.swagger.models.Model;
import io.swagger.models.properties.*; import io.swagger.models.properties.*;
@ -94,7 +95,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.clear(); typeMapping.clear();
typeMapping.put("enum", "NSString"); typeMapping.put("enum", "NSString");
typeMapping.put("date", "NSDate"); typeMapping.put("date", "NSDate");
typeMapping.put("DateTime", "NSDate"); typeMapping.put("datetime", "NSDate");
typeMapping.put("boolean", "NSNumber"); typeMapping.put("boolean", "NSNumber");
typeMapping.put("string", "NSString"); typeMapping.put("string", "NSString");
typeMapping.put("integer", "NSNumber"); typeMapping.put("integer", "NSNumber");
@ -105,12 +106,15 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("array", "NSArray"); typeMapping.put("array", "NSArray");
typeMapping.put("map", "NSDictionary"); typeMapping.put("map", "NSDictionary");
typeMapping.put("number", "NSNumber"); typeMapping.put("number", "NSNumber");
typeMapping.put("bigdecimal", "NSNumber");
typeMapping.put("List", "NSArray"); typeMapping.put("List", "NSArray");
typeMapping.put("object", "NSObject"); typeMapping.put("object", "NSObject");
typeMapping.put("file", "NSURL"); typeMapping.put("file", "NSURL");
typeMapping.put("binary", "NSData"); typeMapping.put("binary", "NSData");
typeMapping.put("ByteArray", "NSData"); typeMapping.put("bytearray", "NSData");
typeMapping.put("byte", "NSData"); typeMapping.put("byte", "NSData");
typeMapping.put("uuid", "NSString");
typeMapping.put("password", "NSString");
// ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm
setReservedWordsLowerCase( setReservedWordsLowerCase(
@ -293,8 +297,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
public String getSwaggerType(Property p) { public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p); String swaggerType = super.getSwaggerType(p);
String type = null; String type = null;
if (typeMapping.containsKey(swaggerType)) { if (typeMapping.containsKey(swaggerType.toLowerCase())) {
type = typeMapping.get(swaggerType); type = typeMapping.get(swaggerType.toLowerCase());
if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) { if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) {
return toModelNameWithoutReservedWordCheck(type); return toModelNameWithoutReservedWordCheck(type);
} }
@ -304,15 +308,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
return toModelNameWithoutReservedWordCheck(type); return toModelNameWithoutReservedWordCheck(type);
} }
public CodegenProperty coreDatafromProperty(String name, Property p) {
CodegenProperty property = fromProperty(name, p);
if(!generateCoreData) {
return property;
}
property.baseType = getTypeCoreDataDeclaration(p);
return property;
}
@Override @Override
public String getTypeDeclaration(Property p) { public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) { if (p instanceof ArrayProperty) {
@ -377,73 +372,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
} }
} }
public String getTypeCoreDataDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
String innerType = getSwaggerType(inner);
String innerTypeDeclaration = getTypeDeclaration(inner);
if (innerTypeDeclaration.endsWith("*")) {
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
}
// In this codition, type of property p is array of primitive,
// return container type with pointer, e.g. `NSArray*<NSString*>*'
if (languageSpecificPrimitives.contains(innerTypeDeclaration)) {
return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*";
}
// In this codition, type of property p is array of model,
// return container type combine inner type with pointer, e.g. `NSArray<SWGTag>*'
else {
for (String sd : advancedMapingTypes) {
if(innerTypeDeclaration.startsWith(sd)) {
return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*";
}
}
return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*";
}
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
String innerTypeDeclaration = getTypeDeclaration(inner);
if (innerTypeDeclaration.endsWith("*")) {
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
}
if (languageSpecificPrimitives.contains(innerTypeDeclaration)) {
return getSwaggerType(p) + "<NSString*, " + innerTypeDeclaration + "*>*";
} else {
for (String s : advancedMapingTypes) {
if(innerTypeDeclaration.startsWith(s)) {
return getSwaggerType(p) + "<NSString*, " + innerTypeDeclaration + "*>*";
}
}
return getSwaggerType(p) + "<NSString*, " + innerTypeDeclaration + ">*";
}
} else {
String swaggerType = getSwaggerType(p);
// In this codition, type of p is objective-c primitive type, e.g. `NSSNumber',
// return type of p with pointer, e.g. `NSNumber*'
if (languageSpecificPrimitives.contains(swaggerType) &&
foundationClasses.contains(swaggerType)) {
return swaggerType + "*";
}
// In this codition, type of p is c primitive type, e.g. `bool',
// return type of p, e.g. `bool'
else if (languageSpecificPrimitives.contains(swaggerType)) {
return swaggerType;
}
// In this codition, type of p is objective-c object type, e.g. `SWGPet',
// return type of p with pointer, e.g. `SWGPet*'
else {
return swaggerType + "*";
}
}
}
@Override @Override
public boolean isDataTypeBinary(String dataType) { public boolean isDataTypeBinary(String dataType) {
return dataType.toLowerCase().startsWith("nsdata"); return dataType.toLowerCase().startsWith("nsdata");

View File

@ -167,6 +167,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
} }
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"));
supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml"));
} }
private static String dropDots(String str) { private static String dropDots(String str) {

View File

@ -104,8 +104,8 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + "Helpers.h")); supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + "Helpers.h"));
supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, PREFIX + "Helpers.cpp")); supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, PREFIX + "Helpers.cpp"));
supportingFiles.add(new SupportingFile("HttpRequest.h", sourceFolder, PREFIX + "HttpRequest.h")); supportingFiles.add(new SupportingFile("HttpRequest.h.mustache", sourceFolder, PREFIX + "HttpRequest.h"));
supportingFiles.add(new SupportingFile("HttpRequest.cpp", sourceFolder, PREFIX + "HttpRequest.cpp")); supportingFiles.add(new SupportingFile("HttpRequest.cpp.mustache", sourceFolder, PREFIX + "HttpRequest.cpp"));
supportingFiles.add(new SupportingFile("modelFactory.mustache", sourceFolder, PREFIX + "ModelFactory.h")); supportingFiles.add(new SupportingFile("modelFactory.mustache", sourceFolder, PREFIX + "ModelFactory.h"));
supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h")); supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h"));
@ -135,6 +135,9 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
systemIncludes.add("QString"); systemIncludes.add("QString");
systemIncludes.add("QList"); systemIncludes.add("QList");
systemIncludes.add("QMap");
systemIncludes.add("QDate");
systemIncludes.add("QDateTime");
} }
/** /**

View File

@ -86,7 +86,7 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("build.sbt", "", "build.sbt")); supportingFiles.add(new SupportingFile("build.sbt", "", "build.sbt"));
supportingFiles.add(new SupportingFile("web.xml", "/src/main/webapp/WEB-INF", "web.xml")); supportingFiles.add(new SupportingFile("web.xml", "/src/main/webapp/WEB-INF", "web.xml"));
supportingFiles.add(new SupportingFile("JettyMain.scala", sourceFolder, "JettyMain.scala")); supportingFiles.add(new SupportingFile("JettyMain.mustache", sourceFolder, "JettyMain.scala"));
supportingFiles.add(new SupportingFile("Bootstrap.mustache", sourceFolder, "ScalatraBootstrap.scala")); supportingFiles.add(new SupportingFile("Bootstrap.mustache", sourceFolder, "ScalatraBootstrap.scala"));
supportingFiles.add(new SupportingFile("ServletApp.mustache", sourceFolder, "ServletApp.scala")); supportingFiles.add(new SupportingFile("ServletApp.mustache", sourceFolder, "ServletApp.scala"));
supportingFiles.add(new SupportingFile("project/build.properties", "project", "build.properties")); supportingFiles.add(new SupportingFile("project/build.properties", "project", "build.properties"));

View File

@ -12,11 +12,15 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
public static final String BASE_PACKAGE = "basePackage"; public static final String BASE_PACKAGE = "basePackage";
public static final String INTERFACE_ONLY = "interfaceOnly"; public static final String INTERFACE_ONLY = "interfaceOnly";
public static final String SINGLE_CONTENT_TYPES = "singleContentTypes"; public static final String SINGLE_CONTENT_TYPES = "singleContentTypes";
public static final String JAVA_8 = "java8";
public static final String ASYNC = "async";
protected String title = "Petstore Server"; protected String title = "Petstore Server";
protected String configPackage = ""; protected String configPackage = "";
protected String basePackage = ""; protected String basePackage = "";
protected boolean interfaceOnly = false; protected boolean interfaceOnly = false;
protected boolean singleContentTypes = false; protected boolean singleContentTypes = false;
protected boolean java8 = false;
protected boolean async = false;
protected String templateFileName = "api.mustache"; protected String templateFileName = "api.mustache";
public SpringBootServerCodegen() { public SpringBootServerCodegen() {
@ -45,11 +49,14 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code")); cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code"));
cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files.")); cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files."));
cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation.")); cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation."));
cliOptions.add(CliOption.newBoolean(JAVA_8, "use java8 default interface"));
cliOptions.add(CliOption.newBoolean(ASYNC, "use async Callable controllers"));
supportedLibraries.clear(); supportedLibraries.clear();
supportedLibraries.put(DEFAULT_LIBRARY, "Default Spring Boot server stub."); 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 " + 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."); "declaration is useful when using Maven plugin. Just provide a implementation with @Controller to instantiate service." +
"(DEPRECATED: use -Djava8=true,async=true instead)");
} }
@Override @Override
@ -92,11 +99,19 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get(SINGLE_CONTENT_TYPES).toString())); this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get(SINGLE_CONTENT_TYPES).toString()));
} }
if (additionalProperties.containsKey(JAVA_8)) {
this.setJava8(Boolean.valueOf(additionalProperties.get(JAVA_8).toString()));
}
if (additionalProperties.containsKey(ASYNC)) {
this.setAsync(Boolean.valueOf(additionalProperties.get(ASYNC).toString()));
}
supportingFiles.clear(); supportingFiles.clear();
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
if(!this.interfaceOnly) { if (!this.interfaceOnly) {
apiTemplateFiles.put("apiController.mustache", "Controller.java"); apiTemplateFiles.put("apiController.mustache", "Controller.java");
supportingFiles.add(new SupportingFile("apiException.mustache", supportingFiles.add(new SupportingFile("apiException.mustache",
(sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java")); (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java"));
@ -115,6 +130,19 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
supportingFiles.add(new SupportingFile("application.properties", supportingFiles.add(new SupportingFile("application.properties",
("src.main.resources").replace(".", java.io.File.separator), "application.properties")); ("src.main.resources").replace(".", java.io.File.separator), "application.properties"));
} }
if ("j8-async".equals(getLibrary())) {
setJava8(true);
setAsync(true);
}
if (this.java8) {
additionalProperties.put("javaVersion", "1.8");
typeMapping.put("date", "LocalDate");
typeMapping.put("DateTime", "OffsetDateTime");
importMapping.put("LocalDate", "java.time.LocalDate");
importMapping.put("OffsetDateTime", "java.time.OffsetDateTime");
}
} }
@Override @Override
@ -228,23 +256,6 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
} }
} }
} }
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; return objs;
} }
@ -266,14 +277,16 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
this.basePackage = configPackage; this.basePackage = configPackage;
} }
public void setInterfaceOnly(boolean interfaceOnly) { public void setInterfaceOnly(boolean interfaceOnly) { this.interfaceOnly = interfaceOnly; }
this.interfaceOnly = interfaceOnly;
}
public void setSingleContentTypes(boolean singleContentTypes) { public void setSingleContentTypes(boolean singleContentTypes) {
this.singleContentTypes = singleContentTypes; this.singleContentTypes = singleContentTypes;
} }
public void setJava8(boolean java8) { this.java8 = java8; }
public void setAsync(boolean async) { this.async = async; }
@Override @Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) { public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// remove the import of "Object" to avoid compilation error // remove the import of "Object" to avoid compilation error

View File

@ -13,3 +13,9 @@
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid* hs_err_pid*
# build files
**/target
target
.gradle
build

View File

@ -0,0 +1,29 @@
#
# Generated by: https://github.com/swagger-api/swagger-codegen.git
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
language: java
jdk:
- oraclejdk8
- oraclejdk7
before_install:
# ensure gradlew has proper permission
- chmod a+x ./gradlew
script:
# test using maven
- mvn test
# uncomment below to test using gradle
# - gradle test
# uncomment below to test using sbt
# - sbt test

View File

@ -18,6 +18,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
{{>enumClass}}{{/items}}{{/items.isEnum}} {{>enumClass}}{{/items}}{{/items.isEnum}}
@XmlElement(name="{{baseName}}")
private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}}
{{#vars}} {{#vars}}

View File

@ -11,23 +11,23 @@ import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider; import javax.ws.rs.ext.Provider;
import java.time.LocalDateTime; import java.time.OffsetDateTime;
import java.util.List; import java.util.List;
@Provider @Provider
public class LocalDateTimeProvider extends PerRequestTypeInjectableProvider<QueryParam, LocalDateTime> { public class OffsetDateTimeProvider extends PerRequestTypeInjectableProvider<QueryParam, OffsetDateTime> {
private final UriInfo uriInfo; private final UriInfo uriInfo;
public LocalDateTimeProvider(@Context UriInfo uriInfo) { public OffsetDateTimeProvider(@Context UriInfo uriInfo) {
super(LocalDateTime.class); super(OffsetDateTime.class);
this.uriInfo = uriInfo; this.uriInfo = uriInfo;
} }
@Override @Override
public Injectable<LocalDateTime> getInjectable(final ComponentContext cc, final QueryParam a) { public Injectable<OffsetDateTime> getInjectable(final ComponentContext cc, final QueryParam a) {
return new Injectable<LocalDateTime>() { return new Injectable<OffsetDateTime>() {
@Override @Override
public LocalDateTime getValue() { public OffsetDateTime getValue() {
final List<String> values = uriInfo.getQueryParameters().get(a.value()); final List<String> values = uriInfo.getQueryParameters().get(a.value());
if (values == null || values.isEmpty()) if (values == null || values.isEmpty())
@ -37,7 +37,7 @@ public class LocalDateTimeProvider extends PerRequestTypeInjectableProvider<Quer
entity(a.value() + " cannot contain multiple values").build()); entity(a.value() + " cannot contain multiple values").build());
} }
return LocalDateTime.parse(values.get(0)); return OffsetDateTime.parse(values.get(0));
} }
}; };
} }

View File

@ -11,23 +11,23 @@ import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider; import javax.ws.rs.ext.Provider;
import java.time.LocalDateTime; import java.time.OffsetDateTime;
import java.util.List; import java.util.List;
@Provider @Provider
public class LocalDateTimeProvider extends PerRequestTypeInjectableProvider<QueryParam, LocalDateTime> { public class OffsetDateTimeProvider extends PerRequestTypeInjectableProvider<QueryParam, OffsetDateTime> {
private final UriInfo uriInfo; private final UriInfo uriInfo;
public LocalDateTimeProvider(@Context UriInfo uriInfo) { public OffsetDateTimeProvider(@Context UriInfo uriInfo) {
super(LocalDateTime.class); super(OffsetDateTime.class);
this.uriInfo = uriInfo; this.uriInfo = uriInfo;
} }
@Override @Override
public Injectable<LocalDateTime> getInjectable(final ComponentContext cc, final QueryParam a) { public Injectable<OffsetDateTime> getInjectable(final ComponentContext cc, final QueryParam a) {
return new Injectable<LocalDateTime>() { return new Injectable<OffsetDateTime>() {
@Override @Override
public LocalDateTime getValue() { public OffsetDateTime getValue() {
final List<String> values = uriInfo.getQueryParameters().get(a.value()); final List<String> values = uriInfo.getQueryParameters().get(a.value());
if (values == null || values.isEmpty()) if (values == null || values.isEmpty())
@ -37,7 +37,7 @@ public class LocalDateTimeProvider extends PerRequestTypeInjectableProvider<Quer
entity(a.value() + " cannot contain multiple values").build()); entity(a.value() + " cannot contain multiple values").build());
} }
return LocalDateTime.parse(values.get(0)); return OffsetDateTime.parse(values.get(0));
} }
}; };
} }

View File

@ -1,34 +0,0 @@
package {{apiPackage}};
import java.time.LocalDateTime;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
@Provider
public class LocalDateTimeProvider implements ParamConverterProvider {
public static class LocalDateTimeConverter implements ParamConverter<LocalDateTime> {
@Override
public LocalDateTime fromString(String string) {
LocalDateTime localDateTime = LocalDateTime.parse(string);
return localDateTime;
}
@Override
public String toString(LocalDateTime t) {
return t.toString();
}
}
@Override
public <T> ParamConverter<T> getConverter(Class<T> type, Type type1, Annotation[] antns) {
if (LocalDateTime.class.equals(type)) {
return (ParamConverter<T>) new LocalDateTimeConverter();
}
return null;
}
}

View File

@ -0,0 +1,34 @@
package {{apiPackage}};
import java.time.OffsetDateTime;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
@Provider
public class OffsetDateTimeProvider implements ParamConverterProvider {
public static class OffsetDateTimeConverter implements ParamConverter<OffsetDateTime> {
@Override
public OffsetDateTime fromString(String string) {
OffsetDateTime OffsetDateTime = OffsetDateTime.parse(string);
return OffsetDateTime;
}
@Override
public String toString(OffsetDateTime t) {
return t.toString();
}
}
@Override
public <T> ParamConverter<T> getConverter(Class<T> type, Type type1, Annotation[] antns) {
if (OffsetDateTime.class.equals(type)) {
return (ParamConverter<T>) new OffsetDateTimeConverter();
}
return null;
}
}

View File

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

View File

@ -1,7 +1,6 @@
package {{apiPackage}}; package {{apiPackage}};
import {{modelPackage}}.*; {{^java8}}
{{#imports}}import {{import}}; {{#imports}}import {{import}};
{{/imports}} {{/imports}}
@ -9,7 +8,9 @@ import io.swagger.annotations.*;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
{{/java8}}
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
{{^java8}}
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestHeader;
@ -18,18 +19,26 @@ import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.util.List; import java.util.List;
{{#async}}
import java.util.concurrent.Callable;
{{/async}}{{/java8}}
@Controller
{{>generatedAnnotation}} {{>generatedAnnotation}}
@Controller
{{#operations}} {{#operations}}
public class {{classname}}Controller implements {{classname}} { public class {{classname}}Controller implements {{classname}} {
{{#operation}} {{^java8}}{{#operation}}
public ResponseEntity<{{>returnTypes}}> {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, public {{#async}}Callable<{{/async}}ResponseEntity<{{>returnTypes}}>{{#async}}>{{/async}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},
{{/hasMore}}{{/allParams}}) { {{/hasMore}}{{/allParams}}) {
// do some magic! // do some magic!{{^async}}
return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK); return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK);{{/async}}{{#async}}
} return new Callable<ResponseEntity<{{>returnTypes}}>>() {
@Override
{{/operation}} public ResponseEntity<{{>returnTypes}}> call() throws Exception {
return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK);
}
};{{/async}}
}
{{/operation}}{{/java8}}
} }
{{/operations}} {{/operations}}

View File

@ -1,63 +1,78 @@
<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"> <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> <modelVersion>4.0.0</modelVersion>
<groupId>{{groupId}}</groupId> <groupId>{{groupId}}</groupId>
<artifactId>{{artifactId}}</artifactId> <artifactId>{{artifactId}}</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>{{artifactId}}</name> <name>{{artifactId}}</name>
<version>{{artifactVersion}}</version> <version>{{artifactVersion}}</version>
<properties> <properties>
<springfox-version>2.4.0</springfox-version> <springfox-version>2.4.0</springfox-version>
</properties> {{#java8}}
<parent> <maven.compiler.source>1.8</maven.compiler.source>
<groupId>org.springframework.boot</groupId> <maven.compiler.target>1.8</maven.compiler.target>
<artifactId>spring-boot-starter-parent</artifactId> {{/java8}}
<version>1.3.3.RELEASE</version> </properties>
</parent> <parent>
<build> <groupId>org.springframework.boot</groupId>
<sourceDirectory>src/main/java</sourceDirectory>{{^interfaceOnly}} <artifactId>spring-boot-starter-parent</artifactId>
<plugins> <version>1.3.3.RELEASE</version>
<plugin> </parent>
<groupId>org.springframework.boot</groupId> <build>
<artifactId>spring-boot-maven-plugin</artifactId> <sourceDirectory>src/main/java</sourceDirectory>
<executions> {{^interfaceOnly}}
<execution> <plugins>
<goals> <plugin>
<goal>repackage</goal> <groupId>org.springframework.boot</groupId>
</goals> <artifactId>spring-boot-maven-plugin</artifactId>
</execution> <executions>
</executions> <execution>
</plugin> <goals>
</plugins>{{/interfaceOnly}} <goal>repackage</goal>
</build> </goals>
<dependencies> </execution>
<dependency> </executions>
<groupId>org.springframework.boot</groupId> </plugin>
<artifactId>spring-boot-starter-web</artifactId> </plugins>
</dependency> {{/interfaceOnly}}
<dependency> </build>
<groupId>org.springframework.boot</groupId> <dependencies>
<artifactId>spring-boot-starter-tomcat</artifactId> <dependency>
<scope>provided</scope> <groupId>org.springframework.boot</groupId>
</dependency> <artifactId>spring-boot-starter-web</artifactId>
<!--SpringFox dependencies --> </dependency>
<dependency> <dependency>
<groupId>io.springfox</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>springfox-swagger2</artifactId> <artifactId>spring-boot-starter-tomcat</artifactId>
<version>${springfox-version}</version> <scope>provided</scope>
</dependency> </dependency>
<dependency> <!--SpringFox dependencies -->
<groupId>io.springfox</groupId> <dependency>
<artifactId>springfox-swagger-ui</artifactId> <groupId>io.springfox</groupId>
<version>${springfox-version}</version> <artifactId>springfox-swagger2</artifactId>
</dependency> <version>${springfox-version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${springfox-version}</version>
</dependency>
{{#java8}}
<dependency> <dependency>
<groupId>com.fasterxml.jackson.datatype</groupId> <groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId> <artifactId>jackson-datatype-jsr310</artifactId>
</dependency> </dependency>
<dependency> {{/java8}}
<groupId>joda-time</groupId> {{^java8}}
<artifactId>joda-time</artifactId>
</dependency> <dependency>
</dependencies> <groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
{{/java8}}
</dependencies>
</project> </project>

View File

@ -30,13 +30,15 @@ public class SwaggerDocumentationConfig {
@Bean @Bean
public Docket customImplementation(){ public Docket customImplementation(){
return new Docket(DocumentationType.SWAGGER_2) return new Docket(DocumentationType.SWAGGER_2)
.select() .select()
.apis(RequestHandlerSelectors.basePackage("{{apiPackage}}")) .apis(RequestHandlerSelectors.basePackage("{{apiPackage}}"))
.build() .build(){{#java8}}
.directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class) .directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class)
.directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class) .directModelSubstitute(java.time.OffsetDateTime.class, java.util.Date.class){{/java8}}{{^java8}}
.apiInfo(apiInfo()); .directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class)
.directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class){{/java8}}
.apiInfo(apiInfo());
} }
} }

View File

@ -1,3 +1,4 @@
{{>licenseInfo}}
(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.

View File

@ -1,3 +1,4 @@
{{>licenseInfo}}
{{=< >=}}(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.

View File

@ -0,0 +1,55 @@
{{>licenseInfo}}
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD.
define(['expect.js', '../../src/index'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
factory(require('expect.js'), require('../../src/index'));
} else {
// Browser globals (root is window)
factory(root.expect, root.{{moduleName}});
}
}(this, function(expect, {{moduleName}}) {
'use strict';
var instance;
beforeEach(function() {
instance = new {{moduleName}}.{{classname}}();
});
var getProperty = function(object, getter, property) {
// Use getter method if present; otherwise, get the property directly.
if (typeof object[getter] === 'function')
return object[getter]();
else
return object[property];
}
var setProperty = function(object, setter, property, value) {
// Use setter method if present; otherwise, set the property directly.
if (typeof object[setter] === 'function')
object[setter](value);
else
object[property] = value;
}
describe('{{classname}}', function() {
{{#operations}}
{{#operation}}
describe('{{operationId}}', function() {
it('should call {{operationId}} successfully', function(done) {
//uncomment below and update the code to test {{operationId}}
//instance.{{operationId}}(pet, function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
{{/operation}}
{{/operations}}
});
}));

View File

@ -1,3 +1,4 @@
{{>licenseInfo}}
(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.

View File

@ -0,0 +1,23 @@
/**
* {{{appName}}}
* {{{appDescription}}}
*
* {{#version}}OpenAPI spec version: {{{version}}}{{/version}}
* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}}
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

View File

@ -0,0 +1 @@
--timeout 10000

View File

@ -1,3 +1,4 @@
{{>licenseInfo}}
(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.

View File

@ -0,0 +1,65 @@
{{>licenseInfo}}
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD.
define(['expect.js', '../../src/index'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
factory(require('expect.js'), require('../../src/index'));
} else {
// Browser globals (root is window)
factory(root.expect, root.{{moduleName}});
}
}(this, function(expect, {{moduleName}}) {
'use strict';
var instance;
beforeEach(function() {
{{#models}}
{{#model}}
{{^isEnum}}
instance = new {{moduleName}}.{{classname}}();
{{/isEnum}}
{{/model}}
{{/models}}
});
var getProperty = function(object, getter, property) {
// Use getter method if present; otherwise, get the property directly.
if (typeof object[getter] === 'function')
return object[getter]();
else
return object[property];
}
var setProperty = function(object, setter, property, value) {
// Use setter method if present; otherwise, set the property directly.
if (typeof object[setter] === 'function')
object[setter](value);
else
object[property] = value;
}
describe('{{classname}}', function() {
it('should create an instance of {{classname}}', function() {
// uncomment below and update the code to test {{classname}}
//var instane = new {{moduleName}}.{{classname}}();
//expect(instance).to.be.a({{moduleName}}.{{classname}});
});
{{#models}}
{{#model}}
{{#vars}}
it('should have the property {{name}} (base name: "{{baseName}}")', function() {
// uncomment below and update the code to test the property {{name}}
//var instane = new {{moduleName}}.{{classname}}();
//expect(instance).to.be();
});
{{/vars}}
{{/model}}
{{/models}}
});
}));

View File

@ -0,0 +1,7 @@
language: node_js
node_js:
- "6"
- "6.1"
- "5"
- "5.11"

View File

@ -2,6 +2,7 @@ io.swagger.codegen.languages.AndroidClientCodegen
io.swagger.codegen.languages.AspNet5ServerCodegen io.swagger.codegen.languages.AspNet5ServerCodegen
io.swagger.codegen.languages.AsyncScalaClientCodegen io.swagger.codegen.languages.AsyncScalaClientCodegen
io.swagger.codegen.languages.CSharpClientCodegen io.swagger.codegen.languages.CSharpClientCodegen
io.swagger.codegen.languages.CppRestClientCodegen
io.swagger.codegen.languages.DartClientCodegen io.swagger.codegen.languages.DartClientCodegen
io.swagger.codegen.languages.FlashClientCodegen io.swagger.codegen.languages.FlashClientCodegen
io.swagger.codegen.languages.FlaskConnexionCodegen io.swagger.codegen.languages.FlaskConnexionCodegen
@ -46,3 +47,4 @@ io.swagger.codegen.languages.CsharpDotNet2ClientCodegen
io.swagger.codegen.languages.ClojureClientCodegen io.swagger.codegen.languages.ClojureClientCodegen
io.swagger.codegen.languages.HaskellServantCodegen io.swagger.codegen.languages.HaskellServantCodegen
io.swagger.codegen.languages.LumenServerCodegen io.swagger.codegen.languages.LumenServerCodegen
io.swagger.codegen.languages.GoServerCodegen

View File

@ -14,7 +14,7 @@
# You can recursively match patterns against a directory, file or extension with a double asterisk (**): # You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux #foo/**/qux
# Thsi matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux # This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!). # You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md: # For example, you can ignore all files in a docs folder with the file extension .md:

View File

@ -34,11 +34,17 @@ public class DeleteRequest extends Request<String> {
@Override @Override
public String getBodyContentType() { public String getBodyContentType() {
if(entity == null) {
return null;
}
return entity.getContentType().getValue(); return entity.getContentType().getValue();
} }
@Override @Override
public byte[] getBody() throws AuthFailureError { public byte[] getBody() throws AuthFailureError {
if(entity == null) {
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
try { try {
entity.writeTo(bos); entity.writeTo(bos);

View File

@ -34,11 +34,17 @@ public class PatchRequest extends Request<String> {
@Override @Override
public String getBodyContentType() { public String getBodyContentType() {
if(entity == null) {
return null;
}
return entity.getContentType().getValue(); return entity.getContentType().getValue();
} }
@Override @Override
public byte[] getBody() throws AuthFailureError { public byte[] getBody() throws AuthFailureError {
if(entity == null) {
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
try { try {
entity.writeTo(bos); entity.writeTo(bos);

View File

@ -34,11 +34,17 @@ public class PostRequest extends Request<String> {
@Override @Override
public String getBodyContentType() { public String getBodyContentType() {
if(entity == null) {
return null;
}
return entity.getContentType().getValue(); return entity.getContentType().getValue();
} }
@Override @Override
public byte[] getBody() throws AuthFailureError { public byte[] getBody() throws AuthFailureError {
if(entity == null) {
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
try { try {
entity.writeTo(bos); entity.writeTo(bos);

View File

@ -34,11 +34,17 @@ public class PutRequest extends Request<String> {
@Override @Override
public String getBodyContentType() { public String getBodyContentType() {
if(entity == null) {
return null;
}
return entity.getContentType().getValue(); return entity.getContentType().getValue();
} }
@Override @Override
public byte[] getBody() throws AuthFailureError { public byte[] getBody() throws AuthFailureError {
if(entity == null) {
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
try { try {
entity.writeTo(bos); entity.writeTo(bos);

View File

@ -0,0 +1,48 @@
{{#operations}}/*
* {{classname}}.h
*
* {{description}}
*/
#ifndef {{classname}}_H_
#define {{classname}}_H_
{{{defaultInclude}}}
#include "ApiClient.h"
{{#imports}}{{{import}}}
{{/imports}}
{{#apiNamespaceDeclarations}}
namespace {{this}} {
{{/apiNamespaceDeclarations}}
using namespace {{modelNamespace}};
class {{declspec}} {{classname}}
{
public:
{{classname}}( std::shared_ptr<ApiClient> apiClient );
virtual ~{{classname}}();
{{#operation}}
/// <summary>
/// {{summary}}
/// </summary>
/// <remarks>
/// {{notes}}
/// </remarks>
{{#allParams}}/// <param name="{{paramName}}">{{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}</param>{{/allParams}}
pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
{{/operation}}
protected:
std::shared_ptr<ApiClient> m_ApiClient;
};
{{#apiNamespaceDeclarations}}
}
{{/apiNamespaceDeclarations}}
#endif /* {{classname}}_H_ */
{{/operations}}

View File

@ -0,0 +1,269 @@
{{#operations}}
#include "{{classname}}.h"
#include "IHttpBody.h"
#include "JsonBody.h"
#include "MultipartFormData.h"
#include <unordered_set>
#include <boost/algorithm/string/replace.hpp>
{{#apiNamespaceDeclarations}}
namespace {{this}} {
{{/apiNamespaceDeclarations}}
using namespace {{modelNamespace}};
{{classname}}::{{classname}}( std::shared_ptr<ApiClient> apiClient )
: m_ApiClient(apiClient)
{
}
{{classname}}::~{{classname}}()
{
}
{{#operation}}
pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> {{classname}}::{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
{
{{#allParams}}{{#required}}{{^isPrimitiveType}}{{^isContainer}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == nullptr)
{
throw ApiException(400, U("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"));
}
{{/isContainer}}{{/isPrimitiveType}}{{/required}}{{/allParams}}
std::shared_ptr<ApiConfiguration> apiConfiguration( m_ApiClient->getConfiguration() );
utility::string_t path = U("{{path}}");
{{#pathParams}}boost::replace_all(path, U("{") U("{{baseName}}") U("}"), ApiClient::parameterToString({{{paramName}}}));
{{/pathParams}}
std::map<utility::string_t, utility::string_t> queryParams;
std::map<utility::string_t, utility::string_t> headerParams( apiConfiguration->getDefaultHeaders() );
std::map<utility::string_t, utility::string_t> formParams;
std::map<utility::string_t, std::shared_ptr<HttpContent>> fileParams;
std::unordered_set<utility::string_t> responseHttpContentTypes;
{{#produces}}responseHttpContentTypes.insert( U("{{mediaType}}") );
{{/produces}}
utility::string_t responseHttpContentType;
// use JSON if possible
if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() )
{
responseHttpContentType = U("application/json");
}
// multipart formdata
else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() )
{
responseHttpContentType = U("multipart/form-data");
}
else
{
throw ApiException(400, U("{{classname}}->{{operationId}} does not produce any supported media type"));
}
headerParams[U("Accept")] = responseHttpContentType;
std::unordered_set<utility::string_t> consumeHttpContentTypes;
{{#consumes}}consumeHttpContentTypes.insert( U("{{mediaType}}") );
{{/consumes}}
{{#allParams}}{{^isBodyParam}}{{^isPrimitiveType}}{{^isContainer}}if ({{paramName}} != nullptr){{/isContainer}}{{/isPrimitiveType}}
{
{{#isContainer}}{{#isQueryParam}}queryParams[U("{{baseName}}")] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}});
{{/isQueryParam}}{{#isHeaderParam}}headerParams[U("{{baseName}}")] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}});
{{/isHeaderParam}}{{#isFormParam}}{{^isFile}}formParams[ U("{{baseName}}") ] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}});
{{/isFile}}{{/isFormParam}}{{/isContainer}}{{^isContainer}}{{#isQueryParam}}queryParams[U("{{baseName}}")] = ApiClient::parameterToString({{paramName}});
{{/isQueryParam}}{{#isHeaderParam}}headerParams[U("{{baseName}}")] = ApiClient::parameterToString({{paramName}});
{{/isHeaderParam}}{{#isFormParam}}{{#isFile}}fileParams[ U("{{baseName}}") ] = {{paramName}};
{{/isFile}}{{^isFile}}formParams[ U("{{baseName}}") ] = ApiClient::parameterToString({{paramName}});
{{/isFile}}{{/isFormParam}}{{/isContainer}}
}
{{/isBodyParam}}{{/allParams}}
std::shared_ptr<IHttpBody> httpBody;
utility::string_t requestHttpContentType;
// use JSON if possible
if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() )
{
requestHttpContentType = U("application/json");
{{#bodyParam}}
web::json::value json;
{{#isPrimitiveType}} json = ModelBase::toJson({{paramName}});
{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}}
{
std::vector<web::json::value> jsonArray;
for( auto& item : {{paramName}} )
{
{{#items.isPrimitiveType}}jsonArray.push_back(ModelBase::toJson(item));
{{/items.isPrimitiveType}}{{^items.isPrimitiveType}}{{#items.isString}}jsonArray.push_back(ModelBase::toJson(item));
{{/items.isString}}{{^items.isString}}{{#items.isDateTime}}jsonArray.push_back(ModelBase::toJson(item));
{{/items.isDateTime}}{{^items.isDateTime}}jsonArray.push_back( item.get() ? item->toJson() : web::json::value::null() );
{{/items.isDateTime}}{{/items.isString}}{{/items.isPrimitiveType}}
}
json = web::json::value::array(jsonArray);
}
{{/isListContainer}}{{^isListContainer}}json = ModelBase::toJson({{paramName}});
{{/isListContainer}}{{/isPrimitiveType}}
httpBody = std::shared_ptr<IHttpBody>( new JsonBody( json ) );
{{/bodyParam}}
}
// multipart formdata
else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() )
{
requestHttpContentType = U("multipart/form-data");
{{#bodyParam}}
std::shared_ptr<MultipartFormData> multipart(new MultipartFormData);
{{#isPrimitiveType}} multipart->add(ModelBase::toHttpContent("{{paramName}}", {{paramName}}));
{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}}
{
std::vector<web::json::value> jsonArray;
for( auto& item : {{paramName}} )
{
{{#items.isPrimitiveType}}jsonArray.push_back(ModelBase::toJson(item));
{{/items.isPrimitiveType}}{{^items.isPrimitiveType}}{{#items.isString}}jsonArray.push_back(ModelBase::toJson(item));
{{/items.isString}}{{^items.isString}}{{#items.isDateTime}}jsonArray.push_back(ModelBase::toJson(item));
{{/items.isDateTime}}{{^items.isDateTime}}jsonArray.push_back( item.get() ? item->toJson() : web::json::value::null() );
{{/items.isDateTime}}{{/items.isString}}{{/items.isPrimitiveType}}
}
multipart->add(ModelBase::toHttpContent(U("{{paramName}}"), web::json::value::array(jsonArray), U("application/json")));
}
{{/isListContainer}}{{^isListContainer}}{{#isString}}multipart->add(ModelBase::toHttpContent(U("{{paramName}}"), {{paramName}}));
{{/isString}}{{^isString}}
if({{paramName}}.get())
{
{{paramName}}->toMultipart(multipart, U("{{paramName}}"));
}
{{/isString}}{{/isListContainer}}{{/isPrimitiveType}}
httpBody = multipart;
requestHttpContentType += U("; boundary=") + multipart->getBoundary();
{{/bodyParam}}
}
else
{
throw ApiException(415, U("{{classname}}->{{operationId}} does not consume any supported media type"));
}
{{#authMethods}}
// authentication ({{name}}) required
{{#isApiKey}}
{{#isKeyInHeader}}
{
utility::string_t apiKey = apiConfiguration->getApiKey(U("{{keyParamName}}"));
if ( apiKey.size() > 0 )
{
headerParams[U("{{keyParamName}}")] = apiKey;
}
}
{{/isKeyInHeader}}
{{#isKeyInQuery}}
{
utility::string_t apiKey = apiConfiguration->getApiKey(U("{{keyParamName}}"));
if ( apiKey.size() > 0 )
{
queryParams[U("{{keyParamName}}")] = apiKey;
}
}
{{/isKeyInQuery}}
{{/isApiKey}}
{{#isBasic}}
// Basic authentication is added automatically as part of the http_client_config
{{/isBasic}}
{{#isOAuth}}
// oauth2 authentication is added automatically as part of the http_client_config
{{/isOAuth}}
{{/authMethods}}
return m_ApiClient->callApi(path, U("{{httpMethod}}"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType)
.then([=](web::http::http_response response)
{
// 1xx - informational : OK
// 2xx - successful : OK
// 3xx - redirection : OK
// 4xx - client error : not OK
// 5xx - client error : not OK
if (response.status_code() >= 400)
{
throw ApiException(response.status_code()
, U("error calling {{operationId}}: ") + response.reason_phrase()
, std::make_shared<std::stringstream>(response.extract_utf8string(true).get()));
}
// check response content type
if(response.headers().has(U("Content-Type")))
{
utility::string_t contentType = response.headers()[U("Content-Type")];
if( contentType.find(responseHttpContentType) == std::string::npos )
{
throw ApiException(500
, U("error calling {{operationId}}: unexpected response type: ") + contentType
, std::make_shared<std::stringstream>(response.extract_utf8string(true).get()));
}
}
return response.extract_string();
})
.then([=](utility::string_t response)
{
{{^returnType}}return void();
{{/returnType}}{{#returnType}}{{#returnContainer}}{{{returnType}}} result;
{{/returnContainer}}{{^returnContainer}}{{{returnType}}} result({{{defaultResponse}}});{{/returnContainer}}
if(responseHttpContentType == U("application/json"))
{
web::json::value json = web::json::value::parse(response);
{{#isListContainer}}for( auto& item : json.as_array() )
{
{{#vendorExtensions.x-codegen-response.items.isPrimitiveType}}result.push_back(ModelBase::{{vendorExtensions.x-codegen-response.items.datatype}}FromJson(item));
{{/vendorExtensions.x-codegen-response.items.isPrimitiveType}}{{^vendorExtensions.x-codegen-response.items.isPrimitiveType}}{{#vendorExtensions.x-codegen-response.items.isString}}result.push_back(ModelBase::stringFromJson(item));
{{/vendorExtensions.x-codegen-response.items.isString}}{{^vendorExtensions.x-codegen-response.items.isString}}{{{vendorExtensions.x-codegen-response.items.datatype}}} itemObj({{{vendorExtensions.x-codegen-response.items.defaultValue}}});
itemObj->fromJson(item);
result.push_back(itemObj);
{{/vendorExtensions.x-codegen-response.items.isString}}{{/vendorExtensions.x-codegen-response.items.isPrimitiveType}}
}
{{/isListContainer}}{{^isListContainer}}{{#isMapContainer}}for( auto& item : json.as_object() )
{
{{#vendorExtensions.x-codegen-response.items.isPrimitiveType}}result[item.first] = ModelBase::{{vendorExtensions.x-codegen-response.items.datatype}}FromJson(item.second);
{{/vendorExtensions.x-codegen-response.items.isPrimitiveType}}{{^vendorExtensions.x-codegen-response.items.isPrimitiveType}}{{#vendorExtensions.x-codegen-response.items.isString}}result[item.first] = ModelBase::stringFromJson(item.second);
{{/vendorExtensions.x-codegen-response.items.isString}}{{^vendorExtensions.x-codegen-response.items.isString}}{{{vendorExtensions.x-codegen-response.items.datatype}}} itemObj({{{vendorExtensions.x-codegen-response.items.defaultValue}}});
itemObj->fromJson(item);
result[item.first] = itemObj;
{{/vendorExtensions.x-codegen-response.items.isString}}{{/vendorExtensions.x-codegen-response.items.isPrimitiveType}}
}
{{/isMapContainer}}{{^isMapContainer}}{{#vendorExtensions.x-codegen-response.isPrimitiveType}}result = ModelBase::{{vendorExtensions.x-codegen-response.items.datatype}}FromJson(json);
{{/vendorExtensions.x-codegen-response.isPrimitiveType}}{{^vendorExtensions.x-codegen-response.isPrimitiveType}}{{#vendorExtensions.x-codegen-response.isString}}result = ModelBase::stringFromJson(json);
{{/vendorExtensions.x-codegen-response.isString}}{{^vendorExtensions.x-codegen-response.isString}}result->fromJson(json);{{/vendorExtensions.x-codegen-response.isString}}{{/vendorExtensions.x-codegen-response.isPrimitiveType}}{{/isMapContainer}}{{/isListContainer}}
}
// else if(responseHttpContentType == U("multipart/form-data"))
// {
// TODO multipart response parsing
// }
else
{
throw ApiException(500
, U("error calling findPetsByStatus: unsupported response type"));
}
return result;
{{/returnType}}
});
}
{{/operation}}
{{#apiNamespaceDeclarations}}
}
{{/apiNamespaceDeclarations}}
{{/operations}}

View File

@ -0,0 +1,75 @@
/*
* ApiClient.h
*
* This is an API client responsible for stating the HTTP calls
*/
#ifndef ApiClient_H_
#define ApiClient_H_
{{{defaultInclude}}}
#include "ApiConfiguration.h"
#include "ApiException.h"
#include "IHttpBody.h"
#include "HttpContent.h"
#include <memory>
#include <vector>
#include <cpprest/details/basic_types.h>
#include <cpprest/http_client.h>
{{#apiNamespaceDeclarations}}
namespace {{this}} {
{{/apiNamespaceDeclarations}}
using namespace {{modelNamespace}};
class {{declspec}} ApiClient
{
public:
ApiClient( std::shared_ptr<ApiConfiguration> configuration = nullptr );
virtual ~ApiClient();
std::shared_ptr<ApiConfiguration> getConfiguration() const;
void setConfiguration(std::shared_ptr<ApiConfiguration> configuration);
static utility::string_t parameterToString(utility::string_t value);
static utility::string_t parameterToString(int32_t value);
static utility::string_t parameterToString(int64_t value);
template<class T>
static utility::string_t parameterToArrayString(std::vector<T> value)
{
utility::stringstream_t ss;
for( size_t i = 0; i < value.size(); i++)
{
if( i > 0) ss << U(", ");
ss << ApiClient::parameterToString(value[i]);
}
return ss.str();
}
pplx::task<web::http::http_response> callApi(
const utility::string_t& path,
const utility::string_t& method,
const std::map<utility::string_t, utility::string_t>& queryParams,
const std::shared_ptr<IHttpBody> postBody,
const std::map<utility::string_t, utility::string_t>& headerParams,
const std::map<utility::string_t, utility::string_t>& formParams,
const std::map<utility::string_t, std::shared_ptr<HttpContent>>& fileParams,
const utility::string_t& contentType
) const;
protected:
std::shared_ptr<ApiConfiguration> m_Configuration;
};
{{#apiNamespaceDeclarations}}
}
{{/apiNamespaceDeclarations}}
#endif /* ApiClient_H_ */

View File

@ -0,0 +1,131 @@
#include "ApiClient.h"
#include "MultipartFormData.h"
#include "ModelBase.h"
{{#apiNamespaceDeclarations}}
namespace {{this}} {
{{/apiNamespaceDeclarations}}
using namespace {{modelNamespace}};
ApiClient::ApiClient(std::shared_ptr<ApiConfiguration> configuration )
: m_Configuration(configuration)
{
}
ApiClient::~ApiClient()
{
}
std::shared_ptr<ApiConfiguration> ApiClient::getConfiguration() const
{
return m_Configuration;
}
void ApiClient::setConfiguration(std::shared_ptr<ApiConfiguration> configuration)
{
m_Configuration = configuration;
}
utility::string_t ApiClient::parameterToString(utility::string_t value)
{
return value;
}
utility::string_t ApiClient::parameterToString(int64_t value)
{
return std::to_wstring(value);
}
utility::string_t ApiClient::parameterToString(int32_t value)
{
return std::to_wstring(value);
}
pplx::task<web::http::http_response> ApiClient::callApi(
const utility::string_t& path,
const utility::string_t& method,
const std::map<utility::string_t, utility::string_t>& queryParams,
const std::shared_ptr<IHttpBody> postBody,
const std::map<utility::string_t, utility::string_t>& headerParams,
const std::map<utility::string_t, utility::string_t>& formParams,
const std::map<utility::string_t, std::shared_ptr<HttpContent>>& fileParams,
const utility::string_t& contentType
) const
{
if (postBody != nullptr && formParams.size() != 0)
{
throw ApiException(400, U("Cannot have body and form params"));
}
if (postBody != nullptr && fileParams.size() != 0)
{
throw ApiException(400, U("Cannot have body and file params"));
}
if (fileParams.size() > 0 && contentType != U("multipart/form-data"))
{
throw ApiException(400, U("Operations with file parameters must be called with multipart/form-data"));
}
web::http::client::http_client client(m_Configuration->getBaseUrl(), m_Configuration->getHttpConfig());
web::http::http_request request;
for ( auto& kvp : headerParams )
{
request.headers().add(kvp.first, kvp.second);
}
if (fileParams.size() > 0)
{
MultipartFormData uploadData;
for (auto& kvp : formParams)
{
uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second));
}
for (auto& kvp : fileParams)
{
uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second));
}
std::stringstream data;
postBody->writeTo(data);
auto bodyString = data.str();
auto length = bodyString.size();
request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, contentType);
}
else
{
if (postBody != nullptr)
{
std::stringstream data;
postBody->writeTo(data);
auto bodyString = data.str();
auto length = bodyString.size();
request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, contentType);
}
else
{
web::http::uri_builder formData;
for (auto& kvp : formParams)
{
formData.append_query(kvp.first, kvp.second);
}
request.set_body(formData.query(), U("application/x-www-form-urlencoded"));
}
}
web::http::uri_builder builder(path);
for (auto& kvp : queryParams)
{
builder.append_query(kvp.first, kvp.second);
}
request.set_request_uri(builder.to_uri());
request.set_method(method);
if ( !request.headers().has( web::http::header_names::user_agent ) )
{
request.headers().add( web::http::header_names::user_agent, m_Configuration->getUserAgent() );
}
return client.request(request);
}
{{#apiNamespaceDeclarations}}
}
{{/apiNamespaceDeclarations}}

View File

@ -0,0 +1,51 @@
/*
* ApiConfiguration.h
*
* This class represents a single item of a multipart-formdata request.
*/
#ifndef ApiConfiguration_H_
#define ApiConfiguration_H_
{{{defaultInclude}}}
#include <map>
#include <cpprest/details/basic_types.h>
#include <cpprest/http_client.h>
{{#apiNamespaceDeclarations}}
namespace {{this}} {
{{/apiNamespaceDeclarations}}
class {{declspec}} ApiConfiguration
{
public:
ApiConfiguration();
virtual ~ApiConfiguration();
web::http::client::http_client_config& getHttpConfig();
void setHttpConfig( web::http::client::http_client_config& value );
utility::string_t getBaseUrl() const;
void setBaseUrl( const utility::string_t value );
utility::string_t getUserAgent() const;
void setUserAgent( const utility::string_t value );
std::map<utility::string_t, utility::string_t>& getDefaultHeaders();
utility::string_t getApiKey( const utility::string_t& prefix) const;
void setApiKey( const utility::string_t& prefix, const utility::string_t& apiKey );
protected:
utility::string_t m_BaseUrl;
std::map<utility::string_t, utility::string_t> m_DefaultHeaders;
std::map<utility::string_t, utility::string_t> m_ApiKeys;
web::http::client::http_client_config m_HttpConfig;
utility::string_t m_UserAgent;
};
{{#apiNamespaceDeclarations}}
}
{{/apiNamespaceDeclarations}}
#endif /* ApiConfiguration_H_ */

View File

@ -0,0 +1,67 @@
#include "ApiConfiguration.h"
{{#apiNamespaceDeclarations}}
namespace {{this}} {
{{/apiNamespaceDeclarations}}
ApiConfiguration::ApiConfiguration()
{
}
ApiConfiguration::~ApiConfiguration()
{
}
web::http::client::http_client_config& ApiConfiguration::getHttpConfig()
{
return m_HttpConfig;
}
void ApiConfiguration::setHttpConfig( web::http::client::http_client_config& value )
{
m_HttpConfig = value;
}
utility::string_t ApiConfiguration::getBaseUrl() const
{
return m_BaseUrl;
}
void ApiConfiguration::setBaseUrl( const utility::string_t value )
{
m_BaseUrl = value;
}
utility::string_t ApiConfiguration::getUserAgent() const
{
return m_UserAgent;
}
void ApiConfiguration::setUserAgent( const utility::string_t value )
{
m_UserAgent = value;
}
std::map<utility::string_t, utility::string_t>& ApiConfiguration::getDefaultHeaders()
{
return m_DefaultHeaders;
}
utility::string_t ApiConfiguration::getApiKey( const utility::string_t& prefix) const
{
auto result = m_ApiKeys.find(prefix);
if( result != m_ApiKeys.end() )
{
return result->second;
}
return U("");
}
void ApiConfiguration::setApiKey( const utility::string_t& prefix, const utility::string_t& apiKey )
{
m_ApiKeys[prefix] = apiKey;
}
{{#apiNamespaceDeclarations}}
}
{{/apiNamespaceDeclarations}}

View File

@ -0,0 +1,48 @@
/*
* ApiException.h
*
* This is the exception being thrown in case the api call was not successful
*/
#ifndef ApiException_H_
#define ApiException_H_
{{{defaultInclude}}}
#include <memory>
#include <map>
#include <cpprest/details/basic_types.h>
#include <cpprest/http_msg.h>
{{#apiNamespaceDeclarations}}
namespace {{this}} {
{{/apiNamespaceDeclarations}}
class {{declspec}} ApiException
: public web::http::http_exception
{
public:
ApiException( int errorCode
, const utility::string_t& message
, std::shared_ptr<std::istream> content = nullptr );
ApiException( int errorCode
, const utility::string_t& message
, std::map<utility::string_t, utility::string_t>& headers
, std::shared_ptr<std::istream> content = nullptr );
virtual ~ApiException();
std::map<utility::string_t, utility::string_t>& getHeaders();
std::shared_ptr<std::istream> getContent() const;
protected:
std::shared_ptr<std::istream> m_Content;
std::map<utility::string_t, utility::string_t> m_Headers;
};
{{#apiNamespaceDeclarations}}
}
{{/apiNamespaceDeclarations}}
#endif /* ApiBase_H_ */

View File

@ -0,0 +1,40 @@
#include "ApiException.h"
{{#apiNamespaceDeclarations}}
namespace {{this}} {
{{/apiNamespaceDeclarations}}
ApiException::ApiException( int errorCode
, const utility::string_t& message
, std::shared_ptr<std::istream> content /*= nullptr*/ )
: web::http::http_exception( errorCode, message )
, m_Content(content)
{
}
ApiException::ApiException( int errorCode
, const utility::string_t& message
, std::map<utility::string_t, utility::string_t>& headers
, std::shared_ptr<std::istream> content /*= nullptr*/ )
: web::http::http_exception( errorCode, message )
, m_Content(content)
, m_Headers(headers)
{
}
ApiException::~ApiException()
{
}
std::shared_ptr<std::istream> ApiException::getContent() const
{
return m_Content;
}
std::map<utility::string_t, utility::string_t>& ApiException::getHeaders()
{
return m_Headers;
}
{{#apiNamespaceDeclarations}}
}
{{/apiNamespaceDeclarations}}

View File

@ -0,0 +1,51 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-cpprest "minor update"
git_user_id=$1
git_repo_id=$2
release_note=$3
if [ "$git_user_id" = "" ]; then
git_user_id="{{{gitUserId}}}"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="{{{gitRepoId}}}"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="{{{releaseNote}}}"
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
git_remote=`git remote`
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment."
git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git
fi
fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@ -0,0 +1,29 @@
# Compiled Object files
*.slo
*.lo
*.o
*.obj
# Precompiled Headers
*.gch
*.pch
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Fortran module files
*.mod
*.smod
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Executables
*.exe
*.out
*.app

View File

@ -0,0 +1,56 @@
/*
* HttpContent.h
*
* This class represents a single item of a multipart-formdata request.
*/
#ifndef HttpContent_H_
#define HttpContent_H_
{{{defaultInclude}}}
#include <memory>
#include <cpprest/details/basic_types.h>
{{#modelNamespaceDeclarations}}
namespace {{this}} {
{{/modelNamespaceDeclarations}}
class {{declspec}} HttpContent
{
public:
HttpContent();
virtual ~HttpContent();
virtual utility::string_t getContentDisposition();
virtual void setContentDisposition( const utility::string_t& value );
virtual utility::string_t getName();
virtual void setName( const utility::string_t& value );
virtual utility::string_t getFileName();
virtual void setFileName( const utility::string_t& value );
virtual utility::string_t getContentType();
virtual void setContentType( const utility::string_t& value );
virtual std::shared_ptr<std::istream> getData();
virtual void setData( std::shared_ptr<std::istream> value );
virtual void writeTo( std::ostream& stream );
protected:
// NOTE: no utility::string_t here because those strings can only contain ascii
utility::string_t m_ContentDisposition;
utility::string_t m_Name;
utility::string_t m_FileName;
utility::string_t m_ContentType;
std::shared_ptr<std::istream> m_Data;
};
{{#modelNamespaceDeclarations}}
}
{{/modelNamespaceDeclarations}}
#endif /* HttpContent_H_ */

View File

@ -0,0 +1,73 @@
#include "HttpContent.h"
{{#modelNamespaceDeclarations}}
namespace {{this}} {
{{/modelNamespaceDeclarations}}
HttpContent::HttpContent()
{
}
HttpContent::~HttpContent()
{
}
utility::string_t HttpContent::getContentDisposition()
{
return m_ContentDisposition;
}
void HttpContent::setContentDisposition( const utility::string_t & value )
{
m_ContentDisposition = value;
}
utility::string_t HttpContent::getName()
{
return m_Name;
}
void HttpContent::setName( const utility::string_t & value )
{
m_Name = value;
}
utility::string_t HttpContent::getFileName()
{
return m_FileName;
}
void HttpContent::setFileName( const utility::string_t & value )
{
m_FileName = value;
}
utility::string_t HttpContent::getContentType()
{
return m_ContentType;
}
void HttpContent::setContentType( const utility::string_t & value )
{
m_ContentType = value;
}
std::shared_ptr<std::istream> HttpContent::getData()
{
return m_Data;
}
void HttpContent::setData( std::shared_ptr<std::istream> value )
{
m_Data = value;
}
void HttpContent::writeTo( std::ostream& stream )
{
m_Data->seekg( 0, m_Data->beg );
stream << m_Data->rdbuf();
}
{{#modelNamespaceDeclarations}}
}
{{/modelNamespaceDeclarations}}

View File

@ -0,0 +1,29 @@
/*
* IHttpBody.h
*
* This is the interface for contents that can be sent to a remote HTTP server.
*/
#ifndef IHttpBody_H_
#define IHttpBody_H_
{{{defaultInclude}}}
#include <iostream>
{{#modelNamespaceDeclarations}}
namespace {{this}} {
{{/modelNamespaceDeclarations}}
class {{declspec}} IHttpBody
{
public:
virtual ~IHttpBody() { }
virtual void writeTo( std::ostream& stream ) = 0;
};
{{#modelNamespaceDeclarations}}
}
{{/modelNamespaceDeclarations}}
#endif /* IHttpBody_H_ */

View File

@ -0,0 +1,36 @@
/*
* JsonBody.h
*
* This is a JSON http body which can be submitted via http
*/
#ifndef JsonBody_H_
#define JsonBody_H_
{{{defaultInclude}}}
#include "IHttpBody.h"
#include <cpprest/json.h>
{{#modelNamespaceDeclarations}}
namespace {{this}} {
{{/modelNamespaceDeclarations}}
class {{declspec}} JsonBody
: public IHttpBody
{
public:
JsonBody( const web::json::value& value );
virtual ~JsonBody();
void writeTo( std::ostream& target ) override;
protected:
web::json::value m_Json;
};
{{#modelNamespaceDeclarations}}
}
{{/modelNamespaceDeclarations}}
#endif /* JsonBody_H_ */

View File

@ -0,0 +1,23 @@
#include "JsonBody.h"
{{#modelNamespaceDeclarations}}
namespace {{this}} {
{{/modelNamespaceDeclarations}}
JsonBody::JsonBody( const web::json::value& json)
: m_Json(json)
{
}
JsonBody::~JsonBody()
{
}
void JsonBody::writeTo( std::ostream& target )
{
m_Json.serialize(target);
}
{{#modelNamespaceDeclarations}}
}
{{/modelNamespaceDeclarations}}

View File

@ -0,0 +1,69 @@
{{#models}}{{#model}}/*
* {{classname}}.h
*
* {{description}}
*/
#ifndef {{classname}}_H_
#define {{classname}}_H_
{{{defaultInclude}}}
#include "ModelBase.h"
{{#imports}}{{{this}}}
{{/imports}}
{{#modelNamespaceDeclarations}}
namespace {{this}} {
{{/modelNamespaceDeclarations}}
/// <summary>
/// {{description}}
/// </summary>
class {{declspec}} {{classname}}
: public ModelBase
{
public:
{{classname}}();
virtual ~{{classname}}();
/////////////////////////////////////////////
/// ModelBase overrides
void validate() override;
web::json::value toJson() const override;
void fromJson(web::json::value& json) override;
void toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) const override;
void fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) override;
/////////////////////////////////////////////
/// {{classname}} members
{{#vars}}
/// <summary>
/// {{description}}
/// </summary>
{{^isNotContainer}}{{{datatype}}}& {{getter}}();
{{/isNotContainer}}{{#isNotContainer}}{{{datatype}}} {{getter}}() const;
void {{setter}}({{{datatype}}} value);
{{/isNotContainer}}{{^required}}bool {{baseName}}IsSet() const;
void unset{{name}}();
{{/required}}
{{/vars}}
protected:
{{#vars}}{{{datatype}}} m_{{name}};
{{^required}}bool m_{{name}}IsSet;
{{/required}}
{{/vars}}
};
{{#modelNamespaceDeclarations}}
}
{{/modelNamespaceDeclarations}}
#endif /* {{classname}}_H_ */
{{/model}}
{{/models}}

View File

@ -0,0 +1,254 @@
{{#models}}{{#model}}
#include "{{classname}}.h"
{{#modelNamespaceDeclarations}}
namespace {{this}} {
{{/modelNamespaceDeclarations}}
{{classname}}::{{classname}}()
{
{{#vars}}{{#isNotContainer}}{{#isPrimitiveType}}m_{{name}} = {{{defaultValue}}};
{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isString}}m_{{name}} = {{{defaultValue}}};
{{/isString}}{{#isDateTime}}m_{{name}} = {{{defaultValue}}};
{{/isDateTime}}{{/isPrimitiveType}}{{/isNotContainer}}{{^required}}m_{{name}}IsSet = false;
{{/required}}{{/vars}}
}
{{classname}}::~{{classname}}()
{
}
void {{classname}}::validate()
{
// TODO: implement validation
}
web::json::value {{classname}}::toJson() const
{
web::json::value val = web::json::value::object();
{{#vars}}{{#isPrimitiveType}}{{^required}}if(m_{{name}}IsSet)
{
val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}});
}
{{/required}}{{#required}}val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}});
{{/required}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}}{
std::vector<web::json::value> jsonArray;
for( auto& item : m_{{name}} )
{
jsonArray.push_back(ModelBase::toJson(item));
}
{{#required}}val[U("{{baseName}}")] = web::json::value::array(jsonArray);
{{/required}}{{^required}}
if(jsonArray.size() > 0)
{
val[U("{{baseName}}")] = web::json::value::array(jsonArray);
}
{{/required}}
}
{{/isListContainer}}{{^isListContainer}}{{^required}}if(m_{{name}}IsSet)
{
val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}});
}
{{/required}}{{#required}}val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}});
{{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{/vars}}
return val;
}
void {{classname}}::fromJson(web::json::value& val)
{
{{#vars}}{{#isPrimitiveType}}{{^required}}if(val.has_field(U("{{baseName}}")))
{
{{setter}}(ModelBase::{{baseType}}FromJson(val[U("{{baseName}}")]));
}
{{/required}}{{#required}}{{setter}}(ModelBase::{{baseType}}FromJson(val[U("{{baseName}}")]));
{{/required}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}}{
m_{{name}}.clear();
std::vector<web::json::value> jsonArray;
{{^required}}if(val.has_field(U("{{baseName}}")))
{
{{/required}}
for( auto& item : val[U("{{baseName}}")].as_array() )
{
{{#items.isPrimitiveType}}m_{{name}}.push_back(ModelBase::{{baseType}}FromJson(item));
{{/items.isPrimitiveType}}{{^items.isPrimitiveType}}{{#items.isString}}m_{{name}}.push_back(ModelBase::stringFromJson(item));
{{/items.isString}}{{^items.isString}}{{#items.isDateTime}}m_{{name}}.push_back(ModelBase::dateFromJson(item));
{{/items.isDateTime}}{{^items.isDateTime}}
if(item.is_null())
{
m_{{name}}.push_back( {{{items.datatype}}}(nullptr) );
}
else
{
{{{items.datatype}}} newItem({{{items.defaultValue}}});
newItem->fromJson(item);
m_{{name}}.push_back( newItem );
}
{{/items.isDateTime}}{{/items.isString}}{{/items.isPrimitiveType}}
}
{{^required}}
}
{{/required}}
}
{{/isListContainer}}{{^isListContainer}}{{^required}}if(val.has_field(U("{{baseName}}")))
{
{{#isString}}{{setter}}(ModelBase::stringFromJson(val[U("{{baseName}}")]));
{{/isString}}{{^isString}}{{#isDateTime}}{{setter}}(ModelBase::dateFromJson(val[U("{{baseName}}")]));
{{/isDateTime}}{{^isDateTime}}if(!val[U("{{baseName}}")].is_null())
{
{{{datatype}}} newItem({{{defaultValue}}});
newItem->fromJson(val[U("{{baseName}}")]);
{{setter}}( newItem );
}
{{/isDateTime}}{{/isString}}
}
{{/required}}{{#required}}{{#isString}}{{setter}}(ModelBase::stringFromJson(val[U("{{baseName}}")]));
{{/isString}}{{^isString}}{{#isDateTime}}{{setter}}(ModelBase::dateFromJson(val[U("{{baseName}}")]));
{{/isDateTime}}{{^isDateTime}}{{#vendorExtensions.x-codegen-file}}{{setter}}(ModelBase::fileFromJson(val[U("{{baseName}}")]));
{{/vendorExtensions.x-codegen-file}}{{^vendorExtensions.x-codegen-file}}{{{datatype}}} new{{name}}({{{defaultValue}}});
new{{name}}->fromJson(val[U("{{baseName}}")]);
{{setter}}( newItem );
{{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{/vars}}
}
void {{classname}}::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.'))
{
namePrefix += U(".");
}
{{#vars}}{{#isPrimitiveType}}{{^required}}if(m_{{name}}IsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}}));
}
{{/required}}{{#required}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}}));
{{/required}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}}{
std::vector<web::json::value> jsonArray;
for( auto& item : m_{{name}} )
{
jsonArray.push_back(ModelBase::toJson(item));
}
{{#required}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), web::json::value::array(jsonArray), U("application/json")));
{{/required}}{{^required}}
if(jsonArray.size() > 0)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), web::json::value::array(jsonArray), U("application/json")));
}
{{/required}}
}
{{/isListContainer}}{{^isListContainer}}{{^required}}if(m_{{name}}IsSet)
{
{{#isString}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}}));
{{/isString}}{{^isString}}{{#isDateTime}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}}));
{{/isDateTime}}{{^isDateTime}}if (m_{{name}}.get())
{
m_{{name}}->toMultipart(multipart, U("{{baseName}}."));
}
{{/isDateTime}}{{/isString}}
}
{{/required}}{{#required}}{{#isString}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}}));
{{/isString}}{{^isString}}{{#isDateTime}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}}));
{{/isDateTime}}{{^isDateTime}}{{#vendorExtensions.x-codegen-file}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}}));
{{/vendorExtensions.x-codegen-file}}{{^vendorExtensions.x-codegen-file}}m_{{name}}->toMultipart(multipart, U("{{baseName}}."));
{{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{/vars}}
}
void {{classname}}::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix)
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.'))
{
namePrefix += U(".");
}
{{#vars}}{{#isPrimitiveType}}{{^required}}if(multipart->hasContent(U("{{baseName}}")))
{
{{setter}}(ModelBase::{{baseType}}FromHttpContent(multipart->getContent(U("{{baseName}}"))));
}
{{/required}}{{#required}}{{setter}}(ModelBase::{{baseType}}FromHttpContent(multipart->getContent(U("{{baseName}}"))));
{{/required}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}}{
m_{{name}}.clear();
{{^required}}if(multipart->hasContent(U("{{baseName}}")))
{
{{/required}}
web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(U("{{baseName}}"))));
for( auto& item : jsonArray.as_array() )
{
{{#items.isPrimitiveType}}m_{{name}}.push_back(ModelBase::{{baseType}}FromJson(item));
{{/items.isPrimitiveType}}{{^items.isPrimitiveType}}{{#items.isString}}m_{{name}}.push_back(ModelBase::stringFromJson(item));
{{/items.isString}}{{^items.isString}}{{#items.isDateTime}}m_{{name}}.push_back(ModelBase::dateFromJson(item));
{{/items.isDateTime}}{{^items.isDateTime}}
if(item.is_null())
{
m_{{name}}.push_back( {{{items.datatype}}}(nullptr) );
}
else
{
{{{items.datatype}}} newItem({{{items.defaultValue}}});
newItem->fromJson(item);
m_{{name}}.push_back( newItem );
}
{{/items.isDateTime}}{{/items.isString}}{{/items.isPrimitiveType}}
}
{{^required}}
}
{{/required}}
}
{{/isListContainer}}{{^isListContainer}}{{^required}}if(multipart->hasContent(U("{{baseName}}")))
{
{{#isString}}{{setter}}(ModelBase::stringFromHttpContent(multipart->getContent(U("{{baseName}}"))));
{{/isString}}{{^isString}}{{#isDateTime}}{{setter}}(ModelBase::dateFromHttpContent(multipart->getContent(U("{{baseName}}"))));
{{/isDateTime}}{{^isDateTime}}if(multipart->hasContent(U("{{baseName}}")))
{
{{{datatype}}} newItem({{{defaultValue}}});
newItem->fromMultiPart(multipart, U("{{baseName}}."));
{{setter}}( newItem );
}
{{/isDateTime}}{{/isString}}
}
{{/required}}{{#required}}{{#isString}}{{setter}}(ModelBase::stringFromHttpContent(multipart->getContent(U("{{baseName}}"))));
{{/isString}}{{^isString}}{{#isDateTime}}{{setter}}(ModelBase::dateFromHttpContent(multipart->getContent(U("{{baseName}}"))));
{{/isDateTime}}{{^isDateTime}}{{#vendorExtensions.x-codegen-file}}{{setter}}(multipart->getContent(U("{{baseName}}")));
{{/vendorExtensions.x-codegen-file}}{{^vendorExtensions.x-codegen-file}}{{{datatype}}} new{{name}}({{{defaultValue}}});
new{{name}}->fromMultiPart(multipart, U("{{baseName}}."));
{{setter}}( new{{name}} );
{{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{/vars}}
}
{{#vars}}{{^isNotContainer}}{{{datatype}}}& {{classname}}::{{getter}}()
{
return m_{{name}};
}
{{/isNotContainer}}{{#isNotContainer}}{{{datatype}}} {{classname}}::{{getter}}() const
{
return m_{{name}};
}
void {{classname}}::{{setter}}({{{datatype}}} value)
{
m_{{name}} = value;
{{^required}}m_{{name}}IsSet = true;{{/required}}
}
{{/isNotContainer}}
{{^required}}bool {{classname}}::{{baseName}}IsSet() const
{
return m_{{name}}IsSet;
}
void {{classname}}::unset{{name}}()
{
m_{{name}}IsSet = false;
}
{{/required}}
{{/vars}}
{{#modelNamespaceDeclarations}}
}
{{/modelNamespaceDeclarations}}
{{/model}}
{{/models}}

View File

@ -0,0 +1,76 @@
/*
* ModelBase.h
*
* This is the base class for all model classes
*/
#ifndef ModelBase_H_
#define ModelBase_H_
{{{defaultInclude}}}
#include "HttpContent.h"
#include "MultipartFormData.h"
#include <cpprest/details/basic_types.h>
#include <cpprest/json.h>
{{#modelNamespaceDeclarations}}
namespace {{this}} {
{{/modelNamespaceDeclarations}}
class {{declspec}} ModelBase
{
public:
ModelBase();
virtual ~ModelBase();
virtual void validate() = 0;
virtual web::json::value toJson() const = 0;
virtual void fromJson(web::json::value& json) = 0;
virtual void toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) const = 0;
virtual void fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) = 0;
static web::json::value toJson( const utility::string_t& value );
static web::json::value toJson( const utility::datetime& value );
static web::json::value toJson( std::shared_ptr<HttpContent> value );
static web::json::value toJson( std::shared_ptr<ModelBase> value );
static web::json::value toJson( int32_t value );
static web::json::value toJson( int64_t value );
static web::json::value toJson( double value );
static int64_t int64_tFromJson(web::json::value& val);
static int32_t int32_tFromJson(web::json::value& val);
static utility::string_t stringFromJson(web::json::value& val);
static utility::datetime dateFromJson(web::json::value& val);
static double doubleFromJson(web::json::value& val);
static bool boolFromJson(web::json::value& val);
static std::shared_ptr<HttpContent> fileFromJson(web::json::value& val);
static std::shared_ptr<HttpContent> toHttpContent( const utility::string_t& name, const utility::string_t& value, const utility::string_t& contentType = U(""));
static std::shared_ptr<HttpContent> toHttpContent( const utility::string_t& name, const utility::datetime& value, const utility::string_t& contentType = U(""));
static std::shared_ptr<HttpContent> toHttpContent( const utility::string_t& name, std::shared_ptr<HttpContent> value );
static std::shared_ptr<HttpContent> toHttpContent( const utility::string_t& name, const web::json::value& value, const utility::string_t& contentType = U("application/json") );
static std::shared_ptr<HttpContent> toHttpContent( const utility::string_t& name, int32_t value, const utility::string_t& contentType = U("") );
static std::shared_ptr<HttpContent> toHttpContent( const utility::string_t& name, int64_t value, const utility::string_t& contentType = U("") );
static std::shared_ptr<HttpContent> toHttpContent( const utility::string_t& name, double value, const utility::string_t& contentType = U("") );
static int64_t int64_tFromHttpContent(std::shared_ptr<HttpContent> val);
static int32_t int32_tFromHttpContent(std::shared_ptr<HttpContent> val);
static utility::string_t stringFromHttpContent(std::shared_ptr<HttpContent> val);
static utility::datetime dateFromHttpContent(std::shared_ptr<HttpContent> val);
static bool boolFromHttpContent(std::shared_ptr<HttpContent> val);
static double doubleFromHttpContent(std::shared_ptr<HttpContent> val);
static utility::string_t toBase64( utility::string_t value );
static utility::string_t toBase64( std::shared_ptr<std::istream> value );
static std::shared_ptr<std::istream> fromBase64( const utility::string_t& encoded );
};
{{#modelNamespaceDeclarations}}
}
{{/modelNamespaceDeclarations}}
#endif /* ModelBase_H_ */

View File

@ -0,0 +1,337 @@
#include "ModelBase.h"
{{#modelNamespaceDeclarations}}
namespace {{this}} {
{{/modelNamespaceDeclarations}}
ModelBase::ModelBase()
{
}
ModelBase::~ModelBase()
{
}
web::json::value ModelBase::toJson( const utility::string_t& value )
{
return web::json::value::string(value);
}
web::json::value ModelBase::toJson( const utility::datetime& value )
{
return web::json::value::string(value.to_string(utility::datetime::ISO_8601));
}
web::json::value ModelBase::toJson( int32_t value )
{
return web::json::value::number(value);
}
web::json::value ModelBase::toJson( int64_t value )
{
return web::json::value::number(value);
}
web::json::value ModelBase::toJson( double value )
{
return web::json::value::number(value);
}
web::json::value ModelBase::toJson( std::shared_ptr<HttpContent> content )
{
web::json::value value;
value[U("ContentDisposition")] = ModelBase::toJson(content->getContentDisposition());
value[U("ContentType")] = ModelBase::toJson(content->getContentType());
value[U("FileName")] = ModelBase::toJson(content->getFileName());
value[U("InputStream")] = web::json::value::string( ModelBase::toBase64(content->getData()) );
return value;
}
std::shared_ptr<HttpContent> ModelBase::fileFromJson(web::json::value& val)
{
std::shared_ptr<HttpContent> content(new HttpContent);
if(val.has_field(U("ContentDisposition")))
{
content->setContentDisposition( ModelBase::stringFromJson(val[U("ContentDisposition")]) );
}
if(val.has_field(U("ContentType")))
{
content->setContentType( ModelBase::stringFromJson(val[U("ContentType")]) );
}
if(val.has_field(U("FileName")))
{
content->setFileName( ModelBase::stringFromJson(val[U("FileName")]) );
}
if(val.has_field(U("InputStream")))
{
content->setData( ModelBase::fromBase64( ModelBase::stringFromJson(val[U("InputStream")]) ) );
}
return content;
}
web::json::value ModelBase::toJson( std::shared_ptr<ModelBase> content )
{
return content.get() ? content->toJson() : web::json::value::null();
}
std::shared_ptr<HttpContent> ModelBase::toHttpContent( const utility::string_t& name, const utility::string_t& value, const utility::string_t& contentType)
{
std::shared_ptr<HttpContent> content(new HttpContent);
content->setName( name );
content->setContentDisposition( U("form-data") );
content->setContentType( contentType );
content->setData( std::shared_ptr<std::istream>( new std::stringstream( utility::conversions::to_utf8string(value) ) ) );
return content;
}
std::shared_ptr<HttpContent> ModelBase::toHttpContent( const utility::string_t& name, const utility::datetime& value, const utility::string_t& contentType )
{
std::shared_ptr<HttpContent> content( new HttpContent );
content->setName( name );
content->setContentDisposition( U("form-data") );
content->setContentType( contentType );
content->setData( std::shared_ptr<std::istream>( new std::stringstream( utility::conversions::to_utf8string(value.to_string(utility::datetime::ISO_8601) ) ) ) );
return content;
}
std::shared_ptr<HttpContent> ModelBase::toHttpContent( const utility::string_t& name, std::shared_ptr<HttpContent> value )
{
std::shared_ptr<HttpContent> content( new HttpContent );
content->setName( name );
content->setContentDisposition( value->getContentDisposition() );
content->setContentType( value->getContentType() );
content->setData( value->getData() );
content->setFileName( value->getFileName() );
return content;
}
std::shared_ptr<HttpContent> ModelBase::toHttpContent( const utility::string_t& name, const web::json::value& value, const utility::string_t& contentType )
{
std::shared_ptr<HttpContent> content( new HttpContent );
content->setName( name );
content->setContentDisposition( U("form-data") );
content->setContentType( contentType );
content->setData( std::shared_ptr<std::istream>( new std::stringstream( utility::conversions::to_utf8string(value.serialize()) ) ) );
return content;
}
std::shared_ptr<HttpContent> ModelBase::toHttpContent( const utility::string_t& name, int32_t value, const utility::string_t& contentType )
{
std::shared_ptr<HttpContent> content( new HttpContent );
content->setName( name );
content->setContentDisposition( U("form-data") );
content->setContentType( contentType );
content->setData( std::shared_ptr<std::istream>( new std::stringstream( std::to_string( value ) ) ) );
return content;
}
std::shared_ptr<HttpContent> ModelBase::toHttpContent( const utility::string_t& name, int64_t value, const utility::string_t& contentType )
{
std::shared_ptr<HttpContent> content( new HttpContent );
content->setName( name );
content->setContentDisposition( U("form-data") );
content->setContentType( contentType );
content->setData( std::shared_ptr<std::istream>( new std::stringstream( std::to_string( value ) ) ) );
return content;
}
std::shared_ptr<HttpContent> ModelBase::toHttpContent( const utility::string_t& name, double value, const utility::string_t& contentType )
{
std::shared_ptr<HttpContent> content( new HttpContent );
content->setName( name );
content->setContentDisposition( U("form-data") );
content->setContentType( contentType );
content->setData( std::shared_ptr<std::istream>( new std::stringstream( std::to_string( value ) ) ) );
return content;
}
// base64 encoding/decoding based on : https://en.wikibooks.org/wiki/Algorithm_Implementation/Miscellaneous/Base64#C.2B.2B
const static char Base64Chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const static char Base64PadChar = '=';
utility::string_t ModelBase::toBase64( utility::string_t value )
{
std::shared_ptr<std::istream> source( new std::stringstream( utility::conversions::to_utf8string(value) ) );
return ModelBase::toBase64(source);
}
utility::string_t ModelBase::toBase64( std::shared_ptr<std::istream> value )
{
value->seekg( 0, value->end );
size_t length = value->tellg();
value->seekg( 0, value->beg );
utility::string_t base64;
base64.reserve( ((length / 3) + (length % 3 > 0)) * 4 );
char read[3] = { 0 };
uint32_t temp;
for ( size_t idx = 0; idx < length / 3; idx++ )
{
value->read( read, 3 );
temp = (read[0]) << 16;
temp += (read[1]) << 8;
temp += (read[2]);
base64.append( 1, Base64Chars[(temp & 0x00FC0000) >> 18] );
base64.append( 1, Base64Chars[(temp & 0x0003F000) >> 12] );
base64.append( 1, Base64Chars[(temp & 0x00000FC0) >> 6] );
base64.append( 1, Base64Chars[(temp & 0x0000003F)] );
}
switch ( length % 3 )
{
case 1:
value->read( read, 1 );
temp = read[0] << 16;
base64.append( 1, Base64Chars[(temp & 0x00FC0000) >> 18] );
base64.append( 1, Base64Chars[(temp & 0x0003F000) >> 12] );
base64.append( 2, Base64PadChar );
break;
case 2:
value->read( read, 2 );
temp = read[0] << 16;
temp += read[1] << 8;
base64.append( 1, Base64Chars[(temp & 0x00FC0000) >> 18] );
base64.append( 1, Base64Chars[(temp & 0x0003F000) >> 12] );
base64.append( 1, Base64Chars[(temp & 0x00000FC0) >> 6] );
base64.append( 1, Base64PadChar );
break;
}
return base64;
}
std::shared_ptr<std::istream> ModelBase::fromBase64( const utility::string_t& encoded )
{
std::shared_ptr<std::stringstream> result(new std::stringstream);
char outBuf[3] = { 0 };
uint32_t temp = 0;
utility::string_t::const_iterator cursor = encoded.begin();
while ( cursor < encoded.end() )
{
for ( size_t quantumPosition = 0; quantumPosition < 4; quantumPosition++ )
{
temp <<= 6;
if ( *cursor >= 0x41 && *cursor <= 0x5A )
{
temp |= *cursor - 0x41;
}
else if ( *cursor >= 0x61 && *cursor <= 0x7A )
{
temp |= *cursor - 0x47;
}
else if ( *cursor >= 0x30 && *cursor <= 0x39 )
{
temp |= *cursor + 0x04;
}
else if ( *cursor == 0x2B )
{
temp |= 0x3E; //change to 0x2D for URL alphabet
}
else if ( *cursor == 0x2F )
{
temp |= 0x3F; //change to 0x5F for URL alphabet
}
else if ( *cursor == Base64PadChar ) //pad
{
switch ( encoded.end() - cursor )
{
case 1: //One pad character
outBuf[0] = (temp >> 16) & 0x000000FF;
outBuf[1] = (temp >> 8) & 0x000000FF;
result->write( outBuf, 2 );
return result;
case 2: //Two pad characters
outBuf[0] = (temp >> 10) & 0x000000FF;
result->write( outBuf, 1 );
return result;
default:
throw web::json::json_exception( U( "Invalid Padding in Base 64!" ) );
}
}
else
{
throw web::json::json_exception( U( "Non-Valid Character in Base 64!" ) );
}
++cursor;
}
outBuf[0] = (temp >> 16) & 0x000000FF;
outBuf[1] = (temp >> 8) & 0x000000FF;
outBuf[2] = (temp) & 0x000000FF;
result->write( outBuf, 3 );
}
return result;
}
int64_t ModelBase::int64_tFromJson(web::json::value& val)
{
return val.as_number().to_int64();
}
int32_t ModelBase::int32_tFromJson(web::json::value& val)
{
return val.as_integer();
}
utility::string_t ModelBase::stringFromJson(web::json::value& val)
{
return val.is_string() ? val.as_string() : U("");
}
utility::datetime ModelBase::dateFromJson(web::json::value& val)
{
return utility::datetime::from_string(val.as_string(), utility::datetime::ISO_8601);
}
bool ModelBase::boolFromJson(web::json::value& val)
{
return val.as_bool();
}
double ModelBase::doubleFromJson(web::json::value& val)
{
return val.as_double();
}
int64_t ModelBase::int64_tFromHttpContent(std::shared_ptr<HttpContent> val)
{
utility::string_t str = ModelBase::stringFromHttpContent(val);
utility::stringstream_t ss(str);
int64_t result = 0;
ss >> result;
return result;
}
int32_t ModelBase::int32_tFromHttpContent(std::shared_ptr<HttpContent> val)
{
utility::string_t str = ModelBase::stringFromHttpContent(val);
utility::stringstream_t ss(str);
int32_t result = 0;
ss >> result;
return result;
}
utility::string_t ModelBase::stringFromHttpContent(std::shared_ptr<HttpContent> val)
{
std::shared_ptr<std::istream> data = val->getData();
data->seekg( 0, data->beg );
std::string str((std::istreambuf_iterator<char>(*data.get())),
std::istreambuf_iterator<char>());
return utility::conversions::to_utf16string(str);
}
utility::datetime ModelBase::dateFromHttpContent(std::shared_ptr<HttpContent> val)
{
utility::string_t str = ModelBase::stringFromHttpContent(val);
return utility::datetime::from_string(str, utility::datetime::ISO_8601);
}
bool ModelBase::boolFromHttpContent(std::shared_ptr<HttpContent> val)
{
utility::string_t str = ModelBase::stringFromHttpContent(val);
utility::stringstream_t ss(str);
bool result = false;
ss >> result;
return result;
}
double ModelBase::doubleFromHttpContent(std::shared_ptr<HttpContent> val)
{
utility::string_t str = ModelBase::stringFromHttpContent(val);
utility::stringstream_t ss(str);
double result = 0.0;
ss >> result;
return result;
}
{{#modelNamespaceDeclarations}}
}
{{/modelNamespaceDeclarations}}

View File

@ -0,0 +1,49 @@
/*
* MultipartFormData.h
*
* This class represents a container for building a application/x-multipart-formdata requests.
*/
#ifndef MultipartFormData_H_
#define MultipartFormData_H_
{{{defaultInclude}}}
#include "IHttpBody.h"
#include "HttpContent.h"
#include <vector>
#include <map>
#include <memory>
#include <cpprest/details/basic_types.h>
{{#modelNamespaceDeclarations}}
namespace {{this}} {
{{/modelNamespaceDeclarations}}
class {{declspec}} MultipartFormData
: public IHttpBody
{
public:
MultipartFormData();
MultipartFormData(const utility::string_t& boundary);
virtual ~MultipartFormData();
virtual void add( std::shared_ptr<HttpContent> content );
virtual utility::string_t getBoundary();
virtual std::shared_ptr<HttpContent> getContent(const utility::string_t& name) const;
virtual bool hasContent(const utility::string_t& name) const;
virtual void writeTo( std::ostream& target );
protected:
std::vector<std::shared_ptr<HttpContent>> m_Contents;
utility::string_t m_Boundary;
std::map<utility::string_t, std::shared_ptr<HttpContent>> m_ContentLookup;
};
{{#modelNamespaceDeclarations}}
}
{{/modelNamespaceDeclarations}}
#endif /* MultipartFormData_H_ */

View File

@ -0,0 +1,99 @@
#include "MultipartFormData.h"
#include "ModelBase.h"
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid_io.hpp>
{{#modelNamespaceDeclarations}}
namespace {{this}} {
{{/modelNamespaceDeclarations}}
MultipartFormData::MultipartFormData()
{
utility::stringstream_t uuidString;
uuidString << boost::uuids::random_generator()();
m_Boundary = uuidString.str();
}
MultipartFormData::MultipartFormData(const utility::string_t& boundary)
: m_Boundary(boundary)
{
}
MultipartFormData::~MultipartFormData()
{
}
utility::string_t MultipartFormData::getBoundary()
{
return m_Boundary;
}
void MultipartFormData::add( std::shared_ptr<HttpContent> content )
{
m_Contents.push_back( content );
m_ContentLookup[content->getName()] = content;
}
bool MultipartFormData::hasContent(const utility::string_t& name) const
{
return m_ContentLookup.find(name) != m_ContentLookup.end();
}
std::shared_ptr<HttpContent> MultipartFormData::getContent(const utility::string_t& name) const
{
auto result = m_ContentLookup.find(name);
if(result == m_ContentLookup.end())
{
return std::shared_ptr<HttpContent>(nullptr);
}
return result->second;
}
void MultipartFormData::writeTo( std::ostream& target )
{
for ( size_t i = 0; i < m_Contents.size(); i++ )
{
std::shared_ptr<HttpContent> content = m_Contents[i];
// boundary
target << "\r\n" << "--" << utility::conversions::to_utf8string( m_Boundary ) << "\r\n";
// headers
target << "Content-Disposition: " << utility::conversions::to_utf8string( content->getContentDisposition() );
if ( content->getName().size() > 0 )
{
target << "; name=\"" << utility::conversions::to_utf8string( content->getName() ) << "\"";
}
if ( content->getFileName().size() > 0 )
{
target << "; filename=\"" << utility::conversions::to_utf8string( content->getFileName() ) << "\"";
}
target << "\r\n";
if ( content->getContentType().size() > 0 )
{
target << "Content-Type: " << utility::conversions::to_utf8string( content->getContentType() ) << "\r\n";
}
target << "\r\n";
// body
std::shared_ptr<std::istream> data = content->getData();
data->seekg( 0, data->end );
std::vector<char> dataBytes( data->tellg() );
data->seekg( 0, data->beg );
data->read( &dataBytes[0], dataBytes.size() );
std::copy( dataBytes.begin(), dataBytes.end(), std::ostreambuf_iterator<char>( target ) );
}
target << "\r\n--" << utility::conversions::to_utf8string( m_Boundary ) << "--\r\n";
}
{{#modelNamespaceDeclarations}}
}
{{/modelNamespaceDeclarations}}

View File

@ -0,0 +1,30 @@
# Go API Server for {{packageName}}
{{#appDescription}}
{{{appDescription}}}
{{/appDescription}}
## 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/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub.
-
To see how to make this your own, look here:
[README](https://github.com/swagger-api/swagger-codegen/blob/master/README.md)
- API version: {{appVersion}}
- Build date: {{generatedDate}}
{{#infoUrl}}
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
{{/infoUrl}}
### Running the server
To run the server, follow these simple steps:
```
go run main.go
```

View File

@ -0,0 +1 @@
application: {{packageName}}

View File

@ -0,0 +1,19 @@
package {{packageName}}
{{#operations}}
import (
"net/http"
)
type {{classname}} struct {
}
{{#operation}}
func {{nickname}}(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
}
{{/operation}}
{{/operations}}

View File

@ -0,0 +1,23 @@
package {{packageName}}
import (
"log"
"net/http"
"time"
)
func Logger(inner http.Handler, name string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
inner.ServeHTTP(w, r)
log.Printf(
"%s %s %s %s",
r.Method,
r.RequestURI,
name,
time.Since(start),
)
})
}

View File

@ -0,0 +1,22 @@
package main
import (
// WARNING!
// Change this to a fully-qualified import path
// once you place this file into your project.
// For example,
//
// sw "github.com/myname/myrepo/{{apiPath}}"
//
sw "./{{apiPath}}"
"log"
"net/http"
)
func main() {
log.Printf("Server started")
router := sw.NewRouter()
log.Fatal(http.ListenAndServe(":{{serverPort}}", router))
}

View File

@ -0,0 +1,54 @@
package {{packageName}}
import (
"net/http"
"fmt"
"github.com/gorilla/mux"
)
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
func NewRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
var handler http.Handler
handler = route.HandlerFunc
handler = Logger(handler, route.Name)
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(handler)
}
return router
}
func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World!")
}
var routes = Routes{
Route{
"Index",
"GET",
"/",
Index,
},
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}
Route{
"{{operationId}}",
"{{httpMethod}}",
"{{path}}",
{{operationId}},
},
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
}

View File

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

View File

@ -1,5 +1,23 @@
<?php <?php
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace App\Http\Middleware; namespace App\Http\Middleware;
use Closure; use Closure;

View File

@ -0,0 +1,28 @@
<?php
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController;
class Controller extends BaseController
{
//
}

View File

@ -1,5 +1,23 @@
<?php <?php
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace App\Exceptions; namespace App\Exceptions;
use Exception; use Exception;

View File

@ -0,0 +1,47 @@
<?php
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Laravel\Lumen\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
//
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
//
}
}

View File

@ -0,0 +1,52 @@
<?php
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace App;
use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
class User extends Model implements
AuthenticatableContract,
AuthorizableContract
{
use Authenticatable, Authorizable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email',
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'password',
];
}

View File

@ -0,0 +1,108 @@
<?php
{{>licenseInfo}}
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Request;
{{#operations}}class {{classname}} extends Controller
{
/**
* Constructor
*/
public function __construct()
{
}
{{#operation}}
/**
* Operation {{{operationId}}}
*
* {{{summary}}}.
*
{{#pathParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/pathParams}} *
* @return Http response
*/
public function {{operationId}}({{#pathParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/pathParams}})
{
$input = Request::all();
//path params validation
{{#pathParams}}
{{#hasValidation}}
{{#maxLength}}
if (strlen(${{paramName}}]) > {{maxLength}}) {
throw new \InvalidArgumentException('invalid length for ${{paramName}} when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maxLength}}.');
}
{{/maxLength}}
{{#minLength}}
if (strlen(${{paramName}}]) < {{minLength}}) {
throw new \InvalidArgumentException('invalid length for ${{paramName}} when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minLength}}.');
}
{{/minLength}}
{{#maximum}}
if (${{paramName}}] > {{maximum}}) {
throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maximum}}.');
}
{{/maximum}}
{{#minimum}}
if (${{paramName}}] < {{minimum}}) {
throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minimum}}.');
}
{{/minimum}}
{{#pattern}}
if (!preg_match("{{pattern}}", ${{paramName}}])) {
throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must conform to the pattern {{pattern}}.');
}
{{/pattern}}
{{/hasValidation}}
{{/pathParams}}
//not path params validation
{{#allParams}}
{{^pathParams}}
{{#required}}
if (!isset($input['{{paramName}}'])) {
throw new \InvalidArgumentException('Missing the required parameter ${{paramName}} when calling {{operationId}}');
}
{{/required}}
{{#hasValidation}}
{{#maxLength}}
if (strlen($input['{{paramName}}']) > {{maxLength}}) {
throw new \InvalidArgumentException('invalid length for ${{paramName}} when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maxLength}}.');
}
{{/maxLength}}
{{#minLength}}
if (strlen($input['{{paramName}}']) < {{minLength}}) {
throw new \InvalidArgumentException('invalid length for ${{paramName}} when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minLength}}.');
}
{{/minLength}}
{{#maximum}}
if ($input['{{paramName}}'] > {{maximum}}) {
throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maximum}}.');
}
{{/maximum}}
{{#minimum}}
if ($input['{{paramName}}'] < {{minimum}}) {
throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minimum}}.');
}
{{/minimum}}
{{#pattern}}
if (!preg_match("{{pattern}}", $input['{{paramName}}'])) {
throw new \InvalidArgumentException('invalid value for ${{paramName}} when calling {{classname}}.{{operationId}}, must conform to the pattern {{pattern}}.');
}
{{/pattern}}
{{/hasValidation}}
${{paramName}} = $input['{{paramName}}'];
{{/pathParams}}
{{/allParams}}
return response('How about implementing {{nickname}} as a {{httpMethod}} method ?');
}
{{/operation}}
}
{{/operations}}

View File

@ -1,5 +1,23 @@
<?php <?php
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once __DIR__.'/../vendor/autoload.php'; require_once __DIR__.'/../vendor/autoload.php';
try { try {
@ -23,7 +41,7 @@ $app = new Laravel\Lumen\Application(
realpath(__DIR__.'/../') realpath(__DIR__.'/../')
); );
// $app->withFacades(); $app->withFacades();
// $app->withEloquent(); // $app->withEloquent();
@ -48,8 +66,6 @@ $app->singleton(
App\Console\Kernel::class App\Console\Kernel::class
); );
class_alias('Illuminate\Support\Facades\Request', 'Request'); //to use the Reqesut facade
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Register Middleware | Register Middleware

View File

@ -1,29 +0,0 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Laravel\Lumen\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
//
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
//
}
}

View File

@ -1,10 +0,0 @@
<?php
namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController;
class Controller extends BaseController
{
//
}

View File

@ -1,18 +0,0 @@
<?php
namespace App\Http\Controllers;
class ExampleController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
//
}
//
}

View File

@ -1,20 +0,0 @@
<?php
namespace App\Http\Middleware;
use Closure;
class ExampleMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request);
}
}

View File

@ -1,28 +0,0 @@
<?php
{{#apiInfo}}/**
* {{appName}}
* @version {{appVersion}}
*/
$app->get('/', function () use ($app) {
return $app->version();
});
{{#apis}}{{#operations}}{{#operation}}
/**
* {{httpMethod}} {{nickname}}
* Summary: {{summary}}
* Notes: {{notes}}
{{#hasProduces}} * Output-Formats: [{{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}]{{/hasProduces}}
*/
$app->{{httpMethod}}('{{path}}', function({{#pathParams}}${{paramName}}, {{/pathParams}}$null = null) use ($app) {
{{#hasHeaderParams}}$headers = Request::header();{{/hasHeaderParams}}
{{#hasQueryParams}}{{#queryParams}}${{paramName}} = Request::input('{{paramName}}');{{newline}}
{{/queryParams}}{{/hasQueryParams}}
{{#hasFormParams}}{{#formParams}}${{paramName}} = Request::input('{{paramName}}');{{newline}} {{/formParams}}{{/hasFormParams}}
return response('How about implementing {{nickname}} as a {{httpMethod}} method ?');
});
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}

View File

@ -1,18 +0,0 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}

View File

@ -1,40 +0,0 @@
<?php
namespace App\Providers;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Boot the authentication services for the application.
*
* @return void
*/
public function boot()
{
// Here you may define how you wish users to be authenticated for your Lumen
// application. The callback which receives the incoming request instance
// should return either a User instance or null. You're free to obtain
// the User instance via an API token or any other method necessary.
Auth::viaRequest('api', function ($request) {
if ($request->input('api_token')) {
return User::where('api_token', $request->input('api_token'))->first();
}
});
}
}

View File

@ -1,19 +0,0 @@
<?php
namespace App\Providers;
use Laravel\Lumen\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'App\Events\SomeEvent' => [
'App\Listeners\EventListener',
],
];
}

View File

@ -1,34 +0,0 @@
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
class User extends Model implements
AuthenticatableContract,
AuthorizableContract
{
use Authenticatable, Authorizable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email',
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'password',
];
}

View File

@ -1,17 +0,0 @@
{
"name": "laravel/lumen",
"description": "The Laravel Lumen Framework.",
"keywords": ["framework", "laravel", "lumen"],
"license": "MIT",
"type": "project",
"require": {
"php": ">=5.5.9",
"laravel/lumen-framework": "5.2.*",
"vlucas/phpdotenv": "~2.2"
},
"autoload": {
"psr-4": {
"App\\": "app/"
}
}
}

View File

@ -0,0 +1,31 @@
{
"name": "{{#composerVendorName}}{{.}}{{/composerVendorName}}{{^composerVendorName}}{{gitUserId}}{{/composerVendorName}}/{{#composerProjectName}}{{.}}{{/composerProjectName}}{{^composerProjectName}}{{gitRepoId}}{{/composerProjectName}}",
{{#artifactVersion}}
"version": "{{artifactVersion}}",
{{/artifactVersion}}
"description": "{{description}}",
"keywords": [
"swagger",
"php",
"sdk",
"api"
],
"homepage": "http://swagger.io",
"license": "Apache v2",
"authors": [
{
"name": "Swagger and contributors",
"homepage": "https://github.com/swagger-api/swagger-codegen"
}
],
"require": {
"php": ">=5.5.9",
"laravel/lumen-framework": "5.2.*",
"vlucas/phpdotenv": "~2.2"
},
"autoload": {
"psr-4": {
"App\\": "app/"
}
}
}

View File

@ -1,5 +1,23 @@
<?php <?php
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Create The Application | Create The Application

View File

@ -0,0 +1,23 @@
/**
* {{{appName}}}
* {{{appDescription}}}
*
* {{#version}}OpenAPI spec version: {{{version}}}{{/version}}
* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}}
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

View File

@ -1,16 +0,0 @@
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

View File

@ -1,21 +1,16 @@
## Lumen PHP Framework # Swagger generated server
[![Build Status](https://travis-ci.org/laravel/lumen-framework.svg)](https://travis-ci.org/laravel/lumen-framework) ## Overview
[![Total Downloads](https://poser.pugx.org/laravel/lumen-framework/d/total.svg)](https://packagist.org/packages/laravel/lumen-framework) This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the
[![Latest Stable Version](https://poser.pugx.org/laravel/lumen-framework/v/stable.svg)](https://packagist.org/packages/laravel/lumen-framework) [OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This
[![Latest Unstable Version](https://poser.pugx.org/laravel/lumen-framework/v/unstable.svg)](https://packagist.org/packages/laravel/lumen-framework) is an example of building a PHP server.
[![License](https://poser.pugx.org/laravel/lumen-framework/license.svg)](https://packagist.org/packages/laravel/lumen-framework)
Laravel Lumen is a stunningly fast PHP micro-framework for building web applications with expressive, elegant syntax. We believe development must be an enjoyable, creative experience to be truly fulfilling. Lumen attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as routing, database abstraction, queueing, and caching. This example uses the [Lumen Framework](http://lumen.laravel.com/). To see how to make this your own, please take a look at the template here:
## Official Documentation [TEMPLATES](https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/main/resources/slim/)
Documentation for the framework can be found on the [Lumen website](http://lumen.laravel.com/docs). ## Installation & Usage
### Composer
## Security Vulnerabilities Using `composer install` to install the framework and dependencies via [Composer](http://getcomposer.org/).
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell at taylor@laravel.com. All security vulnerabilities will be promptly addressed.
### License
The Lumen framework is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT)

View File

@ -1,4 +1,6 @@
<?php <?php
{{>licenseInfo}}
{{#apiInfo}}/** {{#apiInfo}}/**
* {{appName}} * {{appName}}
* @version {{appVersion}} * @version {{appVersion}}
@ -8,21 +10,18 @@ $app->get('/', function () use ($app) {
return $app->version(); return $app->version();
}); });
{{#apis}}{{#operations}}{{#operation}} {{#apis}}
{{#operations}}
{{#operation}}
/** /**
* {{httpMethod}} {{nickname}} * {{httpMethod}} {{nickname}}
* Summary: {{summary}} * Summary: {{summary}}
* Notes: {{notes}} * Notes: {{notes}}
{{#hasProduces}} * Output-Formats: [{{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}]{{/hasProduces}} {{#hasProduces}} * Output-Formats: [{{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}]{{/hasProduces}}
*/ */
Route::{{httpMethod}}('{{path}}', function({{#pathParams}}${{paramName}}, {{/pathParams}}null) use ($app) { $app->{{httpMethod}}('{{path}}', '{{classname}}@{{operationId}}');
{{#hasHeaderParams}}$headers = Request::header();{{/hasHeaderParams}} {{/operation}}
{{#hasQueryParams}}{{#queryParams}}${{paramName}} = Request::input('{{paramName}}');{{newline}} {{/operations}}
{{/queryParams}}{{/hasQueryParams}} {{/apis}}
{{#hasFormParams}}{{#formParams}}${{paramName}} = Request::input('{{paramName}}');{{newline}} {{/formParams}}{{/hasFormParams}} {{/apiInfo}}
return response('How about implementing {{nickname}} as a {{httpMethod}} method ?');
});
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}

View File

@ -1,2 +0,0 @@
*
!.gitignore

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