Merge remote-tracking branch 'origin/master' into 3.4.x

This commit is contained in:
William Cheng 2018-10-26 21:04:25 +08:00
commit 3482a0a993
757 changed files with 23913 additions and 2474 deletions

View File

@ -15,7 +15,7 @@ elif [ "$NODE_INDEX" = "2" ]; then
java -version
#export GO_POST_PROCESS_FILE="/usr/local/bin/gofmt -w"
# not formatting the code as different go versions may format the code a bit different
#./bin/utils/ensure-up-to-date
./bin/utils/ensure-up-to-date
else
echo "Running node $NODE_INDEX to test 'samples.circleci.jdk7' defined in pom.xml ..."
sudo update-java-alternatives -s java-1.7.0-openjdk-amd64

View File

@ -12,6 +12,7 @@
- Search the [open issue](https://github.com/openapitools/openapi-generator/issues) to ensure no one else has reported something similar and no one is actively working on similar proposed change.
- If no one has suggested something similar, open an ["issue"](https://github.com/openapitools/openapi-generator/issues) with your suggestion to gather feedback from the community.
- If you're adding a new option to a generator, please consider using the `-t` option with customized templates instead or start a discussion first by opening an issue as we want to avoid adding too many options to the generator.
- It's recommended to **create a new git branch** for the change so that the merge commit message looks nicer in the commit history.
## How to contribute
@ -86,6 +87,7 @@ To test the templates, please perform the following:
- Run the tests in the sample folder, e.g. in `samples/client/petstore/ruby`, run `mvn integration-test -rf :RubyPetstoreClientTests`. (some languages may not contain unit testing for Petstore and we're looking for contribution from the community to implement those tests)
- Finally, git commit the updated samples files: `git commit -a`
(`git add -A` if added files with new test cases)
- For new test cases, please add to the [Fake Petstore spec](https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml)
To start the CI tests, you can run `mvn verify -Psamples` (assuming you've all the required tools installed to run tests for different languages) or you can leverage http://travis-ci.org to run the CI tests by adding your own openapi-generator repository.

View File

@ -668,7 +668,7 @@ If you want to join the committee, please kindly apply by sending an email to te
| Perl | @wing328 (2017/07) |
| PHP | @jebentier (2017/07) @dkarlovi (2017/07) @mandrean (2017/08) @jfastnacht (2017/09) @ackintosh (2017/09) @ybelenko (2018/07) |
| PowerShell | |
| Python | @taxpon (2017/07) @frol (2017/07) @mbohlool (2017/07) @cbornet (2017/09) @kenjones-cisco (2017/11)|
| Python | @taxpon (2017/07) @frol (2017/07) @mbohlool (2017/07) @cbornet (2017/09) @kenjones-cisco (2017/11) @tomplus (2018/10) |
| R | |
| Ruby | @cliffano (2017/07) @zlx (2017/09) |
| Rust | @frol (2017/07) @farcaller (2017/08) @bjgill (2017/12) |

View File

@ -27,6 +27,6 @@ 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/openapi-generator/src/test/resources/3_0/petstore.yaml -g elm -o samples/client/petstore/elm $@"
ags="generate -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g elm -t modules/openapi-generator/src/main/resources/elm -o samples/openapi3/client/petstore/elm --additional-properties elmPrefixCustomTypeVariants=true $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -27,6 +27,6 @@ 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 --artifact-id "openapiv3-jaxrs-jersey-petstore-server" -t modules/openapi-generator/src/main/resources/JavaJaxRS/ -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g jaxrs-jersey -o samples/server/petstore/jaxrs-jersey $@"
ags="generate --artifact-id "openapiv3-jaxrs-jersey-petstore-server" -t modules/openapi-generator/src/main/resources/JavaJaxRS/ -i modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml -g jaxrs-jersey -o samples/server/petstore/jaxrs-jersey -DhideGenerationTimestamp=true $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -27,6 +27,6 @@ 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/openapi-generator/src/main/resources/ruby-client -i modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml -g ruby -c bin/ruby-petstore.json -o samples/client/petstore/ruby $@"
ags="generate -t modules/openapi-generator/src/main/resources/ruby-client -i modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml -g ruby -c bin/ruby-petstore.json -o samples/client/petstore/ruby -DskipFormModel=true $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -26,7 +26,7 @@ then
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/openapi-generator/src/main/resources/rust -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g rust -o samples/client/petstore/rust -DpackageName=petstore_client $@"
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/rust -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g rust -o samples/client/petstore/rust -DpackageName=petstore_client --library=hyper $@"
java ${JAVA_OPTS} -jar ${executable} ${ags}

32
bin/rust-reqwest-petstore.sh Executable file
View File

@ -0,0 +1,32 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
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/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn -B clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/rust -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g rust -o samples/client/petstore/rust-reqwest -DpackageName=petstore_client --library=reqwest $@"
java ${JAVA_OPTS} -jar ${executable} ${ags}

View File

@ -10,9 +10,10 @@ echo "Please press CTRL+C to stop or the script will continue in 5 seconds."
sleep 5
# LIST OF SCRIPTS:
./bin/ruby-client-petstore.sh > /dev/null 2>&1
./bin/openapi3/ruby-client-petstore.sh > /dev/null 2>&1
./bin/java-petstore-all.sh > /dev/null 2>&1
./bin/java-jaxrs-petstore-server-all.sh > /dev/null 2>&1
./bin/openapi3/jaxrs-jersey-petstore.sh > /dev/null 2>&1
./bin/spring-all-pestore.sh > /dev/null 2>&1
./bin/kotlin-client-petstore.sh > /dev/null 2>&1
./bin/kotlin-client-string.sh > /dev/null 2>&1

View File

@ -5,6 +5,6 @@ If Not Exist %executable% (
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -t modules\openapi-generator\src\main\resources\erlang-server -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g erlang-server -o samples\client\petstore\erlang-server
set ags=generate -t modules\openapi-generator\src\main\resources\erlang-server -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g erlang-server -o samples\server\petstore\erlang-server
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -12,6 +12,7 @@ The following generators are available:
- [csharp](csharp.md)
- [csharp-dotnet2](csharp-dotnet2.md)
- [dart](dart.md)
- [dart-jaguar](dart-jaguar.md)
- [eiffel](eiffel.md)
- [elixir](elixir.md)
- [elm](elm.md)
@ -46,6 +47,7 @@ The following generators are available:
- [typescript-angular](typescript-angular.md)
- [typescript-angularjs](typescript-angularjs.md)
- [typescript-aurelia](typescript-aurelia.md)
- [typescript-axios](typescript-axios.md)
- [typescript-fetch](typescript-fetch.md)
- [typescript-inversify](typescript-inversify.md)
- [typescript-jquery](typescript-jquery.md)
@ -60,8 +62,8 @@ The following generators are available:
- [cpp-restbed-server](cpp-restbed-server.md)
- [csharp-nancyfx](csharp-nancyfx.md)
- [erlang-server](erlang-server.md)
- [go-server](go-server.md)
- [go-gin-server](go-gin-server.md)
- [go-server](go-server.md)
- [haskell](haskell.md)
- [java-inflector](java-inflector.md)
- [java-msf4j](java-msf4j.md)
@ -103,6 +105,10 @@ The following generators are available:
- [openapi-yaml](openapi-yaml.md)
* SCHEMA generators:
- [mysql-schema](mysql-schema.md)
* CONFIG generators:
- [apache2](apache2.md)

View File

@ -6,4 +6,7 @@ CONFIG OPTIONS for elm
0.19 - Elm 0.19
0.18 - Elm 0.18
elmPrefixCustomTypeVariants
Prefix custom type variants (Default: false)
Back to the [generators list](README.md)

View File

@ -4,4 +4,7 @@ CONFIG OPTIONS for erlang-server
packageName
Erlang package name (convention: lowercase). (Default: openapi)
openAPISpecName
Openapi Spec Name. (Default: openapi)
Back to the [generators list](README.md)

View File

@ -2,7 +2,7 @@
CONFIG OPTIONS for lua
packageName
Lua package name (convention: lowercase). (Default: openapir-client)
Lua package name (convention: single word). (Default: openapiclient)
packageVersion
Lua package version. (Default: 1.0.0-1)

View File

@ -10,4 +10,9 @@ CONFIG OPTIONS for rust
hideGenerationTimestamp
Hides the generation timestamp when files are generated. (Default: true)
library
library template (sub-template) to use. (Default: hyper)
hyper - HTTP client: Hyper.
reqwest - HTTP client: Reqwest.
Back to the [generators list](README.md)

View File

@ -152,6 +152,9 @@ CONFIG OPTIONS for spring
useBeanValidation
Use BeanValidation API annotations (Default: true)
performBeanValidation
Use Bean Validation Impl. to perform BeanValidation (Default: false)
implicitHeaders
Use of @ApiImplicitParams for headers. (Default: false)
@ -164,6 +167,9 @@ CONFIG OPTIONS for spring
useOptional
Use Optional container for optional parameters (Default: false)
hateoas
Use Spring HATEOAS library to allow adding HATEOAS links (Default: false)
library
library template (sub-template) to use (Default: spring-boot)
spring-boot - Spring-boot Server application using the SpringFox integration.

View File

@ -247,9 +247,10 @@ If your API client is using named parameters in the function call (e.g. Perl req
The following gnereators are not yet fully migrated and tested
- ~~rust-server~~ (migrated)
- `apex` (migration scheduled in Jul/Aug 2018)
- ~~`apex`~~ (migrated)
and we welcome contributions from the community to help with the migration
and we welcome contributions from the community to help with the migration.
UPDATE: all generators have been successfullly migrated.
[Back to OpenAPI-Generator's README page](../README.md)

View File

@ -88,7 +88,7 @@
<dependency>
<groupId>io.airlift</groupId>
<artifactId>airline</artifactId>
<version>0.7</version>
<version>0.8</version>
</dependency>
<dependency>
<groupId>com.googlecode.lambdaj</groupId>

View File

@ -84,7 +84,8 @@ public class CompletionCommand
null,
null,
suggesterMetadata.getMetadataInjections(),
bindings.build());
bindings.build(),
new DefaultCommandFactory<Suggester>());
return suggester.suggest();
}

View File

@ -35,6 +35,7 @@ import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
@ -571,6 +572,7 @@ public class CodeGenMojo extends AbstractMojo {
}
return;
}
adjustAdditionalProperties(config);
try {
new DefaultGenerator().opts(input).generate();
} catch (Exception e) {
@ -608,4 +610,30 @@ public class CodeGenMojo extends AbstractMojo {
}
}
}
/**
* This method enables conversion of true/false strings in
* config.additionalProperties (configuration/configOptions) to proper booleans.
* This enables mustache files to handle the properties better.
*
* @param config
*/
private void adjustAdditionalProperties(final CodegenConfig config) {
Map<String, Object> configAdditionalProperties = config.additionalProperties();
Set<String> keySet = configAdditionalProperties.keySet();
for (String key : keySet) {
Object value = configAdditionalProperties.get(key);
if (value != null) {
if (value instanceof String) {
String stringValue = (String) value;
if (stringValue.equalsIgnoreCase("true")) {
configAdditionalProperties.put(key, Boolean.TRUE);
} else if (stringValue.equalsIgnoreCase("false")) {
configAdditionalProperties.put(key, Boolean.FALSE);
}
}
} else {
configAdditionalProperties.put(key, Boolean.FALSE);
}
}
}
}

View File

@ -278,4 +278,5 @@ public class CodegenConstants {
public static final String ENABLE_POST_PROCESS_FILE = "enablePostProcessFile";
public static final String ENABLE_POST_PROCESS_FILE_DESC = "Enable post-processing file using environment variables.";
public static final String OPEN_API_SPEC_NAME = "openAPISpecName";
}

View File

@ -25,13 +25,13 @@ import java.util.Map;
public class CodegenParameter {
public boolean isFormParam, isQueryParam, isPathParam, isHeaderParam,
isCookieParam, isBodyParam, hasMore, isContainer,
secondaryParam, isCollectionFormatMulti, isPrimitiveType;
secondaryParam, isCollectionFormatMulti, isPrimitiveType, isModel;
public String baseName, paramName, dataType, datatypeWithEnum, dataFormat,
collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName;
public String example; // example value (x-example)
public String jsonSchema;
public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid;
public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid, isEmail;
public boolean isListContainer, isMapContainer;
public boolean isFile;
public boolean isEnum;
@ -110,6 +110,7 @@ public class CodegenParameter {
output.collectionFormat = this.collectionFormat;
output.isCollectionFormatMulti = this.isCollectionFormatMulti;
output.isPrimitiveType = this.isPrimitiveType;
output.isModel = this.isModel;
output.description = this.description;
output.unescapedDescription = this.unescapedDescription;
output.baseType = this.baseType;
@ -165,6 +166,7 @@ public class CodegenParameter {
output.isDate = this.isDate;
output.isDateTime = this.isDateTime;
output.isUuid = this.isUuid;
output.isEmail = this.isEmail;
output.isListContainer = this.isListContainer;
output.isMapContainer = this.isMapContainer;
@ -201,6 +203,8 @@ public class CodegenParameter {
return false;
if (isPrimitiveType != that.isPrimitiveType)
return false;
if (isModel != that.isModel)
return false;
if (baseName != null ? !baseName.equals(that.baseName) : that.baseName != null)
return false;
if (paramName != null ? !paramName.equals(that.paramName) : that.paramName != null)
@ -253,6 +257,8 @@ public class CodegenParameter {
return false;
if (isUuid != that.isUuid)
return false;
if (isEmail != that.isEmail)
return false;
if (isListContainer != that.isListContainer)
return false;
if (isMapContainer != that.isMapContainer)
@ -312,6 +318,7 @@ public class CodegenParameter {
result = 31 * result + (secondaryParam ? 13:31);
result = 31 * result + (isCollectionFormatMulti ? 13:31);
result = 31 * result + (isPrimitiveType ? 13:31);
result = 31 * result + (isModel ? 13:31);
result = 31 * result + (baseName != null ? baseName.hashCode() : 0);
result = 31 * result + (paramName != null ? paramName.hashCode() : 0);
result = 31 * result + (dataType != null ? dataType.hashCode() : 0);
@ -338,6 +345,7 @@ public class CodegenParameter {
result = 31 * result + (isDate ? 13:31);
result = 31 * result + (isDateTime ? 13:31);
result = 31 * result + (isUuid ? 13:31);
result = 31 * result + (isEmail ? 13:31);
result = 31 * result + (isListContainer ? 13:31);
result = 31 * result + (isMapContainer ? 13:31);
result = 31 * result + (isFile ? 13:31);
@ -378,6 +386,7 @@ public class CodegenParameter {
", secondaryParam=" + secondaryParam +
", isCollectionFormatMulti=" + isCollectionFormatMulti +
", isPrimitiveType=" + isPrimitiveType +
", isModel=" + isModel +
", baseName='" + baseName + '\'' +
", paramName='" + paramName + '\'' +
", dataType='" + dataType + '\'' +
@ -404,6 +413,7 @@ public class CodegenParameter {
", isDate=" + isDate +
", isDateTime=" + isDateTime +
", isUuid=" + isUuid +
", isEmail=" + isEmail +
", isListContainer=" + isListContainer +
", isMapContainer=" + isMapContainer +
", isFile=" + isFile +

View File

@ -55,8 +55,8 @@ public class CodegenProperty implements Cloneable {
public boolean exclusiveMaximum;
public boolean hasMore, required, secondaryParam;
public boolean hasMoreNonReadOnly; // for model constructor, true if next property is not readonly
public boolean isPrimitiveType, isContainer, isNotContainer;
public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBinary, isFile, isBoolean, isDate, isDateTime, isUuid;
public boolean isPrimitiveType, isModel, isContainer, isNotContainer;
public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBinary, isFile, isBoolean, isDate, isDateTime, isUuid, isEmail;
public boolean isListContainer, isMapContainer;
public boolean isEnum;
public boolean isReadOnly;
@ -438,6 +438,7 @@ public class CodegenProperty implements Cloneable {
result = prime * result + (isEnum ? 1231 : 1237);
result = prime * result + ((isNotContainer ? 13:31));
result = prime * result + ((isPrimitiveType ? 13:31));
result = prime * result + ((isModel ? 13:31));
result = prime * result + ((isReadOnly ? 13:31));
result = prime * result + ((isWriteOnly ? 13:31));
result = prime * result + ((isNullable ? 13:31));
@ -472,6 +473,7 @@ public class CodegenProperty implements Cloneable {
result = prime * result + ((isDate ? 13:31));
result = prime * result + ((isDateTime ? 13:31));
result = prime * result + ((isUuid ? 13:31));
result = prime * result + ((isEmail ? 13:31));
result = prime * result + ((isMapContainer ? 13:31));
result = prime * result + ((isListContainer ? 13:31));
result = prime * result + Objects.hashCode(isInherited);
@ -579,6 +581,9 @@ public class CodegenProperty implements Cloneable {
if (this.isPrimitiveType != other.isPrimitiveType) {
return false;
}
if (this.isModel != other.isModel) {
return false;
}
if (this.isContainer != other.isContainer) {
return false;
}
@ -649,6 +654,9 @@ public class CodegenProperty implements Cloneable {
if (this.isUuid != other.isUuid) {
return false;
}
if (this.isEmail != other.isEmail) {
return false;
}
if (this.isBinary != other.isBinary) {
return false;
}
@ -759,6 +767,7 @@ public class CodegenProperty implements Cloneable {
", secondaryParam=" + secondaryParam +
", hasMoreNonReadOnly=" + hasMoreNonReadOnly +
", isPrimitiveType=" + isPrimitiveType +
", isModel=" + isModel +
", isContainer=" + isContainer +
", isNotContainer=" + isNotContainer +
", isString=" + isString +
@ -775,6 +784,7 @@ public class CodegenProperty implements Cloneable {
", isDate=" + isDate +
", isDateTime=" + isDateTime +
", isUuid=" + isUuid +
", isEmail=" + isEmail +
", isListContainer=" + isListContainer +
", isMapContainer=" + isMapContainer +
", isEnum=" + isEnum +

View File

@ -30,7 +30,7 @@ public class CodegenResponse {
public List<Map<String, Object>> examples;
public String dataType, baseType, containerType;
public boolean hasHeaders;
public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBoolean, isDate, isDateTime, isUuid;
public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isByteArray, isBoolean, isDate, isDateTime, isUuid, isEmail;
public boolean isDefault;
public boolean simpleType;
public boolean primitiveType;

View File

@ -1895,6 +1895,9 @@ public class DefaultCodegen implements CodegenConfig {
// keep isString to true to make it backward compatible
property.isString = true;
property.isUuid = true;
} else if (ModelUtils.isEmailSchema(p)) {
property.isString = true;
property.isEmail = true;
} else {
property.isString = true;
}
@ -2175,6 +2178,7 @@ public class DefaultCodegen implements CodegenConfig {
property.isPrimitiveType = true;
} else {
property.complexType = property.baseType;
property.isModel = true;
}
}
@ -2578,8 +2582,9 @@ public class DefaultCodegen implements CodegenConfig {
}
r.dataType = cp.dataType;
if (Boolean.TRUE.equals(cp.isString) && Boolean.TRUE.equals(cp.isUuid)) {
if (Boolean.TRUE.equals(cp.isString) && Boolean.TRUE.equals(cp.isEmail)) {
r.isEmail = true;
} else if (Boolean.TRUE.equals(cp.isString) && Boolean.TRUE.equals(cp.isUuid)) {
r.isUuid = true;
} else if (Boolean.TRUE.equals(cp.isByteArray)) {
r.isByteArray = true;
@ -3840,8 +3845,9 @@ public class DefaultCodegen implements CodegenConfig {
LOGGER.error("Codegen Property cannot be null.");
return;
}
if (Boolean.TRUE.equals(property.isUuid) && Boolean.TRUE.equals(property.isString)) {
if (Boolean.TRUE.equals(property.isEmail) && Boolean.TRUE.equals(property.isString)) {
parameter.isEmail = true;
} else if (Boolean.TRUE.equals(property.isUuid) && Boolean.TRUE.equals(property.isString)) {
parameter.isUuid = true;
} else if (Boolean.TRUE.equals(property.isByteArray)) {
parameter.isByteArray = true;
@ -4515,6 +4521,9 @@ public class DefaultCodegen implements CodegenConfig {
schema.setName(name);
codegenModel = fromModel(name, schema, schemas);
}
if (codegenModel != null) {
codegenParameter.isModel = true;
}
if (codegenModel != null && !codegenModel.emptyVars) {
if (StringUtils.isEmpty(bodyParameterName)) {

View File

@ -500,6 +500,7 @@ public class InlineModelResolver {
model.setExample(example);
model.setName(object.getName());
model.setXml(xml);
model.setRequired(object.getRequired());
if (properties != null) {
flattenProperties(properties, path);
model.setProperties(properties);
@ -545,6 +546,9 @@ public class InlineModelResolver {
public void copyVendorExtensions(Schema source, Schema target) {
Map<String, Object> vendorExtensions = source.getExtensions();
if (vendorExtensions == null) {
return;
}
for (String extName : vendorExtensions.keySet()) {
target.addExtension(extName, vendorExtensions.get(extName));
}

View File

@ -549,7 +549,6 @@ public class CodegenConfigurator implements Serializable {
final List<AuthorizationValue> authorizationValues = AuthParser.parse(auth);
ParseOptions options = new ParseOptions();
options.setResolve(true);
options.setFlatten(true);
SwaggerParseResult result = new OpenAPIParser().readLocation(inputSpec, authorizationValues, options);
Set<String> validationMessages = new HashSet<>(result.getMessages());

View File

@ -27,6 +27,7 @@ import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.CliOption;
@ -212,6 +213,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
public void processOpts() {
super.processOpts();
if (StringUtils.isEmpty(System.getenv("JAVA_POST_PROCESS_FILE"))) {
LOGGER.info("Environment variable JAVA_POST_PROCESS_FILE not defined so the Java code may not be properly formatted. To define it, try 'export JAVA_POST_PROCESS_FILE=\"/usr/local/bin/clang-format -i\"' (Linux/Mac)");
}
if (additionalProperties.containsKey(SUPPORT_JAVA6)) {
this.setSupportJava6(Boolean.valueOf(additionalProperties.get(SUPPORT_JAVA6).toString()));
}
@ -226,7 +231,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
this.setBooleanGetterPrefix(additionalProperties.get(BOOLEAN_GETTER_PREFIX).toString());
}
additionalProperties.put(BOOLEAN_GETTER_PREFIX, booleanGetterPrefix);
if (additionalProperties.containsKey(USE_NULL_FOR_UNKNOWN_ENUM_VALUE)) {
this.setUseNullForUnknownEnumValue(Boolean.valueOf(additionalProperties.get(USE_NULL_FOR_UNKNOWN_ENUM_VALUE).toString()));
}
@ -1382,6 +1386,35 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
return tag;
}
@Override
public void postProcessFile(File file, String fileType) {
if (file == null) {
return;
}
String javaPostProcessFile = System.getenv("JAVA_POST_PROCESS_FILE");
if (StringUtils.isEmpty(javaPostProcessFile)) {
return; // skip if JAVA_POST_PROCESS_FILE env variable is not defined
}
// only process files with hs extension
if ("java".equals(FilenameUtils.getExtension(file.toString()))) {
String command = javaPostProcessFile + " " + file.toString();
try {
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
int exitValue = p.exitValue();
if (exitValue != 0) {
LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue);
} else {
LOGGER.info("Successfully executed: " + command);
}
} catch (Exception e) {
LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage());
}
}
}
public void setParentGroupId(final String parentGroupId) {
this.parentGroupId = parentGroupId;
}

View File

@ -82,8 +82,7 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen {
apiTemplateFiles.put("api-header.mustache", ".h");
apiTemplateFiles.put("api-source.mustache", ".cpp");
apiTemplateFiles.put("api-impl-header.mustache", ".h");
apiTemplateFiles.put("api-impl-source.mustache", ".cpp");
apiTemplateFiles.put("main-api-server.mustache", ".cpp");
apiTemplateFiles.put("api-impl-source.mustache", ".cpp");
embeddedTemplateDir = templateDir = "cpp-pistache-server";
@ -97,6 +96,7 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen {
supportingFiles.add(new SupportingFile("modelbase-source.mustache", "model", modelNamePrefix + "ModelBase.cpp"));
supportingFiles.add(new SupportingFile("helpers-header.mustache", "model", modelNamePrefix + "Helpers.h"));
supportingFiles.add(new SupportingFile("helpers-source.mustache", "model", modelNamePrefix + "Helpers.cpp"));
supportingFiles.add(new SupportingFile("main-api-server.mustache", "", modelNamePrefix + "main-api-server.cpp"));
supportingFiles.add(new SupportingFile("cmake.mustache", "", "CMakeLists.txt"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
@ -139,6 +139,7 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen {
supportingFiles.add(new SupportingFile("modelbase-source.mustache", "model", modelNamePrefix + "ModelBase.cpp"));
supportingFiles.add(new SupportingFile("helpers-header.mustache", "model", modelNamePrefix + "Helpers.h"));
supportingFiles.add(new SupportingFile("helpers-source.mustache", "model", modelNamePrefix + "Helpers.cpp"));
supportingFiles.add(new SupportingFile("main-api-server.mustache", "", modelNamePrefix + "main-api-server.cpp"));
supportingFiles.add(new SupportingFile("cmake.mustache", "", "CMakeLists.txt"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
}
@ -291,10 +292,6 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen {
int ix = result.lastIndexOf(File.separatorChar);
result = result.substring(0, ix) + result.substring(ix, result.length() - 4) + "Impl.cpp";
result = result.replace(apiFileFolder(), implFileFolder());
} else if (templateName.endsWith("api-server.mustache")) {
int ix = result.lastIndexOf(File.separatorChar);
result = result.substring(0, ix) + result.substring(ix, result.length() - 4) + "MainServer.cpp";
result = result.replace(apiFileFolder(), outputFolder);
}
return result;
}

View File

@ -38,6 +38,7 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
@ -154,7 +155,7 @@ public class CppRestSdkClientCodegen extends AbstractCppCodegen {
typeMapping.put("map", "std::map");
typeMapping.put("file", "HttpContent");
typeMapping.put("object", "Object");
typeMapping.put("binary", "std::string");
typeMapping.put("binary", "utility::string_t");
typeMapping.put("number", "double");
typeMapping.put("UUID", "utility::string_t");
typeMapping.put("ByteArray", "utility::string_t");
@ -249,6 +250,7 @@ public class CppRestSdkClientCodegen extends AbstractCppCodegen {
if (methodResponse != null) {
Schema response = ModelUtils.getSchemaFromResponse(methodResponse);
response = ModelUtils.unaliasSchema(openAPI.getComponents().getSchemas(), response);
if (response != null) {
CodegenProperty cm = fromProperty("response", response);
op.vendorExtensions.put("x-codegen-response", cm);
@ -276,6 +278,24 @@ public class CppRestSdkClientCodegen extends AbstractCppCodegen {
}
}
// override with any special post-processing
@SuppressWarnings("unchecked")
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
for(String hdr : op.imports) {
if(importMapping.containsKey(hdr)) {
continue;
}
operations.put("hasModelImport", true);
break;
}
}
return objs;
}
protected boolean isFileSchema(CodegenProperty property) {
return property.baseType.equals("HttpContent");
}

View File

@ -59,8 +59,10 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(ElmClientCodegen.class);
private Set<String> customPrimitives = new HashSet<String>();
private ElmVersion elmVersion = ElmVersion.ELM_019;
private Boolean elmPrefixCustomTypeVariants = false;
private static final String ELM_VERSION = "elmVersion";
private static final String ELM_PREFIX_CUSTOM_TYPE_VARIANTS = "elmPrefixCustomTypeVariants";
private static final String ENCODER = "elmEncoder";
private static final String DECODER = "elmDecoder";
private static final String DISCRIMINATOR_NAME = "discriminatorName";
@ -162,13 +164,14 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
supportedVersions.put("0.19", "Elm 0.19");
elmVersion.setEnum(supportedVersions);
cliOptions.add(elmVersion);
final CliOption elmPrefixCustomTypeVariants = CliOption.newBoolean(ELM_PREFIX_CUSTOM_TYPE_VARIANTS, "Prefix custom type variants");
cliOptions.add(elmPrefixCustomTypeVariants);
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(ELM_VERSION)) {
final String version = (String) additionalProperties.get(ELM_VERSION);
if ("0.18".equals(version)) {
@ -178,6 +181,10 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
}
}
if (additionalProperties.containsKey(ELM_PREFIX_CUSTOM_TYPE_VARIANTS)) {
elmPrefixCustomTypeVariants = Boolean.TRUE.equals(Boolean.valueOf(additionalProperties.get(ELM_PREFIX_CUSTOM_TYPE_VARIANTS).toString()));
}
if (StringUtils.isEmpty(System.getenv("ELM_POST_PROCESS_FILE"))) {
if (elmVersion.equals(ElmVersion.ELM_018)) { // 0.18
LOGGER.info("Environment variable ELM_POST_PROCESS_FILE not defined so the Elm code may not be properly formatted. To define it, try `export ELM_POST_PROCESS_FILE=\"/usr/local/bin/elm-format --elm-version={} --yes\"` (Linux/Mac)", "0.18");
@ -188,7 +195,7 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
switch (elmVersion) {
case ELM_018:
LOGGER.info("Elm version = 0.18");
LOGGER.info("Elm version: 0.18");
additionalProperties.put("isElm018", true);
supportingFiles.add(new SupportingFile("DateOnly018.mustache", "src", "DateOnly.elm"));
supportingFiles.add(new SupportingFile("DateTime018.mustache", "src", "DateTime.elm"));
@ -196,7 +203,7 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("Main018.mustache", "src", "Main.elm"));
break;
case ELM_019:
LOGGER.info("Elm version = 0.19");
LOGGER.info("Elm version: 0.19");
additionalProperties.put("isElm019", true);
supportingFiles.add(new SupportingFile("DateOnly.mustache", "src", "DateOnly.elm"));
supportingFiles.add(new SupportingFile("DateTime.mustache", "src", "DateTime.elm"));
@ -590,6 +597,28 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
addEncoderAndDecoder(parameter.vendorExtensions, parameter.dataType, isPrimitiveType ? DataTypeExposure.PRIMITIVE : DataTypeExposure.EXTERNAL);
}
@Override
public void updateCodegenPropertyEnum(final CodegenProperty property) {
super.updateCodegenPropertyEnum(property);
if (!elmPrefixCustomTypeVariants) {
return;
}
final Map<String, Object> allowableValues = property.allowableValues;
if (allowableValues == null) {
return;
}
final List<Map<String, Object>> enumVars = (ArrayList<Map<String, Object>>) allowableValues.get("enumVars");
if (enumVars == null) {
return;
}
final String prefix = toEnumName(property);
for (Map<String, Object> enumVar : enumVars) {
enumVar.put("name", prefix + enumVar.get("name"));
}
}
private boolean isPrimitiveDataType(String dataType) {
return languageSpecificPrimitives.contains(dataType);
}

View File

@ -40,6 +40,7 @@ public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig
protected String apiVersion = "1.0.0";
protected String apiPath = "src";
protected String packageName = "openapi";
protected String openApiSpecName = "openapi";
public ErlangServerCodegen() {
super();
@ -47,13 +48,6 @@ public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig
// set the output folder here
outputFolder = "generated-code/erlang-server";
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME));
} else {
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
}
;
/**
* Models. You can write model files using the modelTemplateFiles map.
* if you want to create one template for file, you can do so here.
@ -117,6 +111,27 @@ public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig
cliOptions.clear();
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Erlang package name (convention: lowercase).")
.defaultValue(this.packageName));
cliOptions.add(new CliOption(CodegenConstants.OPEN_API_SPEC_NAME, "Openapi Spec Name.")
.defaultValue(this.openApiSpecName));
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME));
} else {
additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName);
}
if (additionalProperties.containsKey(CodegenConstants.OPEN_API_SPEC_NAME)) {
setOpenApiSpecName((String) additionalProperties.get(CodegenConstants.OPEN_API_SPEC_NAME));
} else {
additionalProperties.put(CodegenConstants.OPEN_API_SPEC_NAME, openApiSpecName);
}
/**
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files
@ -135,7 +150,7 @@ public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig
supportingFiles.add(new SupportingFile("server.mustache", "", toSourceFilePath("server", "erl")));
supportingFiles.add(new SupportingFile("utils.mustache", "", toSourceFilePath("utils", "erl")));
supportingFiles.add(new SupportingFile("auth.mustache", "", toSourceFilePath("auth", "erl")));
supportingFiles.add(new SupportingFile("openapi.mustache", "", toPrivFilePath("openapi", "json")));
supportingFiles.add(new SupportingFile("openapi.mustache", "", toPrivFilePath(this.openApiSpecName, "json")));
supportingFiles.add(new SupportingFile("default_logic_handler.mustache", "", toSourceFilePath("default_logic_handler", "erl")));
supportingFiles.add(new SupportingFile("logic_handler.mustache", "", toSourceFilePath("logic_handler", "erl")));
writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md"));
@ -254,6 +269,10 @@ public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig
this.packageName = packageName;
}
public void setOpenApiSpecName(String openApiSpecName) {
this.openApiSpecName = openApiSpecName;
}
protected String toHandlerName(String name) {
return toModuleName(name) + "_handler";
}

View File

@ -269,10 +269,13 @@ public class JavaClientCodegen extends AbstractJavaCodegen
apiDocTemplateFiles.remove("api_doc.mustache");
}
if (!(FEIGN.equals(getLibrary()) || RESTTEMPLATE.equals(getLibrary()) || usesAnyRetrofitLibrary() || GOOGLE_API_CLIENT.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()))) {
if (!(FEIGN.equals(getLibrary()) || RESTTEMPLATE.equals(getLibrary()) || usesAnyRetrofitLibrary() || GOOGLE_API_CLIENT.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()) || WEBCLIENT.equals(getLibrary()))) {
supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java"));
supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java"));
supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java"));
}
if (!(FEIGN.equals(getLibrary()) || RESTTEMPLATE.equals(getLibrary()) || usesAnyRetrofitLibrary() || GOOGLE_API_CLIENT.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()))) {
supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java"));
}

View File

@ -17,27 +17,17 @@
package org.openapitools.codegen.languages;
import com.google.common.base.Strings;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.DefaultCodegen;
import org.openapitools.codegen.SupportingFile;
import org.openapitools.codegen.*;
import org.openapitools.codegen.utils.ModelUtils;
import org.openapitools.codegen.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.*;
public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
@ -45,6 +35,9 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String PACKAGE_NAME = "packageName";
public static final String PACKAGE_VERSION = "packageVersion";
public static final String HYPER_LIBRARY = "hyper";
public static final String REQWEST_LIBRARY = "reqwest";
protected String packageName = "openapi";
protected String packageVersion = "1.0.0";
protected String apiDocPath = "docs/";
@ -68,7 +61,6 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
super();
outputFolder = "generated-code/rust";
modelTemplateFiles.put("model.mustache", ".rs");
apiTemplateFiles.put("api.mustache", ".rs");
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
@ -141,6 +133,15 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC)
.defaultValue(Boolean.TRUE.toString()));
supportedLibraries.put(HYPER_LIBRARY, "HTTP client: Hyper.");
supportedLibraries.put(REQWEST_LIBRARY, "HTTP client: Reqwest.");
CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use.");
libraryOption.setEnum(supportedLibraries);
// set hyper as the default
libraryOption.setDefault(HYPER_LIBRARY);
cliOptions.add(libraryOption);
setLibrary(HYPER_LIBRARY);
}
@Override
@ -165,21 +166,34 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
if ( HYPER_LIBRARY.equals(getLibrary())){
additionalProperties.put(HYPER_LIBRARY, "true");
} else if (REQWEST_LIBRARY.equals(getLibrary())) {
additionalProperties.put(REQWEST_LIBRARY, "true");
} else {
LOGGER.error("Unknown library option (-l/--library): {}", getLibrary());
}
apiTemplateFiles.put(getLibrary() + "/api.mustache", ".rs");
modelPackage = packageName;
apiPackage = packageName;
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("configuration.mustache", apiFolder, "configuration.rs"));
supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml"));
supportingFiles.add(new SupportingFile("api_mod.mustache", apiFolder, "mod.rs"));
supportingFiles.add(new SupportingFile("client.mustache", apiFolder, "client.rs"));
supportingFiles.add(new SupportingFile("request.rs", apiFolder, "request.rs"));
supportingFiles.add(new SupportingFile("model_mod.mustache", modelFolder, "mod.rs"));
supportingFiles.add(new SupportingFile("lib.rs", "src", "lib.rs"));
supportingFiles.add(new SupportingFile("lib.mustache", "src", "lib.rs"));
supportingFiles.add(new SupportingFile("Cargo.mustache", "", "Cargo.toml"));
if (HYPER_LIBRARY.equals(getLibrary())) {
supportingFiles.add(new SupportingFile("request.rs", apiFolder, "request.rs"));
}
supportingFiles.add(new SupportingFile(getLibrary() + "/configuration.mustache", apiFolder, "configuration.rs"));
supportingFiles.add(new SupportingFile(getLibrary() + "/client.mustache", apiFolder, "client.rs"));
supportingFiles.add(new SupportingFile(getLibrary() + "/api_mod.mustache", apiFolder, "mod.rs"));
}
@Override
@ -209,7 +223,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
return name;
// snake_case, e.g. PetId => pet_id
name = org.openapitools.codegen.utils.StringUtils.underscore(name);
name = StringUtils.underscore(name);
// for reserved word or word starting with number, append _
if (isReservedWord(name))
@ -231,16 +245,17 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
public String toModelName(String name) {
// camelize the model name
// phone_number => PhoneNumber
return org.openapitools.codegen.utils.StringUtils.camelize(toModelFilename(name));
return StringUtils.camelize(toModelFilename(name));
}
@Override
public String toModelFilename(String name) {
if (!StringUtils.isEmpty(modelNamePrefix)) {
if (!Strings.isNullOrEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
if (!Strings.isNullOrEmpty(modelNameSuffix)) {
name = name + "_" + modelNameSuffix;
}
@ -258,7 +273,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
name = "model_" + name; // e.g. 200Response => Model200Response (after camelize)
}
return org.openapitools.codegen.utils.StringUtils.underscore(name);
return StringUtils.underscore(name);
}
@Override
@ -267,7 +282,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// e.g. PetApi.rs => pet_api.rs
return org.openapitools.codegen.utils.StringUtils.underscore(name) + "_api";
return StringUtils.underscore(name) + "_api";
}
@Override
@ -340,11 +355,11 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
// method name cannot use reserved keyword, e.g. return
if (isReservedWord(sanitizedOperationId)) {
LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + org.openapitools.codegen.utils.StringUtils.underscore("call_" + operationId));
LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + StringUtils.underscore("call_" + operationId));
sanitizedOperationId = "call_" + sanitizedOperationId;
}
return org.openapitools.codegen.utils.StringUtils.underscore(sanitizedOperationId);
return StringUtils.underscore(sanitizedOperationId);
}
@Override
@ -353,9 +368,15 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
Map<String, Object> objectMap = (Map<String, Object>) objs.get("operations");
@SuppressWarnings("unchecked")
List<CodegenOperation> operations = (List<CodegenOperation>) objectMap.get("operation");
Set<String> headerKeys = new HashSet<>();
for (CodegenOperation operation : operations) {
// http method verb conversion (e.g. PUT => Put)
operation.httpMethod = org.openapitools.codegen.utils.StringUtils.camelize(operation.httpMethod.toLowerCase(Locale.ROOT));
// http method verb conversion, depending on client library (e.g. Hyper: PUT => Put, Reqwest: PUT => put)
if (HYPER_LIBRARY.equals(getLibrary())) {
operation.httpMethod = StringUtils.camelize(operation.httpMethod.toLowerCase(Locale.ROOT));
} else if (REQWEST_LIBRARY.equals(getLibrary())) {
operation.httpMethod = operation.httpMethod.toLowerCase(Locale.ROOT);
}
// update return type to conform to rust standard
/*
if (operation.returnType != null) {
@ -407,6 +428,9 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
}*/
}
additionalProperties.put("headerKeys", headerKeys);
additionalProperties.putIfAbsent("authHeaderKey", "api-key");
return objs;
}

View File

@ -34,6 +34,7 @@ import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.SupportingFile;
import org.openapitools.codegen.languages.features.BeanValidationFeatures;
import org.openapitools.codegen.languages.features.OptionalFeatures;
import org.openapitools.codegen.languages.features.PerformBeanValidationFeatures;
import org.openapitools.codegen.utils.URLPathUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -51,7 +52,8 @@ import java.util.stream.Collectors;
public class SpringCodegen extends AbstractJavaCodegen
implements BeanValidationFeatures, OptionalFeatures {
implements BeanValidationFeatures, PerformBeanValidationFeatures,
OptionalFeatures {
private static final Logger LOGGER = LoggerFactory.getLogger(SpringCodegen.class);
public static final String TITLE = "title";
@ -74,6 +76,7 @@ public class SpringCodegen extends AbstractJavaCodegen
public static final String IMPLICIT_HEADERS = "implicitHeaders";
public static final String OPENAPI_DOCKET_CONFIG = "swaggerDocketConfig";
public static final String API_FIRST = "apiFirst";
public static final String HATEOAS = "hateoas";
protected String title = "OpenAPI Spring";
protected String configPackage = "org.openapitools.configuration";
@ -88,11 +91,13 @@ public class SpringCodegen extends AbstractJavaCodegen
protected String responseWrapper = "";
protected boolean useTags = false;
protected boolean useBeanValidation = true;
protected boolean performBeanValidation = false;
protected boolean implicitHeaders = false;
protected boolean openapiDocketConfig = false;
protected boolean apiFirst = false;
protected boolean useOptional = false;
protected boolean virtualService = false;
protected boolean hateoas = false;
public SpringCodegen() {
super();
@ -120,10 +125,12 @@ public class SpringCodegen extends AbstractJavaCodegen
cliOptions.add(CliOption.newBoolean(VIRTUAL_SERVICE, "Generates the virtual service. For more details refer - https://github.com/elan-venture/virtualan/wiki"));
cliOptions.add(CliOption.newBoolean(USE_TAGS, "use tags for creating interface and controller classnames", useTags));
cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations", useBeanValidation));
cliOptions.add(CliOption.newBoolean(PERFORM_BEANVALIDATION, "Use Bean Validation Impl. to perform BeanValidation", performBeanValidation));
cliOptions.add(CliOption.newBoolean(IMPLICIT_HEADERS, "Use of @ApiImplicitParams for headers.", implicitHeaders));
cliOptions.add(CliOption.newBoolean(OPENAPI_DOCKET_CONFIG, "Generate Spring OpenAPI Docket configuration class.", openapiDocketConfig));
cliOptions.add(CliOption.newBoolean(API_FIRST, "Generate the API from the OAI spec at server compile time (API first approach)", apiFirst));
cliOptions.add(CliOption.newBoolean(USE_OPTIONAL,"Use Optional container for optional parameters", useOptional));
cliOptions.add(CliOption.newBoolean(HATEOAS, "Use Spring HATEOAS library to allow adding HATEOAS links", hateoas));
supportedLibraries.put(SPRING_BOOT, "Spring-boot Server application using the SpringFox integration.");
supportedLibraries.put(SPRING_MVC_LIBRARY, "Spring-MVC Server application using the SpringFox integration.");
@ -245,6 +252,11 @@ public class SpringCodegen extends AbstractJavaCodegen
}
writePropertyBack(USE_BEANVALIDATION, useBeanValidation);
if (additionalProperties.containsKey(PERFORM_BEANVALIDATION)) {
this.setPerformBeanValidation(convertPropertyToBoolean(PERFORM_BEANVALIDATION));
}
writePropertyBack(PERFORM_BEANVALIDATION, performBeanValidation);
if (additionalProperties.containsKey(USE_OPTIONAL)) {
this.setUseOptional(convertPropertyToBoolean(USE_OPTIONAL));
}
@ -260,6 +272,10 @@ public class SpringCodegen extends AbstractJavaCodegen
if (additionalProperties.containsKey(API_FIRST)) {
this.setApiFirst(Boolean.valueOf(additionalProperties.get(API_FIRST).toString()));
}
if (additionalProperties.containsKey(HATEOAS)) {
this.setHateoas(Boolean.valueOf(additionalProperties.get(HATEOAS).toString()));
}
typeMapping.put("file", "Resource");
importMapping.put("Resource", "org.springframework.core.io.Resource");
@ -700,6 +716,10 @@ public class SpringCodegen extends AbstractJavaCodegen
public void setApiFirst(boolean apiFirst) {
this.apiFirst = apiFirst;
}
public void setHateoas(boolean hateoas) {
this.hateoas = hateoas;
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
@ -750,6 +770,10 @@ public class SpringCodegen extends AbstractJavaCodegen
this.useBeanValidation = useBeanValidation;
}
public void setPerformBeanValidation(boolean performBeanValidation) {
this.performBeanValidation = performBeanValidation;
}
@Override
public void setUseOptional(boolean useOptional) {
this.useOptional = useOptional;

View File

@ -69,7 +69,7 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig
additionalProperties.put("appName", "OpenAPI Sample");
additionalProperties.put("appDescription", "A sample OpenAPI server");
additionalProperties.put("infoUrl", "https//openapi-generator.tech");
additionalProperties.put("infoUrl", "https://openapi-generator.tech");
additionalProperties.put("infoEmail", "team@openapitools.org");
additionalProperties.put("licenseInfo", "All rights reserved");
additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html");

View File

@ -20,6 +20,7 @@ package org.openapitools.codegen.utils;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.callbacks.Callback;
import io.swagger.v3.oas.models.headers.Header;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.BinarySchema;
@ -167,40 +168,56 @@ public class ModelUtils {
if (paths != null) {
for (PathItem path : paths.values()) {
List<Operation> allOperations = path.readOperations();
if (allOperations != null) {
for (Operation operation : allOperations) {
//Params:
if (operation.getParameters() != null) {
for (Parameter p : operation.getParameters()) {
Parameter parameter = getReferencedParameter(openAPI, p);
if (parameter.getSchema() != null) {
visitSchema(openAPI, parameter.getSchema(), null, visitedSchemas, visitor);
}
}
}
visitPathItem(path, openAPI, visitor, visitedSchemas);
}
}
}
//RequestBody:
RequestBody requestBody = getReferencedRequestBody(openAPI, operation.getRequestBody());
if (requestBody != null && requestBody.getContent() != null) {
for (Entry<String, MediaType> e : requestBody.getContent().entrySet()) {
private static void visitPathItem(PathItem pathItem, OpenAPI openAPI, OpenAPISchemaVisitor visitor, List<String> visitedSchemas) {
List<Operation> allOperations = pathItem.readOperations();
if (allOperations != null) {
for (Operation operation : allOperations) {
//Params:
if (operation.getParameters() != null) {
for (Parameter p : operation.getParameters()) {
Parameter parameter = getReferencedParameter(openAPI, p);
if (parameter.getSchema() != null) {
visitSchema(openAPI, parameter.getSchema(), null, visitedSchemas, visitor);
}
}
}
//RequestBody:
RequestBody requestBody = getReferencedRequestBody(openAPI, operation.getRequestBody());
if (requestBody != null && requestBody.getContent() != null) {
for (Entry<String, MediaType> e : requestBody.getContent().entrySet()) {
if (e.getValue().getSchema() != null) {
visitSchema(openAPI, e.getValue().getSchema(), e.getKey(), visitedSchemas, visitor);
}
}
}
//Responses:
if (operation.getResponses() != null) {
for (ApiResponse r : operation.getResponses().values()) {
ApiResponse apiResponse = getReferencedApiResponse(openAPI, r);
if (apiResponse != null && apiResponse.getContent() != null) {
for (Entry<String, MediaType> e : apiResponse.getContent().entrySet()) {
if (e.getValue().getSchema() != null) {
visitSchema(openAPI, e.getValue().getSchema(), e.getKey(), visitedSchemas, visitor);
}
}
}
}
}
//Responses:
if (operation.getResponses() != null) {
for (ApiResponse r : operation.getResponses().values()) {
ApiResponse apiResponse = getReferencedApiResponse(openAPI, r);
if (apiResponse != null && apiResponse.getContent() != null) {
for (Entry<String, MediaType> e : apiResponse.getContent().entrySet()) {
if (e.getValue().getSchema() != null) {
visitSchema(openAPI, e.getValue().getSchema(), e.getKey(), visitedSchemas, visitor);
}
}
}
//Callbacks:
if (operation.getCallbacks() != null) {
for (Callback c : operation.getCallbacks().values()) {
Callback callback = getReferencedCallback(openAPI, c);
if (callback != null) {
for (PathItem p : callback.values()) {
visitPathItem(p, openAPI, visitor, visitedSchemas);
}
}
}
@ -603,6 +620,35 @@ public class ModelUtils {
return null;
}
/**
* If a Callback contains a reference to an other Callback with '$ref', returns the referenced Callback if it is found or the actual Callback in the other cases.
*
* @param openAPI specification being checked
* @param callback potentially containing a '$ref'
* @return callback without '$ref'
*/
public static Callback getReferencedCallback(OpenAPI openAPI, Callback callback) {
if (callback != null && StringUtils.isNotEmpty(callback.get$ref())) {
String name = getSimpleRef(callback.get$ref());
Callback referencedCallback = getCallback(openAPI, name);
if (referencedCallback != null) {
return referencedCallback;
}
}
return callback;
}
public static Callback getCallback(OpenAPI openAPI, String name) {
if (name == null) {
return null;
}
if (openAPI != null && openAPI.getComponents() != null && openAPI.getComponents().getCallbacks() != null) {
return openAPI.getComponents().getCallbacks().get(name);
}
return null;
}
/**
* Return the first defined Schema for a RequestBody
*

View File

@ -168,7 +168,7 @@ public class URLPathUtils {
*/
public static String getHost(OpenAPI openAPI) {
if (openAPI.getServers() != null && openAPI.getServers().size() > 0) {
return sanitizeUrl(openAPI.getServers().get(0).getUrl());
return sanitizeUrl(getServerURL(openAPI.getServers().get(0)).toString());
}
return LOCAL_HOST;
}

View File

@ -24,8 +24,9 @@ repositories {
}
ext {
swagger_annotations_version = "1.5.8"
jackson_version = "2.7.0"
swagger_annotations_version = "1.5.21"
jackson_version = "2.8.11"
jackson_databind_version = "2.8.11.2"
}
dependencies {
@ -34,7 +35,7 @@ dependencies {
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version"
compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_databind_version"
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5"
compile 'org.codehaus.groovy.modules.http-builder:http-builder:0.7.1'
}

View File

@ -133,7 +133,8 @@ if(hasProperty('target') && target == 'android') {
ext {
swagger_annotations_version = "1.5.17"
jackson_version = "{{^threetenbp}}2.8.9{{/threetenbp}}{{#threetenbp}}2.6.4{{/threetenbp}}"
jackson_version = "{{^threetenbp}}2.8.11{{/threetenbp}}{{#threetenbp}}2.6.4{{/threetenbp}}"
jackson_databind_version = "{{^threetenbp}}2.8.11.2{{/threetenbp}}{{#threetenbp}}2.6.4{{/threetenbp}}"
jersey_version = "1.19.4"
jodatime_version = "2.9.9"
junit_version = "4.12"
@ -145,7 +146,7 @@ dependencies {
compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version"
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version"
compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version"
{{#joda}}
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version"

View File

@ -119,7 +119,8 @@ if(hasProperty('target') && target == 'android') {
ext {
swagger_annotations_version = "1.5.21"
jackson_version = "2.8.7"
jackson_version = "2.8.11"
jackson_databind_version = "2.8.11.2"
{{#threetenbp}}
threepane_version = "2.6.4"
{{/threetenbp}}
@ -137,7 +138,7 @@ dependencies {
compile "io.github.openfeign.form:feign-form:$feign_form_version"
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version"
{{#joda}}
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version"
{{/joda}}

View File

@ -14,10 +14,11 @@ lazy val root = (project in file(".")).
"io.github.openfeign" % "feign-jackson" % "{{#useFeign10}}10.0.1{{/useFeign10}}{{^useFeign10}}9.4.0{{/useFeign10}}" % "compile",
"io.github.openfeign" % "feign-slf4j" % "{{#useFeign10}}10.0.1{{/useFeign10}}{{^useFeign10}}9.4.0{{/useFeign10}}" % "compile",
"io.github.openfeign.form" % "feign-form" % "2.1.0" % "compile",
"com.fasterxml.jackson.core" % "jackson-core" % "2.8.7" % "compile",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.8.7" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.8.7" % "compile",
"com.fasterxml.jackson.core" % "jackson-core" % "2.8.11" % "compile",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.8.11" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.8.11.2" % "compile",
"com.fasterxml.jackson.datatype" % "jackson-datatype-{{^java8}}joda{{/java8}}{{#java8}}jsr310{{/java8}}" % "2.8.7" % "compile",
"com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.6.4" % "compile",
"org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile",
"com.brsanthu" % "migbase64" % "2.2" % "compile",
"junit" % "junit" % "4.12" % "test",

View File

@ -235,7 +235,7 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
<version>${jackson-databind-version}</version>
</dependency>
{{#withXml}}
@ -302,7 +302,8 @@
<swagger-annotations-version>1.5.21</swagger-annotations-version>
<feign-version>{{#useFeign10}}10.0.1{{/useFeign10}}{{^useFeign10}}9.4.0{{/useFeign10}}</feign-version>
<feign-form-version>2.1.0</feign-form-version>
<jackson-version>2.8.9</jackson-version>
<jackson-version>2.8.11</jackson-version>
<jackson-databind-version>2.8.11.2</jackson-databind-version>
{{#threetenbp}}
<jackson-threetenbp-version>2.6.4</jackson-threetenbp-version>
{{/threetenbp}}

View File

@ -119,7 +119,8 @@ if(hasProperty('target') && target == 'android') {
ext {
swagger_annotations_version = "1.5.21"
jackson_version = "2.8.9"
jackson_version = "2.8.11"
jackson_databind_version = "2.8.11.2"
google_api_client_version = "1.23.0"
jersey_common_version = "2.25.1"
jodatime_version = "2.9.9"
@ -135,7 +136,7 @@ dependencies {
compile "org.glassfish.jersey.core:jersey-common:${jersey_common_version}"
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version"
compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version"
{{#java8}}
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version"

View File

@ -12,9 +12,9 @@ lazy val root = (project in file(".")).
"io.swagger" % "swagger-annotations" % "1.5.21",
"com.google.api-client" % "google-api-client" % "1.23.0",
"org.glassfish.jersey.core" % "jersey-common" % "2.25.1",
"com.fasterxml.jackson.core" % "jackson-core" % "2.8.9" % "compile",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.8.9" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.8.9" % "compile",
"com.fasterxml.jackson.core" % "jackson-core" % "2.8.11" % "compile",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.8.11" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.8.11.2" % "compile",
{{#withXml}}
"com.fasterxml.jackson.dataformat" % "jackson-dataformat-xml" % "2.8.9" % "compile",
{{/withXml}}

View File

@ -295,7 +295,8 @@
<swagger-annotations-version>1.5.21</swagger-annotations-version>
<google-api-client-version>1.23.0</google-api-client-version>
<jersey-common-version>2.25.1</jersey-common-version>
<jackson-version>2.8.9</jackson-version>
<jackson-version>2.8.11</jackson-version>
<jackson-databind-version>2.8.11.2</jackson-databind-version>
{{#joda}}
<jodatime-version>2.9.9</jodatime-version>
{{/joda}}

View File

@ -118,7 +118,8 @@ if(hasProperty('target') && target == 'android') {
ext {
swagger_annotations_version = "1.5.21"
jackson_version = "2.9.6"
jackson_version = "2.8.11"
jackson_databind_version = "2.8.11.2"
{{#supportJava6}}
jersey_version = "2.6"
commons_io_version=2.5
@ -140,7 +141,7 @@ dependencies {
compile "org.glassfish.jersey.media:jersey-media-json-jackson:$jersey_version"
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version"
{{#joda}}
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version"
{{/joda}}

View File

@ -13,9 +13,9 @@ lazy val root = (project in file(".")).
"org.glassfish.jersey.core" % "jersey-client" % {{#supportJava6}}"2.6"{{/supportJava6}}{{^supportJava6}}"2.25.1"{{/supportJava6}},
"org.glassfish.jersey.media" % "jersey-media-multipart" % {{#supportJava6}}"2.6"{{/supportJava6}}{{^supportJava6}}"2.25.1"{{/supportJava6}},
"org.glassfish.jersey.media" % "jersey-media-json-jackson" % {{#supportJava6}}"2.6"{{/supportJava6}}{{^supportJava6}}"2.25.1"{{/supportJava6}},
"com.fasterxml.jackson.core" % "jackson-core" % "2.8.9" % "compile",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.8.9" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.8.9" % "compile",
"com.fasterxml.jackson.core" % "jackson-core" % "2.8.11" % "compile",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.8.11" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.8.11.2" % "compile",
{{#joda}}
"com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.8.9" % "compile",
{{/joda}}

View File

@ -251,7 +251,7 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
<version>${jackson-databind-version}</version>
</dependency>
{{#withXml}}
@ -332,7 +332,8 @@
<commons_io_version>2.5</commons_io_version>
<commons_lang3_version>3.6</commons_lang3_version>
{{/supportJava6}}
<jackson-version>2.8.9</jackson-version>
<jackson-version>2.8.11</jackson-version>
<jackson-databind-version>2.8.11.2</jackson-databind-version>
{{#threetenbp}}
<threetenbp-version>2.6.4</threetenbp-version>
{{/threetenbp}}

View File

@ -117,13 +117,13 @@ if(hasProperty('target') && target == 'android') {
}
ext {
swagger_annotations_version = "1.5.18"
jackson_version = "2.8.6"
swagger_annotations_version = "1.5.21"
jackson_version = "2.8.11"
jackson_databind_version = "2.8.11.2"
threetenbp_version = "2.6.4"
jersey_version = "2.22.2"
resteasy_version = "3.1.3.Final"
{{^java8}}
jodatime_version = "2.9.4"
jodatime_version = "2.9.9"
{{/java8}}
{{#supportJava6}}
commons_io_version=2.5
@ -137,12 +137,9 @@ dependencies {
compile "org.jboss.resteasy:resteasy-client:$resteasy_version"
compile "org.jboss.resteasy:resteasy-multipart-provider:$resteasy_version"
compile "org.jboss.resteasy:resteasy-jackson2-provider:$resteasy_version"
compile "org.glassfish.jersey.core:jersey-client:$jersey_version"
compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version"
compile "org.glassfish.jersey.media:jersey-media-json-jackson:$jersey_version"
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version"
compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$threetenbp_version"
{{#java8}}
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version"

View File

@ -9,28 +9,25 @@ lazy val root = (project in file(".")).
publishArtifact in (Compile, packageDoc) := false,
resolvers += Resolver.mavenLocal,
libraryDependencies ++= Seq(
"io.swagger" % "swagger-annotations" % "1.5.18",
"org.glassfish.jersey.core" % "jersey-client" % "2.22.2",
"org.glassfish.jersey.media" % "jersey-media-multipart" % "2.22.2",
"org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.2",
"org.jboss.resteasy" % "resteasy-client" % "3.1.3.Final",
"org.jboss.resteasy" % "resteasy-multipart-provider" % "3.1.3.Final",
"org.jboss.resteasy" % "resteasy-jackson2-provider" % "3.1.3.Final",
"com.fasterxml.jackson.core" % "jackson-core" % "2.8.6",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.8.6",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.8.6",
"com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.6.4",
"io.swagger" % "swagger-annotations" % "1.5.21" % "compile",
"org.jboss.resteasy" % "resteasy-client" % "3.1.3.Final" % "compile",
"org.jboss.resteasy" % "resteasy-multipart-provider" % "3.1.3.Final" % "compile",
"org.jboss.resteasy" % "resteasy-jackson2-provider" % "3.1.3.Final" % "compile",
"com.fasterxml.jackson.core" % "jackson-core" % "2.8.11" % "compile",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.8.11" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.8.11.2" % "compile",
"com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.6.4" % "compile",
{{#java8}}
"com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.8.6",
"com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.8.6" % "compile",
{{/java8}}
{{^java8}}
"com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.7.5",
"joda-time" % "joda-time" % "2.9.4",
"com.brsanthu" % "migbase64" % "2.2",
"com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.7.5" % "compile",
"joda-time" % "joda-time" % "2.9.9" % "compile",
"com.brsanthu" % "migbase64" % "2.2" % "compile",
{{/java8}}
{{#supportJava6}}
"org.apache.commons" % "commons-lang3" % "3.5",
"commons-io" % "commons-io" % "2.5",
"org.apache.commons" % "commons-lang3" % "3.5" % "compile",
"commons-io" % "commons-io" % "2.5" % "compile",
{{/supportJava6}}
"junit" % "junit" % "4.12" % "test",
"com.novocode" % "junit-interface" % "0.10" % "test"

View File

@ -187,7 +187,7 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
<version>${jackson-databind-version}</version>
</dependency>
{{#withXml}}
@ -266,7 +266,8 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<swagger-annotations-version>1.5.21</swagger-annotations-version>
<resteasy-version>3.1.3.Final</resteasy-version>
<jackson-version>2.8.6</jackson-version>
<jackson-version>2.8.11</jackson-version>
<jackson-databind-version>2.8.11</jackson-databind-version>
<threetenbp-version>2.6.4</threetenbp-version>
{{^java8}}
<jodatime-version>2.9.9</jodatime-version>

View File

@ -119,7 +119,8 @@ if(hasProperty('target') && target == 'android') {
ext {
swagger_annotations_version = "1.5.21"
jackson_version = "2.8.9"
jackson_version = "2.8.11"
jackson_databind_version = "2.8.11.2"
spring_web_version = "4.3.9.RELEASE"
jodatime_version = "2.9.9"
junit_version = "4.12"
@ -133,7 +134,7 @@ dependencies {
compile "org.springframework:spring-web:$spring_web_version"
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version"
compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version"
{{#java8}}
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version"

View File

@ -241,7 +241,7 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
<version>${jackson-databind-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
@ -297,7 +297,8 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<swagger-annotations-version>1.5.21</swagger-annotations-version>
<spring-web-version>4.3.9.RELEASE</spring-web-version>
<jackson-version>2.8.9</jackson-version>
<jackson-version>2.8.11</jackson-version>
<jackson-databind-version>2.8.11.2</jackson-databind-version>
{{#joda}}
<jodatime-version>2.9.9</jodatime-version>
{{/joda}}

View File

@ -130,7 +130,8 @@ ext {
play_version = "2.5.14"
{{/play25}}
{{#play26}}
jackson_version = "2.8.10"
jackson_version = "2.8.11"
jackson_databind_version = "2.8.11"
play_version = "2.6.7"
{{/play26}}
{{/usePlayWS}}

View File

@ -30,9 +30,9 @@ lazy val root = (project in file(".")).
{{#play26}}
"com.typesafe.play" % "play-ahc-ws_2.12" % "2.6.7" % "compile",
"javax.validation" % "validation-api" % "1.1.0.Final" % "compile",
"com.fasterxml.jackson.core" % "jackson-core" % "2.8.10" % "compile",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.8.10" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.8.10" % "compile",
"com.fasterxml.jackson.core" % "jackson-core" % "2.8.11" % "compile",
"com.fasterxml.jackson.core" % "jackson-annotations" % "2.8.11" % "compile",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.8.11.2" % "compile",
{{/play26}}
"com.squareup.retrofit2" % "converter-jackson" % "2.3.0" % "compile",
{{/usePlayWS}}

View File

@ -363,7 +363,7 @@
<play-version>2.5.15</play-version>
{{/play25}}
{{#play26}}
<jackson-version>2.8.10</jackson-version>
<jackson-version>2.8.11</jackson-version>
<play-version>2.6.7</play-version>
{{/play26}}
{{/usePlayWS}}

View File

@ -277,7 +277,7 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<vertx-version>3.4.2</vertx-version>
<swagger-annotations-version>1.5.21</swagger-annotations-version>
<jackson-version>{{^threetenbp}}2.8.9{{/threetenbp}}{{#threetenbp}}2.6.4{{/threetenbp}}</jackson-version>
<jackson-version>{{^threetenbp}}2.8.11{{/threetenbp}}{{#threetenbp}}2.6.4{{/threetenbp}}</jackson-version>
<junit-version>4.12</junit-version>
</properties>
</project>

View File

@ -5,8 +5,7 @@ import {{invokerPackage}}.ApiClient;
{{#imports}}import {{import}};
{{/imports}}
{{^fullJavaUtil}}import java.util.ArrayList;
import java.util.HashMap;
{{^fullJavaUtil}}import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;{{/fullJavaUtil}}

View File

@ -2,7 +2,6 @@
package {{package}};
import {{invokerPackage}}.ApiException;
{{#imports}}import {{import}};
{{/imports}}
import org.junit.Test;
@ -28,12 +27,9 @@ public class {{classname}}Test {
* {{summary}}
*
* {{notes}}
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void {{operationId}}Test() throws ApiException {
public void {{operationId}}Test() {
{{#allParams}}
{{{dataType}}} {{paramName}} = null;
{{/allParams}}

View File

@ -96,7 +96,7 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
<version>${jackson-databind-version}</version>
</dependency>
{{#java8}}
@ -131,12 +131,13 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<swagger-annotations-version>1.5.20</swagger-annotations-version>
<spring-web-version>5.0.7.RELEASE</spring-web-version>
<jackson-version>2.9.5</jackson-version>
<jackson-version>2.8.11</jackson-version>
<jackson-databind-version>2.8.11.2</jackson-databind-version>
<junit-version>4.12</junit-version>
<reactor-version>3.1.8.RELEASE</reactor-version>
<reactor-netty-version>0.7.8.RELEASE</reactor-netty-version>
{{#joda}}
<jodatime-version>2.9.9</jodatime-version>
<jodatime-version>2.9.9</jodatime-version>
{{/joda}}
</properties>
</project>

View File

@ -31,6 +31,9 @@ import android.os.Parcel;
import javax.validation.constraints.*;
import javax.validation.Valid;
{{/useBeanValidation}}
{{#performBeanValidation}}
import org.hibernate.validator.constraints.*;
{{/performBeanValidation}}
{{#models}}
{{#model}}

View File

@ -313,6 +313,14 @@
<scope>provided</scope>
</dependency>
{{/useBeanValidation}}
{{#performBeanValidation}}
<!-- Bean Validation Impl. used to perform BeanValidation -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
{{/performBeanValidation}}
{{#parcelableModel}}
<!-- Needed for Parcelable support-->
<dependency>

View File

@ -23,6 +23,7 @@ import javax.inject.Inject;
{{#useBeanValidation}}
import javax.validation.constraints.*;
import javax.validation.Valid;
{{/useBeanValidation}}
{{#operations}}{{#operation}}{{#isMultipart}}import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
{{/isMultipart}}{{/operation}}{{/operations}}

View File

@ -1 +1 @@
{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isBodyParam}}
{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{#useBeanValidation}}{{#required}} @NotNull{{/required}} @Valid{{/useBeanValidation}} {{{dataType}}} {{paramName}}{{/isBodyParam}}

View File

@ -19,6 +19,7 @@ import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.*;
{{#useBeanValidation}}
import javax.validation.constraints.*;
import javax.validation.Valid;
{{/useBeanValidation}}
{{#operations}}{{#operation}}{{#isMultipart}}import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
{{/isMultipart}}{{/operation}}{{/operations}}

View File

@ -1 +1 @@
{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isBodyParam}}
{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{#useBeanValidation}}{{#required}} @NotNull{{/required}} @Valid{{/useBeanValidation}} {{{dataType}}} {{paramName}}{{/isBodyParam}}

View File

@ -11,6 +11,8 @@ minLength not set, maxLength set
}}{{#minItems}}{{^maxItems}}@Size(min={{minItems}}) {{/maxItems}}{{/minItems}}{{!
@Size: minItems not set && maxItems set
}}{{^minItems}}{{#maxItems}}@Size(max={{maxItems}}) {{/maxItems}}{{/minItems}}{{!
@Email: performBeanValidation set && isEmail set
}}{{#performBeanValidation}}{{#isEmail}}@Email{{/isEmail}}{{/performBeanValidation}}{{!
check for integer or long / all others=decimal type with @Decimal*
isInteger set
}}{{#isInteger}}{{#minimum}}@Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}) {{/maximum}}{{/isInteger}}{{!

View File

@ -164,5 +164,12 @@
</dependency>
<!-- END Virtual Service API support -->
{{/virtualService}}
{{#hateoas}}
<!-- Spring HATEOAS -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
{{/hateoas}}
</dependencies>
</project>

View File

@ -86,5 +86,12 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
{{#hateoas}}
<!-- Spring HATEOAS -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
{{/hateoas}}
</dependencies>
</project>

View File

@ -202,7 +202,6 @@
<version>${jackson-threetenbp-version}</version>
</dependency>
{{/threetenbp}}
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
@ -223,6 +222,14 @@
<scope>provided</scope>
</dependency>
{{/useBeanValidation}}
{{#hateoas}}
<!-- Spring HATEOAS -->
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
<version>0.25.0.RELEASE</version>
</dependency>
{{/hateoas}}
</dependencies>
<properties>
<java.version>{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}</java.version>
@ -238,6 +245,6 @@
{{#useBeanValidation}}
<beanvalidation-version>1.1.0.Final</beanvalidation-version>
{{/useBeanValidation}}
<spring-version>4.3.9.RELEASE</spring-version>
<spring-version>4.3.20.RELEASE</spring-version>
</properties>
</project>

View File

@ -10,6 +10,9 @@ import java.io.Serializable;
import javax.validation.Valid;
import javax.validation.constraints.*;
{{/useBeanValidation}}
{{#performBeanValidation}}
import org.hibernate.validator.constraints.*;
{{/performBeanValidation}}
{{#jackson}}
{{#withXml}}
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
@ -19,6 +22,11 @@ import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
{{#withXml}}
import javax.xml.bind.annotation.*;
{{/withXml}}
{{^parent}}
{{#hateoas}}
import org.springframework.hateoas.ResourceSupport;
{{/hateoas}}
{{/parent}}
{{#models}}
{{#model}}

View File

@ -3,7 +3,7 @@
*/{{#description}}
@ApiModel(description = "{{{description}}}"){{/description}}
{{>generatedAnnotation}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{>xmlAnnotation}}
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} {
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}}{{^parent}}{{#hateoas}}extends ResourceSupport {{/hateoas}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} {
{{#serializableModel}}
private static final long serialVersionUID = 1L;

View File

@ -1,4 +1,3 @@
{{#models}}{{#model}}
{{#emitJSDoc}}
/**
@ -21,11 +20,28 @@
var _this = this;
{{#parent}}{{^parentModel}}{{#vendorExtensions.x-isArray}} _this = new Array();
Object.setPrototypeOf(_this, exports);
{{/vendorExtensions.x-isArray}}{{/parentModel}}{{/parent}}{{#useInheritance}}{{#parentModel}} {{classname}}.call(_this{{#vendorExtensions.x-all-required}}, {{name}}{{/vendorExtensions.x-all-required}});{{/parentModel}}
{{#interfaceModels}} {{classname}}.call(_this{{#vendorExtensions.x-all-required}}, {{name}}{{/vendorExtensions.x-all-required}});
{{/interfaceModels}}{{/useInheritance}}{{#vars}}{{#required}} _this['{{baseName}}'] = {{name}};{{/required}}
{{/vars}}{{#parent}}{{^parentModel}} return _this;
{{/parentModel}}{{/parent}} };
{{/vendorExtensions.x-isArray}}{{/parentModel}}{{/parent}}
{{#useInheritance}}
{{#parentModel}}
{{classname}}.call(_this{{#vendorExtensions.x-all-required}}, {{name}}{{/vendorExtensions.x-all-required}});
{{/parentModel}}
{{^parentModel}}
{{#interfaceModels}}
{{classname}}.call(_this{{#vendorExtensions.x-all-required}}, {{name}}{{/vendorExtensions.x-all-required}});
{{/interfaceModels}}
{{/parentModel}}
{{/useInheritance}}
{{#vars}}
{{#required}}
_this['{{baseName}}'] = {{name}};
{{/required}}
{{/vars}}
{{#parent}}
{{^parentModel}}
return _this;
{{/parentModel}}
{{/parent}}
};
{{#emitJSDoc}}
/**
@ -45,13 +61,27 @@
exports.constructFromObject = function(data, obj) {
if (data){{! TODO: support polymorphism: discriminator property on data determines class to instantiate.}} {
obj = obj || new exports();
{{#parent}}{{^parentModel}} ApiClient.constructFromObject(data, obj, '{{vendorExtensions.x-itemType}}');
{{/parentModel}}{{/parent}}{{#useInheritance}}{{#parentModel}} {{classname}}.constructFromObject(data, obj);{{/parentModel}}
{{#interfaces}} {{.}}.constructFromObject(data, obj);
{{/interfaces}}{{/useInheritance}}{{#vars}} if (data.hasOwnProperty('{{baseName}}')) {
{{#parent}}
{{^parentModel}}
ApiClient.constructFromObject(data, obj, '{{vendorExtensions.x-itemType}}');
{{/parentModel}}
{{/parent}}
{{#useInheritance}}
{{#parentModel}}
{{classname}}.constructFromObject(data, obj);
{{/parentModel}}
{{^parentModel}}
{{#interfaces}}
{{.}}.constructFromObject(data, obj);
{{/interfaces}}
{{/parentModel}}
{{/useInheritance}}
{{#vars}}
if (data.hasOwnProperty('{{baseName}}')) {
obj['{{baseName}}']{{{defaultValueWithParam}}}
}
{{/vars}} }
{{/vars}}
}
return obj;
}
{{/vendorExtensions.x-isPrimitive}}

View File

@ -35,7 +35,7 @@ Once compiled run the server:
```bash
cd build
./server
./api-server
```
## Libraries required

View File

@ -9,12 +9,11 @@
#define {{classname}}_H_
{{{defaultInclude}}}
#include <pistache/endpoint.h>
#include <pistache/http.h>
#include <pistache/router.h>
#include <pistache/http_headers.h>
#include <pistache/optional.h>
{{^hasModelImport}}#include "json.hpp"{{/hasModelImport}}
{{#imports}}{{{import}}}
{{/imports}}
@ -28,11 +27,9 @@ using namespace {{modelNamespace}};{{/hasModelImport}}
class {{declspec}} {{classname}} {
public:
{{classname}}(Pistache::Address addr);
{{classname}}(std::shared_ptr<Pistache::Rest::Router>);
virtual ~{{classname}}() {}
void init(size_t thr);
void start();
void shutdown();
void init();
const std::string base = "{{basePathWithoutHost}}";
@ -44,9 +41,7 @@ private:
{{/operation}}
void {{classnameSnakeLowerCase}}_default_handler(const Pistache::Rest::Request &request, Pistache::Http::ResponseWriter response);
Pistache::Http::Endpoint httpEndpoint;
Pistache::Rest::Router router;
std::shared_ptr<Pistache::Rest::Router> router;
{{#operation}}
/// <summary>

View File

@ -31,7 +31,7 @@ using namespace {{modelNamespace}};{{/hasModelImport}}
class {{classname}}Impl : public {{apiNamespace}}::{{classname}} {
public:
{{classname}}Impl(Pistache::Address addr);
{{classname}}Impl(std::shared_ptr<Pistache::Rest::Router>);
~{{classname}}Impl() {}
{{#operation}}

View File

@ -10,8 +10,8 @@ namespace {{this}} {
{{#hasModelImport}}
using namespace {{modelNamespace}};{{/hasModelImport}}
{{classname}}Impl::{{classname}}Impl(Pistache::Address addr)
: {{classname}}(addr)
{{classname}}Impl::{{classname}}Impl(std::shared_ptr<Pistache::Rest::Router> rtr)
: {{classname}}(rtr)
{ }
{{#operation}}

View File

@ -12,36 +12,23 @@ using namespace {{helpersNamespace}};
{{#hasModelImport}}
using namespace {{modelNamespace}};{{/hasModelImport}}
{{classname}}::{{classname}}(Pistache::Address addr)
: httpEndpoint(addr)
{ };
{{classname}}::{{classname}}(std::shared_ptr<Pistache::Rest::Router> rtr) {
router = rtr;
};
void {{classname}}::init(size_t thr = 2) {
auto opts = Pistache::Http::Endpoint::options()
.threads(thr)
.flags(Pistache::Tcp::Options::InstallSignalHandler);
httpEndpoint.init(opts);
void {{classname}}::init() {
setupRoutes();
}
void {{classname}}::start() {
httpEndpoint.setHandler(router.handler());
httpEndpoint.serve();
}
void {{classname}}::shutdown() {
httpEndpoint.shutdown();
}
void {{classname}}::setupRoutes() {
using namespace Pistache::Rest;
{{#operation}}
Routes::{{httpMethod}}(router, base + "{{{vendorExtensions.x-codegen-pistache-path}}}", Routes::bind(&{{classname}}::{{operationIdSnakeCase}}_handler, this));
Routes::{{httpMethod}}(*router, base + "{{{vendorExtensions.x-codegen-pistache-path}}}", Routes::bind(&{{classname}}::{{operationIdSnakeCase}}_handler, this));
{{/operation}}
// Default handler, called when a route is not found
router.addCustomHandler(Routes::bind(&{{classname}}::{{classnameSnakeLowerCase}}_default_handler, this));
router->addCustomHandler(Routes::bind(&{{classname}}::{{classnameSnakeLowerCase}}_default_handler, this));
}
{{#operation}}

View File

@ -1,6 +1,6 @@
cmake_minimum_required (VERSION 3.2)
project(server)
project(api-server)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -pg -g3" )
@ -24,48 +24,17 @@ include_directories(${EXTERNAL_INSTALL_LOCATION}/include/nlohmann)
link_directories(${EXTERNAL_INSTALL_LOCATION}/lib)
{{/addExternalLibs}}
link_directories(/usr/local/lib/)
aux_source_directory(model MODEL_SOURCES)
{{=<% %>=}}
<%#apiInfo.apis%>
<%#operations%>
file(GLOB <%classnameSnakeUpperCase%>_SOURCES
"api/<%classname%>.h"
"api/<%classname%>.cpp"
"impl/<%classname%>Impl.h"
"impl/<%classname%>Impl.cpp"
)
<%/operations%>
<%/apiInfo.apis%>
include_directories(model)
include_directories(api)
include_directories(impl)
<%#apiInfo.apis%>
<%#operations%>
set(<%classnameSnakeUpperCase%>_SERVER_SOURCES
<%classname%>MainServer.cpp
${MODEL_SOURCES}
${<%classnameSnakeUpperCase%>_SOURCES})
<%/operations%>
<%/apiInfo.apis%>
file(GLOB SRCS
${CMAKE_CURRENT_SOURCE_DIR}/api/*.cpp
${CMAKE_CURRENT_SOURCE_DIR}/impl/*.cpp
${CMAKE_CURRENT_SOURCE_DIR}/model/*.cpp
${CMAKE_CURRENT_SOURCE_DIR}/*.cpp
)
<%#apiInfo.apis%>
<%#operations%>
add_executable(<%classnameSnakeLowerCase%>_server
${<%classnameSnakeUpperCase%>_SERVER_SOURCES})
<%#addExternalLibs%>
add_dependencies(<%classnameSnakeLowerCase%>_server PISTACHE NLOHMANN)
<%/addExternalLibs%>
<%/operations%>
<%/apiInfo.apis%>
<%#apiInfo.apis%>
<%#operations%>
target_link_libraries(<%classnameSnakeLowerCase%>_server pistache pthread)
<%/operations%>
<%/apiInfo.apis%>
<%={{ }}=%>
add_executable(${PROJECT_NAME} ${SRCS} )
add_dependencies(${PROJECT_NAME} PISTACHE NLOHMANN)
target_link_libraries(${PROJECT_NAME} pistache pthread)

View File

@ -1,21 +1,74 @@
{{>licenseInfo}}
{{#operations}}
#include "pistache/endpoint.h"
#include "pistache/http.h"
#include "pistache/router.h"
#include "{{classname}}Impl.h"
#ifdef __linux__
#include <vector>
#include <signal.h>
#include <unistd.h>
#endif
{{#apiInfo}}{{#apis}}{{#operations}}
#include "{{classname}}Impl.h"{{/operations}}{{/apis}}{{/apiInfo}}
#define PISTACHE_SERVER_THREADS 2
static Pistache::Http::Endpoint *httpEndpoint;
#ifdef __linux__
static void sigHandler(int sig){
switch(sig){
case SIGINT:
case SIGQUIT:
case SIGTERM:
case SIGHUP:
default:
httpEndpoint->shutdown();
break;
}
exit(0);
}
static void setUpUnixSignals(std::vector<int> quitSignals) {
sigset_t blocking_mask;
sigemptyset(&blocking_mask);
for (auto sig : quitSignals)
sigaddset(&blocking_mask, sig);
struct sigaction sa;
sa.sa_handler = sigHandler;
sa.sa_mask = blocking_mask;
sa.sa_flags = 0;
for (auto sig : quitSignals)
sigaction(sig, &sa, nullptr);
}
#endif
using namespace {{apiNamespace}};
int main() {
#ifdef __linux__
std::vector<int> sigs{SIGQUIT, SIGINT, SIGTERM, SIGHUP};
setUpUnixSignals(sigs);
#endif
Pistache::Address addr(Pistache::Ipv4::any(), Pistache::Port(8080));
{{classname}}Impl server(addr);
server.init(2);
server.start();
httpEndpoint = new Pistache::Http::Endpoint((addr));
auto router = std::make_shared<Pistache::Rest::Router>();
auto opts = Pistache::Http::Endpoint::options()
.threads(PISTACHE_SERVER_THREADS);
httpEndpoint->init(opts);
{{#apiInfo}}{{#apis}}{{#operations}}
{{classname}}Impl {{classname}}server(router);
{{classname}}server.init();{{/operations}}{{/apis}}{{/apiInfo}}
httpEndpoint->setHandler(router->handler());
httpEndpoint->serve();
httpEndpoint->shutdown();
server.shutdown();
}
{{/operations}}

View File

@ -13,6 +13,7 @@
{{#imports}}{{{import}}}
{{/imports}}
{{^hasModelImport}}#include "../ModelBase.h"{{/hasModelImport}}
#include <boost/optional.hpp>

View File

@ -93,6 +93,17 @@ namespace {{packageName}}.{{apiPackage}}
ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// Initializes a new instance of the <see cref="{{classname}}"/> class
/// </summary>
/// <returns></returns>
public {{classname}}()
{
this.Configuration = {{packageName}}.Client.Configuration.Default;
ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// Initializes a new instance of the <see cref="{{classname}}"/> class
/// using Configuration object

View File

@ -1 +1 @@
{{#required}}required{{/required}}{{^required}}optional{{/required}} "{{baseName}}" {{^required}}(Decode.nullable {{/required}}{{#isContainer}}(Decode.list {{/isContainer}}{{vendorExtensions.elmDecoder}}{{#isContainer}}){{/isContainer}}{{^required}}){{/required}}{{^required}} {{{defaultValue}}}{{/required}}
{{#required}}required{{/required}}{{^required}}optional{{/required}} "{{baseName}}" {{^required}}(Decode.nullable {{/required}}{{#isMapContainer}}(Decode.dict {{/isMapContainer}}{{#isListContainer}}(Decode.list {{/isListContainer}}{{vendorExtensions.elmDecoder}}{{#isContainer}}){{/isContainer}}{{^required}}){{/required}}{{^required}} {{{defaultValue}}}{{/required}}

View File

@ -1 +1 @@
( "{{baseName}}", {{#discriminatorValue}}Encode.string "{{discriminatorValue}}"{{/discriminatorValue}}{{^discriminatorValue}}{{^required}}Maybe.withDefault Encode.null (Maybe.map {{/required}}{{#isContainer}}(Encode.list {{#isElm018}}<< List.map {{/isElm018}}{{/isContainer}}{{vendorExtensions.elmEncoder}}{{#isContainer}}){{/isContainer}} model.{{name}}{{^required}}){{/required}}{{/discriminatorValue}} )
( "{{baseName}}", {{#discriminatorValue}}Encode.string "{{discriminatorValue}}"{{/discriminatorValue}}{{^discriminatorValue}}{{^required}}Maybe.withDefault Encode.null (Maybe.map {{/required}}{{#isMapContainer}}(Encode.dict identity {{/isMapContainer}}{{#isListContainer}}(Encode.list {{#isElm018}}<< List.map {{/isElm018}}{{/isListContainer}}{{vendorExtensions.elmEncoder}}{{#isContainer}}){{/isContainer}} model.{{name}}{{^required}}){{/required}}{{/discriminatorValue}} )

View File

@ -2,7 +2,8 @@
module Data.{{classname}} exposing ({{#models}}{{#model}}{{classname}}{{#hasChildren}}(..){{/hasChildren}}{{#isEnum}}(..){{/isEnum}}{{^isEnum}}{{#vars}}{{#isEnum}}, {{vendorExtensions.elmUnionType}}(..){{/isEnum}}{{/vars}}{{/isEnum}}, decoder, encoder{{/model}}{{/models}})
{{>imports}}import Json.Decode as Decode exposing (Decoder)
{{>imports}}import Dict exposing (Dict)
import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Pipeline exposing ({{#isElm018}}decode, {{/isElm018}}optional, required)
import Json.Encode as Encode
{{#models}}

View File

@ -1,5 +1,5 @@
type alias {{classname}} =
{ {{#allVars}}{{^-first}} , {{/-first}}{{name}} : {{^required}}Maybe {{#isContainer}}({{/isContainer}}{{/required}}{{#isContainer}}List {{/isContainer}}{{#isEnum}}{{nameInCamelCase}}{{/isEnum}}{{^isEnum}}{{dataType}}{{/isEnum}}{{^required}}{{#isContainer}}){{/isContainer}}{{/required}}
{ {{#allVars}}{{^-first}} , {{/-first}}{{name}} : {{^required}}Maybe {{#isContainer}}({{/isContainer}}{{/required}}{{#isMapContainer}}Dict String {{/isMapContainer}}{{#isListContainer}}List {{/isListContainer}}{{#isEnum}}{{nameInCamelCase}}{{/isEnum}}{{^isEnum}}{{dataType}}{{/isEnum}}{{^required}}{{#isContainer}}){{/isContainer}}{{/required}}
{{/allVars}} }
{{#vars}}
{{#isEnum}}

View File

@ -69,6 +69,6 @@ prepare_validator() ->
get_openapi_path() ->
{ok, AppName} = application:get_application(?MODULE),
filename:join({{packageName}}_utils:priv_dir(AppName), "openapi.json").
filename:join({{packageName}}_utils:priv_dir(AppName), "{{{openAPISpecName}}}.json").

View File

@ -272,16 +272,6 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx context.Context{{#hasParams}
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHttpResponse, err
}
{{#returnType}}
if localVarHttpResponse.StatusCode < 300 {
// If we succeed, return the data, otherwise pass on to decode error.
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type"))
if err == nil {
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHttpResponse, err
}
}
{{/returnType}}
if localVarHttpResponse.StatusCode >= 300 {
newErr := GenericOpenAPIError{
body: localVarBody,
@ -304,6 +294,17 @@ func (a *{{{classname}}}Service) {{{nickname}}}(ctx context.Context{{#hasParams}
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHttpResponse, newErr
}
{{#returnType}}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type"))
if err != nil {
newErr := GenericOpenAPIError{
body: localVarBody,
error: err.Error(),
}
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHttpResponse, newErr
}
{{/returnType}}
return {{#returnType}}localVarReturnValue, {{/returnType}}localVarHttpResponse, nil
}
{{/operation}}

View File

@ -49,14 +49,12 @@ function {{classname}}:{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}},
req.headers:upsert(":method", "{{httpMethod}}")
{{#hasConsumes}}
-- TODO: create a function to select proper accept
-- ref: https://openapi-generator.tech/pull/6252#issuecomment-321199879
--local var_content_type = { {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }
req.headers:upsert("accept", {{#consumes}}{{#-first}}"{{{mediaType}}}"{{/-first}}{{/consumes}})
{{/hasConsumes}}
{{#hasProduces}}
-- TODO: create a function to select proper content-type
-- ref: https://openapi-generator.tech/pull/6252#issuecomment-321199879
--local var_accept = { {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }
req.headers:upsert("content-type", {{#produces}}{{#-first}}"{{{mediaType}}}"{{/-first}}{{/produces}})

View File

@ -219,5 +219,70 @@ module {{moduleName}}
{{/authMethods}}
}
end
# Returns an array of Server setting
def server_settings
[
{{#servers}}
{
url: "{{{url}}}",
description: "{{{description}}}{{^description}}No descriptoin provided{{/description}}",
{{#variables}}
{{#-first}}
variables: {
{{/-first}}
{{{name}}}: {
description: "{{{description}}}{{^description}}No descriptoin provided{{/description}}",
default_value: "{{{defaultValue}}}",
{{#enumValues}}
{{#-first}}
enum_values: [
{{/-first}}
"{{{.}}}"{{^-last}},{{/-last}}
{{#-last}}
]
{{/-last}}
{{/enumValues}}
}{{^-last}},{{/-last}}
{{#-last}}
}
{{/-last}}
{{/variables}}
}{{^-last}},{{/-last}}
{{/servers}}
]
end
# Returns URL based on server settings
#
# @param index array index of the server settings
# @param variables hash of variable and the corresponding value
def server_url(index, variables = {})
servers = server_settings
# check array index out of bound
if (index < 0 || index > servers.size)
fail ArgumentError "Invalid index #{index} when selecting the server. Must be less than #{servers.size}"
end
server = servers[index]
url = server[:url]
# go through variable and assign a value
server[:variables].each do |name, variable|
if variables.key?(name)
if (server[:variables][name][:enum_values].include? variables[name])
url.gsub! "{" + name.to_s + "}", variables[name]
else
fail ArgumentError, "The variable `#{name}` in the server URL has invalid value #{variables[name]}. Must be #{server[:variables][name][:enum_values]}."
end
else
# use default value
url.gsub! "{" + name.to_s + "}", server[:variables][name][:default_value]
end
end
url
end
end
end

View File

@ -4,14 +4,21 @@ version = "{{{packageVersion}}}"
authors = ["OpenAPI Generator team and contributors"]
[dependencies]
serde = "1.0"
serde_derive = "1.0"
serde_yaml = "0.7"
serde_json = "1.0"
base64 = "~0.7.0"
futures = "0.1.16"
hyper = "0.11.6"
serde = "^1.0"
serde_derive = "^1.0"
serde_json = "^1.0"
url = "1.5"
{{#hyper}}
hyper = "~0.11"
serde_yaml = "0.7"
base64 = "~0.7.0"
futures = "0.1.23"
{{/hyper}}
{{#reqwest}}
reqwest = "~0.9"
{{/reqwest}}
[dev-dependencies]
{{#hyper}}
tokio-core = "*"
{{/hyper}}

View File

@ -1,4 +1,4 @@
# Rust API client for {{packageName}}
# Rust API client for {{{packageName}}}
{{#appDescription}}
{{{appDescription}}}
@ -7,12 +7,12 @@
## Overview
This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://openapis.org) from a remote server, you can easily generate an API client.
- API version: {{appVersion}}
- Package version: {{packageVersion}}
- API version: {{{appVersion}}}
- Package version: {{{packageVersion}}}
{{^hideGenerationTimestamp}}
- Build date: {{generatedDate}}
- Build date: {{{generatedDate}}}
{{/hideGenerationTimestamp}}
- Build package: {{generatorClass}}
- Build package: {{{generatorClass}}}
{{#infoUrl}}
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
{{/infoUrl}}
@ -20,21 +20,21 @@ For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
## Installation
Put the package under your project folder and add the following in import:
```
"./{{packageName}}"
"./{{{packageName}}}"
```
## Documentation for API Endpoints
All URIs are relative to *{{basePath}}*
All URIs are relative to *{{{basePath}}}*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{{classname}}}* | [**{{{operationId}}}**]({{{apiDocPath}}}{{classname}}.md#{{{operationIdLowerCase}}}) | **{{{httpMethod}}}** {{{path}}} | {{#summary}}{{{summary}}}{{/summary}}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
## Documentation For Models
{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md)
{{#models}}{{#model}} - [{{{classname}}}]({{{modelDocPath}}}{{{classname}}}.md)
{{/model}}{{/models}}
## Documentation For Authorization
@ -92,5 +92,5 @@ Or via OAuth2 module to automatically refresh tokens and perform user authentica
## Author
{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}}
{{#apiInfo}}{{#apis}}{{^hasMore}}{{{infoEmail}}}
{{/hasMore}}{{/apis}}{{/apiInfo}}

View File

@ -1,17 +1,17 @@
# {{invokerPackage}}\{{classname}}{{#description}}
{{description}}{{/description}}
# {{{invokerPackage}}}\{{{classname}}}{{#description}}
{{{description}}}{{/description}}
All URIs are relative to *{{basePath}}*
All URIs are relative to *{{{basePath}}}*
Method | HTTP request | Description
------------- | ------------- | -------------
{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{#operations}}{{#operation}}[**{{{operationId}}}**]({{{classname}}}.md#{{{operationId}}}) | **{{{httpMethod}}}** {{{path}}} | {{#summary}}{{{summary}}}{{/summary}}
{{/operation}}{{/operations}}
{{#operations}}
{{#operation}}
# **{{{operationId}}}**
> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}({{#authMethods}}ctx, {{/authMethods}}{{#allParams}}{{#required}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}optional{{/hasOptionalParams}})
> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}({{#authMethods}}ctx, {{/authMethods}}{{#allParams}}{{#required}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}optional{{/hasOptionalParams}})
{{{summary}}}{{#notes}}
{{{notes}}}{{/notes}}
@ -21,7 +21,7 @@ Method | HTTP request | Description
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------{{#authMethods}}
**ctx** | **context.Context** | context containing the authentication | nil if no authentication{{/authMethods}}{{/-last}}{{/allParams}}{{#allParams}}{{#required}}
**{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{baseType}}.md){{/isPrimitiveType}}| {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/required}}{{/allParams}}{{#hasOptionalParams}}
**{{{paramName}}}** | {{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{{baseType}}}.md){{/isPrimitiveType}}| {{{description}}} | {{#defaultValue}}[default to {{{defaultValue}}}]{{/defaultValue}}{{/required}}{{/allParams}}{{#hasOptionalParams}}
**optional** | **map[string]interface{}** | optional parameters | nil if no parameters
### Optional Parameters
@ -29,11 +29,11 @@ Optional parameters are passed through a map[string]interface{}.
{{#allParams}}{{#-last}}
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}{{#allParams}}
**{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{baseType}}.md){{/isPrimitiveType}}| {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/allParams}}{{/hasOptionalParams}}
**{{{paramName}}}** | {{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{{baseType}}}.md){{/isPrimitiveType}}| {{{description}}} | {{#defaultValue}}[default to {{{defaultValue}}}]{{/defaultValue}}{{/allParams}}{{/hasOptionalParams}}
### Return type
{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}} (empty response body){{/returnType}}
{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{{returnBaseType}}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}} (empty response body){{/returnType}}
### Authorization

View File

@ -21,20 +21,20 @@ impl<C: hyper::client::Connect> {{{classname}}}Client<C> {
}
}
pub trait {{classname}} {
pub trait {{{classname}}} {
{{#operations}}
{{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box<Future<Item = {{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error = Error<serde_json::Value>>>;
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box<Future<Item = {{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error = Error<serde_json::Value>>>;
{{/operation}}
{{/operations}}
}
impl<C: hyper::client::Connect>{{classname}} for {{classname}}Client<C> {
impl<C: hyper::client::Connect>{{{classname}}} for {{{classname}}}Client<C> {
{{#operations}}
{{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box<Future<Item = {{^returnType}}(){{/returnType}}{{#returnType}}{{{.}}}{{/returnType}}, Error = Error<serde_json::Value>>> {
__internal_request::Request::new(hyper::Method::{{httpMethod}}, "{{{path}}}".to_string())
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box<Future<Item = {{^returnType}}(){{/returnType}}{{#returnType}}{{{.}}}{{/returnType}}, Error = Error<serde_json::Value>>> {
__internal_request::Request::new(hyper::Method::{{{httpMethod}}}, "{{{path}}}".to_string())
{{#hasAuthMethods}}
{{#authMethods}}
{{#isApiKey}}
@ -53,29 +53,29 @@ impl<C: hyper::client::Connect>{{classname}} for {{classname}}Client<C> {
{{/authMethods}}
{{/hasAuthMethods}}
{{#queryParams}}
.with_query_param("{{baseName}}".to_string(), {{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string())
.with_query_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string())
{{/queryParams}}
{{#pathParams}}
.with_path_param("{{baseName}}".to_string(), {{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string())
.with_path_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string())
{{/pathParams}}
{{#hasHeaderParams}}
{{#headerParams}}
.with_header_param("{{baseName}}".to_string(), {{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string())
.with_header_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string())
{{/headerParams}}
{{/hasHeaderParams}}
{{#hasFormParams}}
{{#formParams}}
{{#isFile}}
.with_form_param("{{baseName}}".to_string(), unimplemented!())
.with_form_param("{{{baseName}}}".to_string(), unimplemented!())
{{/isFile}}
{{^isFile}}
.with_form_param("{{baseName}}".to_string(), {{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string())
.with_form_param("{{{baseName}}}".to_string(), {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string())
{{/isFile}}
{{/formParams}}
{{/hasFormParams}}
{{#hasBodyParam}}
{{#bodyParams}}
.with_body_param({{paramName}})
.with_body_param({{{paramName}}})
{{/bodyParams}}
{{/hasBodyParam}}
{{^returnType}}

View File

@ -55,11 +55,11 @@ mod request;
{{#apiInfo}}
{{#apis}}
mod {{classFilename}};
mod {{{classFilename}}};
{{#operations}}
{{#operation}}
{{#-last}}
pub use self::{{classFilename}}::{ {{classname}}, {{classname}}Client };
pub use self::{{{classFilename}}}::{ {{{classname}}}, {{{classname}}}Client };
{{/-last}}
{{/operation}}
{{/operations}}

View File

@ -10,7 +10,7 @@ pub struct APIClient<C: hyper::client::Connect> {
{{#operations}}
{{#operation}}
{{#-last}}
{{classFilename}}: Box<::apis::{{classname}}>,
{{{classFilename}}}: Box<::apis::{{{classname}}}>,
{{/-last}}
{{/operation}}
{{/operations}}
@ -29,7 +29,7 @@ impl<C: hyper::client::Connect> APIClient<C> {
{{#operations}}
{{#operation}}
{{#-last}}
{{classFilename}}: Box::new(::apis::{{classname}}Client::new(rc.clone())),
{{{classFilename}}}: Box::new(::apis::{{{classname}}}Client::new(rc.clone())),
{{/-last}}
{{/operation}}
{{/operations}}
@ -43,8 +43,8 @@ impl<C: hyper::client::Connect> APIClient<C> {
{{#operations}}
{{#operation}}
{{#-last}}
pub fn {{classFilename}}(&self) -> &::apis::{{classname}}{
self.{{classFilename}}.as_ref()
pub fn {{{classFilename}}}(&self) -> &::apis::{{{classname}}}{
self.{{{classFilename}}}.as_ref()
}
{{/-last}}

View File

@ -23,7 +23,7 @@ impl<C: hyper::client::Connect> Configuration<C> {
pub fn new(client: hyper::client::Client<C>) -> Configuration<C> {
Configuration {
base_path: "{{{basePath}}}".to_owned(),
user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("OpenAPI-Generator/{{version}}/rust".to_owned()){{/httpUserAgent}},
user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("OpenAPI-Generator/{{{version}}}/rust".to_owned()){{/httpUserAgent}},
client: client,
basic_auth: None,
oauth_access_token: None,

View File

@ -0,0 +1,16 @@
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate url;
{{#hyper}}
extern crate hyper;
extern crate futures;
{{/hyper}}
{{#reqwest}}
extern crate reqwest;
{{/reqwest}}
pub mod apis;
pub mod models;

View File

@ -9,45 +9,45 @@
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub struct {{classname}} {
pub struct {{{classname}}} {
{{#vars}}
{{#description}}
/// {{{description}}}
{{/description}}
#[serde(rename = "{{baseName}}")]
{{name}}: {{^required}}Option<{{/required}}{{{dataType}}}{{^required}}>{{/required}}{{#hasMore}},{{/hasMore}}
#[serde(rename = "{{{baseName}}}")]
{{{name}}}: {{^required}}Option<{{/required}}{{{dataType}}}{{^required}}>{{/required}}{{#hasMore}},{{/hasMore}}
{{/vars}}
}
impl {{classname}} {
impl {{{classname}}} {
{{#description}}
/// {{{description}}}
{{/description}}
pub fn new({{#requiredVars}}{{name}}: {{{dataType}}}{{^-last}}, {{/-last}}{{/requiredVars}}) -> {{classname}} {
{{classname}} {
pub fn new({{#requiredVars}}{{{name}}}: {{{dataType}}}{{^-last}}, {{/-last}}{{/requiredVars}}) -> {{{classname}}} {
{{{classname}}} {
{{#vars}}
{{name}}: {{#required}}{{name}}{{/required}}{{^required}}{{#isListContainer}}None{{/isListContainer}}{{#isMapContainer}}None{{/isMapContainer}}{{^isContainer}}None{{/isContainer}}{{/required}}{{#hasMore}},{{/hasMore}}
{{{name}}}: {{#required}}{{{name}}}{{/required}}{{^required}}{{#isListContainer}}None{{/isListContainer}}{{#isMapContainer}}None{{/isMapContainer}}{{^isContainer}}None{{/isContainer}}{{/required}}{{#hasMore}},{{/hasMore}}
{{/vars}}
}
}
{{#vars}}
pub fn set_{{name}}(&mut self, {{name}}: {{{dataType}}}) {
self.{{name}} = {{^required}}Some({{name}}){{/required}}{{#required}}{{name}}{{/required}};
pub fn set_{{{name}}}(&mut self, {{{name}}}: {{{dataType}}}) {
self.{{{name}}} = {{^required}}Some({{{name}}}){{/required}}{{#required}}{{{name}}}{{/required}};
}
pub fn with_{{name}}(mut self, {{name}}: {{{dataType}}}) -> {{classname}} {
self.{{name}} = {{^required}}Some({{name}}){{/required}}{{#required}}{{name}}{{/required}};
pub fn with_{{{name}}}(mut self, {{{name}}}: {{{dataType}}}) -> {{{classname}}} {
self.{{{name}}} = {{^required}}Some({{{name}}}){{/required}}{{#required}}{{{name}}}{{/required}};
self
}
pub fn {{name}}(&self) -> {{^required}}Option<{{/required}}&{{{dataType}}}{{^required}}>{{/required}} {
{{#required}}&{{/required}}self.{{name}}{{^required}}.as_ref(){{/required}}
pub fn {{{name}}}(&self) -> {{^required}}Option<{{/required}}&{{{dataType}}}{{^required}}>{{/required}} {
{{#required}}&{{/required}}self.{{{name}}}{{^required}}.as_ref(){{/required}}
}
{{^required}}
pub fn reset_{{name}}(&mut self) {
self.{{name}} = None;
pub fn reset_{{{name}}}(&mut self) {
self.{{{name}}} = None;
}
{{/required}}
@ -60,7 +60,7 @@ impl {{classname}} {
//const (
// {{#allowableValues}}
// {{#enumVars}}
// {{name}} {{{classname}}} = "{{{value}}}"
// {{{name}}} {{{classname}}} = "{{{value}}}"
// {{/enumVars}}
// {{/allowableValues}}
//)

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