Merge remote-tracking branch 'origin/3.3.x' into 4.0.x

Conflicts:
	modules/openapi-generator-online/Dockerfile
	samples/*
This commit is contained in:
Jeremie Bresson 2018-08-26 09:13:39 +02:00
commit a08f8d13e0
62 changed files with 1588 additions and 625 deletions

View File

@ -26,7 +26,7 @@ RUN mkdir -p ${TARGET_DIR}
WORKDIR ${TARGET_DIR}
COPY --from=builder ${GEN_DIR}/modules/openapi-generator-online/target/openapi-generator-*.jar ${TARGET_DIR}/openapi-generator-online.jar
COPY --from=builder ${GEN_DIR}/modules/openapi-generator-online/target/openapi-generator.jar ${TARGET_DIR}/openapi-generator-online.jar
ENV GENERATOR_HOST=http://localhost

View File

@ -125,7 +125,7 @@ after_success:
./gradlew -Psigning.keyId="$SIGNING_KEY" -Psigning.password="$SIGNING_PASSPHRASE" -Psigning.secretKeyRingFile="${TRAVIS_BUILD_DIR}/sec.gpg" -PossrhUsername="${SONATYPE_USERNAME}" -PossrhPassword="${SONATYPE_PASSWORD}" uploadArchives --no-daemon;
echo "Finished ./gradlew uploadArchives";
popd;
elif ([ "$TRAVIS_BRANCH" == "4.0.x" ]) ; then
elif ([[ "$TRAVIS_BRANCH" =~ ^[0-9]+\.[0-9]+\.x$ ]]) ; then
mvn clean deploy --settings CI/settings.xml;
echo "Finished mvn clean deploy for $TRAVIS_BRANCH";
pushd .;

View File

@ -45,7 +45,6 @@ declare -a files=("CI/pom.xml.bash"
"modules/openapi-generator-maven-plugin/pom.xml"
"modules/openapi-generator-online/pom.xml"
"modules/openapi-generator/pom.xml"
"modules/openapi-generator-online/Dockerfile"
"pom.xml")
for filename in "${files[@]}"; do

View File

@ -2,7 +2,7 @@ FROM openjdk:8-jre-alpine
WORKDIR /generator
COPY target/openapi-generator-online-4.0.0-SNAPSHOT.jar /generator/openapi-generator-online.jar
COPY target/openapi-generator-online.jar /generator/openapi-generator-online.jar
ENV GENERATOR_HOST=http://localhost

View File

@ -27,6 +27,7 @@
</dependencies>
</dependencyManagement>
<build>
<finalName>openapi-generator-online</finalName>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>

View File

@ -41,6 +41,7 @@ public class CodegenParameter {
public CodegenProperty mostInnerItems;
public Map<String, Object> vendorExtensions = new HashMap<String, Object>();
public boolean hasValidation;
public boolean isNullable;
/**
* Determines whether this parameter is mandatory. If the parameter is in "path",
@ -150,6 +151,7 @@ public class CodegenParameter {
output.vendorExtensions = new HashMap<String, Object>(this.vendorExtensions);
}
output.hasValidation = this.hasValidation;
output.isNullable = this.isNullable;
output.isBinary = this.isBinary;
output.isByteArray = this.isByteArray;
output.isString = this.isString;
@ -269,6 +271,8 @@ public class CodegenParameter {
return false;
if (hasValidation != that.hasValidation)
return false;
if (isNullable != that.isNullable)
return false;
if (required != that.required)
return false;
if (maximum != null ? !maximum.equals(that.maximum) : that.maximum != null)
@ -344,6 +348,7 @@ public class CodegenParameter {
result = 31 * result + (mostInnerItems != null ? mostInnerItems.hashCode() : 0);
result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0);
result = 31 * result + (hasValidation ? 13:31);
result = 31 * result + (isNullable ? 13:31);
result = 31 * result + (required ? 13:31);
result = 31 * result + (maximum != null ? maximum.hashCode() : 0);
result = 31 * result + (exclusiveMaximum ? 13:31);
@ -409,6 +414,7 @@ public class CodegenParameter {
", mostInnerItems=" + mostInnerItems +
", vendorExtensions=" + vendorExtensions +
", hasValidation=" + hasValidation +
", isNullable=" + isNullable +
", required=" + required +
", maximum='" + maximum + '\'' +
", exclusiveMaximum=" + exclusiveMaximum +

View File

@ -1789,7 +1789,11 @@ public class DefaultCodegen implements CodegenConfig {
if (p.getWriteOnly() != null) {
property.isWriteOnly = p.getWriteOnly();
}
if (p.getNullable() != null) {
// use x-nullable
if (p.getExtensions() != null && p.getExtensions().get("x-nullable") != null) {
property.isNullable = Boolean.valueOf(p.getExtensions().get("x-nullable").toString());
} else if (p.getNullable() != null) { // use nullable defined in OAS3
property.isNullable = p.getNullable();
}
@ -2649,6 +2653,14 @@ public class DefaultCodegen implements CodegenConfig {
LOGGER.warn("warning! Schema not found for parameter \"" + parameter.getName() + "\", using String");
parameterSchema = new StringSchema().description("//TODO automatically added by openapi-generator due to missing type definition.");
}
// x-nullable extension in OAS2
if (parameter.getExtensions() != null && parameter.getExtensions().get("x-nullable") != null) {
codegenParameter.isNullable = Boolean.valueOf(parameter.getExtensions().get("x-nullable").toString());
} else if (Boolean.TRUE.equals(parameterSchema.getNullable())) { // use nullable defined in the spec
codegenParameter.isNullable = true;
}
// set default value
if (parameterSchema.getDefault() != null) {
codegenParameter.defaultValue = toDefaultValue(parameterSchema);
@ -4265,6 +4277,9 @@ public class DefaultCodegen implements CodegenConfig {
// default to csv:
codegenParameter.collectionFormat = StringUtils.isEmpty(collectionFormat) ? "csv" : collectionFormat;
// set nullable
setParameterNullable(codegenParameter, codegenProperty);
// recursively add import
while (codegenProperty != null) {
imports.add(codegenProperty.baseType);
@ -4293,7 +4308,7 @@ public class DefaultCodegen implements CodegenConfig {
public CodegenParameter fromFormProperty(String name, Schema propertySchema, Set<String> imports) {
CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER);
LOGGER.debug("Debugging fromFormProperty: " + name);
LOGGER.debug("Debugging fromFormProperty {}: {}", name, propertySchema);
CodegenProperty codegenProperty = fromProperty(name, propertySchema);
codegenParameter.isFormParam = Boolean.TRUE;
@ -4307,7 +4322,6 @@ public class DefaultCodegen implements CodegenConfig {
codegenParameter.jsonSchema = Json.pretty(propertySchema);
codegenParameter.defaultValue = codegenProperty.getDefaultValue();
if (codegenProperty.getVendorExtensions() != null && !codegenProperty.getVendorExtensions().isEmpty()) {
codegenParameter.vendorExtensions = codegenProperty.getVendorExtensions();
}
@ -4366,6 +4380,8 @@ public class DefaultCodegen implements CodegenConfig {
setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty);
setParameterExampleValue(codegenParameter);
// set nullable
setParameterNullable(codegenParameter, codegenProperty);
//TODO collectionFormat for form parameter not yet supported
//codegenParameter.collectionFormat = getCollectionFormat(propertySchema);
@ -4415,6 +4431,9 @@ public class DefaultCodegen implements CodegenConfig {
codegenParameter.isMapContainer = Boolean.TRUE;
setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty);
// set nullable
setParameterNullable(codegenParameter, codegenProperty);
} else if (ModelUtils.isArraySchema(schema)) {
final ArraySchema arraySchema = (ArraySchema) schema;
Schema inner = arraySchema.getItems();
@ -4454,6 +4473,8 @@ public class DefaultCodegen implements CodegenConfig {
codegenParameter.isListContainer = Boolean.TRUE;
setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty);
// set nullable
setParameterNullable(codegenParameter, codegenProperty);
while (codegenProperty != null) {
imports.add(codegenProperty.baseType);
@ -4516,6 +4537,8 @@ public class DefaultCodegen implements CodegenConfig {
}
}
setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty);
// set nullable
setParameterNullable(codegenParameter, codegenProperty);
}
} else {
@ -4539,6 +4562,8 @@ public class DefaultCodegen implements CodegenConfig {
}
setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty);
// set nullable
setParameterNullable(codegenParameter, codegenProperty);
}
// set the parameter's example value
@ -4636,4 +4661,12 @@ public class DefaultCodegen implements CodegenConfig {
}
return codegenServerVariables;
}
private void setParameterNullable(CodegenParameter parameter, CodegenProperty property) {
if (property.getVendorExtensions() != null && property.getVendorExtensions().get("x-nullable") != null) {
parameter.isNullable = Boolean.valueOf(property.getVendorExtensions().get("x-nullable").toString());
} else {
parameter.isNullable = property.isNullable;
}
}
}

View File

@ -246,11 +246,13 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen {
}
op.vendorExtensions.put("x-codegen-pistache-consumesJson", consumeJson);
op.vendorExtensions.put("x-codegen-pistache-isParsingSupported", isParsingSupported);
// Check if any one of the operations needs a model, then at API file level, at least one model has to be included.
for(String hdr : op.imports) {
if(importMapping.containsKey(hdr)) {
continue;
}
additionalProperties.put("hasModelImport", true);
operations.put("hasModelImport", true);
}
}

View File

@ -23,15 +23,19 @@ import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.CodegenParameter;
import org.openapitools.codegen.SupportingFile;
import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
@ -55,7 +59,7 @@ public class CppQt5QHttpEngineServerCodegen extends AbstractCppCodegen implement
protected Map<String, String> namespaces = new HashMap<String, String>();
protected Set<String> systemIncludes = new HashSet<String>();
protected String cppNamespace = "OpenAPI";
protected Set<String> nonFrameworkPrimitives = new HashSet<String>();
public CppQt5QHttpEngineServerCodegen() {
super();
@ -135,7 +139,17 @@ public class CppQt5QHttpEngineServerCodegen extends AbstractCppCodegen implement
"float",
"double")
);
nonFrameworkPrimitives.addAll(languageSpecificPrimitives);
foundationClasses.addAll(
Arrays.asList(
"QString",
"QDate",
"QDateTime",
"QByteArray")
);
languageSpecificPrimitives.addAll(foundationClasses);
supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder + MODEL_DIR, PREFIX + "Helpers.h"));
supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder + MODEL_DIR, PREFIX + "Helpers.cpp"));
supportingFiles.add(new SupportingFile("object.mustache", sourceFolder + MODEL_DIR, PREFIX + "Object.h"));
@ -174,7 +188,7 @@ public class CppQt5QHttpEngineServerCodegen extends AbstractCppCodegen implement
importMapping = new HashMap<String, String>();
namespaces = new HashMap<String, String>();
foundationClasses.add("QString");
systemIncludes.add("QString");
systemIncludes.add("QList");
@ -434,4 +448,71 @@ public class CppQt5QHttpEngineServerCodegen extends AbstractCppCodegen implement
public String getTypeDeclaration(String str) {
return str;
}
@Override
protected boolean needToImport(String type) {
return StringUtils.isNotBlank(type) && !defaultIncludes.contains(type)
&& !nonFrameworkPrimitives.contains(type);
}
@Override
@SuppressWarnings("unchecked")
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> objectMap = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operations = (List<CodegenOperation>) objectMap.get("operation");
List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports");
for (CodegenOperation operation : operations) {
// Check all return parameter baseType if there is a necessity to include, include it if not
// already done
if (operation.returnBaseType != null && needToImport(operation.returnBaseType)) {
if(!isIncluded(operation.returnBaseType, imports)) {
imports.add(createMapping("import", operation.returnBaseType));
}
}
List<CodegenParameter> params = new ArrayList<CodegenParameter>();
if (operation.allParams != null)params.addAll(operation.allParams);
// Check all parameter baseType if there is a necessity to include, include it if not
// already done
for(CodegenParameter param : params) {
if(param.isPrimitiveType && needToImport(param.baseType)) {
if(!isIncluded(param.baseType, imports)) {
imports.add(createMapping("import", param.baseType));
}
}
}
if (operation.pathParams != null) {
// We use QString to pass path params, add it to include
if(!isIncluded("QString", imports)) {
imports.add(createMapping("import", "QString"));
}
}
}
if(isIncluded("QMap", imports)) {
// Maps uses QString as key
if(!isIncluded("QString", imports)) {
imports.add(createMapping("import", "QString"));
}
}
return objs;
}
public Map<String, String> createMapping(String key, String value) {
Map<String, String> customImport = new HashMap<String, String>();
customImport.put(key, toModelImport(value));
return customImport;
}
private boolean isIncluded(String type, List<Map<String, String>> imports) {
boolean included = false;
String inclStr = toModelImport(type);
for (Map<String, String> importItem : imports) {
if(importItem.containsValue(inclStr)) {
included = true;
break;
}
}
return included;
}
}

View File

@ -33,6 +33,7 @@ import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.ExchangeStrategies;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Flux;
import java.util.Optional;
import java.io.BufferedReader;
import java.io.IOException;
@ -76,7 +77,7 @@ public class ApiClient {
}
private HttpHeaders defaultHeaders = new HttpHeaders();
private String basePath = "{{basePath}}";
private final WebClient webClient;
@ -87,16 +88,22 @@ public class ApiClient {
public ApiClient() {
this.dateFormat = createDefaultDateFormat();
this.webClient = buildWebClient(new ObjectMapper(), this.dateFormat);
this.webClient = buildWebClient(new ObjectMapper(), dateFormat);
this.init();
}
public ApiClient(ObjectMapper mapper, DateFormat format) {
this(buildWebClient(mapper.copy(), format), format);
}
public ApiClient(WebClient webClient, ObjectMapper mapper, DateFormat format) {
this(Optional.ofNullable(webClient).orElseGet(() ->buildWebClient(mapper.copy(), format)), format);
}
private ApiClient(WebClient webClient, DateFormat format) {
this.webClient = webClient;
this.dateFormat = format;
this.init();
}
public DateFormat createDefaultDateFormat() {
@ -104,7 +111,7 @@ public class ApiClient {
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return dateFormat;
}
protected void init() {
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}}
@ -132,7 +139,7 @@ public class ApiClient {
return webClient.build();
}
/**
* Get the current base path
* @return String the base path
@ -585,7 +592,7 @@ public class ApiClient {
auth.applyToParams(queryParams, headerParams);
}
}
private class ApiClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
private final Log log = LogFactory.getLog(ApiClientHttpRequestInterceptor.class);
@ -624,7 +631,7 @@ public class ApiClient {
builder.setLength(builder.length() - 1); // Get rid of trailing comma
return builder.toString();
}
private String bodyToString(InputStream body) throws IOException {
StringBuilder builder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8));

View File

@ -1,11 +1,11 @@
FROM alpine:latest AS build
RUN apk add --update \
RUN apk add --update \
cmake \
alpine-sdk \
openssl \
qt5-qtbase-dev \
qt5-qttools-dev
openssl \
qt5-qtbase-dev \
qt5-qttools-dev
WORKDIR /usr/server
ADD ./src ./src
@ -13,10 +13,10 @@ ADD ./CMakeLists.txt ./
RUN mkdir -p ./build
WORKDIR /usr/server/build
RUN cmake -DNODEBUG:STRING="ON" ..
RUN make
RUN make
FROM alpine:latest AS runtime
RUN apk add --update \
RUN apk add --update \
libgcc \
libstdc++ \
qt5-qtbase \

View File

@ -1,4 +1,4 @@
QHttpEngine
QHttpEngine
The MIT License (MIT)

View File

@ -1,8 +1,9 @@
# C++ Qt5 Server
## Qt5 HTTP Server based on the Qhttpengine
This server was generated by the [openapi-generator]
(https://openapi-generator.tech) project.
By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub.
-
This server was generated by the [openapi-generator](https://openapi-generator.tech) project.
By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub.
To see how to make this your own, look here:
@ -25,30 +26,36 @@ Simple set of classes for developing HTTP server applications in Qt.
To learn more about building and using the library, please visit this page:
https://ci.quickmediasolutions.com/job/qhttpengine-documentation/doxygen/
[Link](https://ci.quickmediasolutions.com/job/qhttpengine-documentation/doxygen)
### Viewing the code
You can view the code using an editor like Microsoft Visual Studio Code or you can
You can view the code using an editor like Microsoft Visual Studio Code or you can
Use QtCreator and browse for the root CMakeLists.txt and load it as a project
### Build with make
Install the tools [Linux/Debian]
```
```shell
sudo apt install cmake build-essential libssl-dev qtbase5-dev qtbase5-dev-tools git curl
```
To build, go to the `server` folder
```
make
```shell
make
```
To run the server
```
```shell
./build/src/cpp-qt5-server &
```
#### Invoke an API
```
```shell
curl -X GET http://localhost:8080/v2/store/inventory
curl -X POST http://localhost:8080/v2/store/order -H "Content-Type: application/json" -d "{ \"id\": 22, \"petId\": 1541, \"quantity\": 5, \"shipDate\": \"2018-06-16T18:31:43.870Z\", \"status\": \"placed\", \"complete\": \"true\" }"
curl -X GET http://localhost:8080/v2/pet/findByStatus
@ -56,38 +63,50 @@ curl -X GET http://localhost:8080/v2/store/inventory
```
### Run and build with docker
Building with docker multistage
If you dont have docker install [here](https://docs.docker.com/install)
Add yourself to the docker group
```
```shell
docker build --network=host -t cpp-qt5-server .
```
Running with docker
```
docker run --rm -it --name=server-container cpp-qt5-server
Running with docker
```shell
docker run --rm -it --name=server-container cpp-qt5-server
```
#### Invoking an API
Mind the IP here
```
```shell
curl -X GET http://172.17.0.2:8080/v2/store/inventory
curl -X POST http://172.17.0.2:8080/v2/store/order -H "Content-Type: application/json" -d "{ \"id\": 22, \"petId\": 1541, \"quantity\": 5, \"shipDate\": \"2018-06-16T18:31:43.870Z\", \"status\": \"placed\", \"complete\": \"true\" }"
```
use this command to get the container IP
```
```shell
docker inspect server-container | grep "IPAddress"
```
To exit from the command line
```
To exit from the command line
```shell
Ctrl + p + q
```
To stop container
```
```shell
docker stop <containername>
```
or to terminate and quit
```
```shell
Ctrl+C
```

View File

@ -16,7 +16,7 @@ namespace {{this}} {
auto headers = s->headers();
for(auto itr = headers.begin(); itr != headers.end(); itr++) {
requestHeaders.insert(QString(itr.key()), QString(itr.value()));
}
}
}
{{classname}}Request::~{{classname}}Request(){
@ -24,7 +24,7 @@ namespace {{this}} {
qDebug() << "{{classname}}Request::~{{classname}}Request()";
}
QMap<QString, QString>
QMap<QString, QString>
{{classname}}Request::getRequestHeaders() const {
return requestHeaders;
}
@ -44,9 +44,9 @@ QHttpEngine::Socket* {{classname}}Request::getRawSocket(){
void {{classname}}Request::{{nickname}}Request({{#hasPathParams}}{{#pathParams}}const QString& {{{paramName}}}str{{#hasMore}}, {{/hasMore}}{{/pathParams}}{{/hasPathParams}}){
qDebug() << "{{{basePathWithoutHost}}}{{{path}}}";
connect(this, &{{classname}}Request::{{nickname}}, handler, &{{classname}}Handler::{{nickname}});
{{#queryParams}}{{queryParam}}
{{{dataType}}} {{paramName}};
{{{dataType}}} {{paramName}};
if(socket->queryString().keys().contains("{{paramName}}")){
fromStringValue(socket->queryString().value{{#isListContainer}}s{{/isListContainer}}("{{paramName}}"), {{paramName}});
}
@ -63,7 +63,7 @@ void {{classname}}Request::{{nickname}}Request({{#hasPathParams}}{{#pathParams}}
{{{dataType}}} {{paramName}};{{/formParams}}{{#bodyParams}} {{#bodyParam}}
{{#isListContainer}}
QJsonDocument doc;
{{{dataType}}} {{paramName}};
{{{dataType}}} {{paramName}};
if(socket->readJson(doc)){
QJsonArray jsonArray = doc.array();
foreach(QJsonValue obj, jsonArray) {
@ -84,7 +84,7 @@ void {{classname}}Request::{{nickname}}Request({{#hasPathParams}}{{#pathParams}}
QJsonDocument doc;
socket->readJson(doc);
QJsonObject obj = doc.object();
{{{dataType}}} {{paramName}};
{{{dataType}}} {{paramName}};
foreach(QString key, obj.keys()) {
{{baseType}} val;
::{{cppNamespace}}::fromJsonValue(val, obj[key]);
@ -100,19 +100,21 @@ void {{classname}}Request::{{nickname}}Request({{#hasPathParams}}{{#pathParams}}
::{{cppNamespace}}::fromJsonValue({{paramName}}, obj);
{{/isPrimitiveType}}
{{/isMapContainer}}
{{/isListContainer}}
{{/isListContainer}}
{{/bodyParam}}{{/bodyParams}}
emit {{nickname}}({{#allParams}}{{#isBodyParam}}{{/isBodyParam}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
emit {{nickname}}({{#allParams}}{{#isBodyParam}}{{/isBodyParam}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
}
{{/operation}}{{/operations}}
{{/operation}}{{/operations}}
{{#operations}}{{#operation}}void {{classname}}Request::{{nickname}}Response({{#returnType}}const {{{returnType}}}& res{{/returnType}}){
writeResponseHeaders();{{#returnType}}{{^isPrimitiveType}}
QJsonDocument resDoc(::{{cppNamespace}}::toJsonValue(res).to{{^isListContainer}}Object{{/isListContainer}}{{#isListContainer}}Array{{/isListContainer}}());{{/isPrimitiveType}}
socket->writeJson(resDoc);{{#isPrimitiveType}}
socket->write({{#isListContainer}}QString("["+{{/isListContainer}}::{{cppNamespace}}::toStringValue(res){{#isListContainer}}+"]"){{/isListContainer}}.toUtf8());{{/isPrimitiveType}}{{/returnType}}{{^returnType}}
writeResponseHeaders();{{#returnType}}{{#isMapContainer}}
QJsonDocument resDoc(::{{cppNamespace}}::toJsonValue(res).toObject());
socket->writeJson(resDoc);{{/isMapContainer}}{{^isMapContainer}}{{^returnTypeIsPrimitive}}
QJsonDocument resDoc(::{{cppNamespace}}::toJsonValue(res).to{{^isListContainer}}Object{{/isListContainer}}{{#isListContainer}}Array{{/isListContainer}}());
socket->writeJson(resDoc);{{/returnTypeIsPrimitive}}{{#returnTypeIsPrimitive}}
socket->write({{#isListContainer}}QString("["+{{/isListContainer}}::{{cppNamespace}}::toStringValue(res){{#isListContainer}}+"]"){{/isListContainer}}.toUtf8());{{/returnTypeIsPrimitive}}{{/isMapContainer}}{{/returnType}}{{^returnType}}
socket->setStatusCode(QHttpEngine::Socket::OK);{{/returnType}}
if(socket->isOpen()){
socket->close();
@ -123,10 +125,12 @@ void {{classname}}Request::{{nickname}}Request({{#hasPathParams}}{{#pathParams}}
{{#operations}}{{#operation}}void {{classname}}Request::{{nickname}}Error({{#returnType}}const {{{returnType}}}& res, {{/returnType}}QNetworkReply::NetworkError error_type, QString& error_str){
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();{{#returnType}}
Q_UNUSED(error_str); // response will be used instead of error string{{^isPrimitiveType}}
QJsonDocument resDoc(::{{cppNamespace}}::toJsonValue(res).to{{^isListContainer}}Object{{/isListContainer}}{{#isListContainer}}Array{{/isListContainer}}());{{/isPrimitiveType}}
socket->writeJson(resDoc);{{#isPrimitiveType}}
socket->write({{#isListContainer}}QString("["+{{/isListContainer}}::{{cppNamespace}}::toStringValue(res){{#isListContainer}}+"]"){{/isListContainer}}.toUtf8());{{/isPrimitiveType}}{{/returnType}}{{^returnType}}
Q_UNUSED(error_str); // response will be used instead of error string{{#isMapContainer}}
QJsonDocument resDoc(::{{cppNamespace}}::toJsonValue(res).toObject());
socket->writeJson(resDoc);{{/isMapContainer}}{{^isMapContainer}}{{^returnTypeIsPrimitive}}
QJsonDocument resDoc(::{{cppNamespace}}::toJsonValue(res).to{{^isListContainer}}Object{{/isListContainer}}{{#isListContainer}}Array{{/isListContainer}}());
socket->writeJson(resDoc);{{/returnTypeIsPrimitive}}{{#returnTypeIsPrimitive}}
socket->write({{#isListContainer}}QString("["+{{/isListContainer}}::{{cppNamespace}}::toStringValue(res){{#isListContainer}}+"]"){{/isListContainer}}.toUtf8());{{/returnTypeIsPrimitive}}{{/isMapContainer}}{{/returnType}}{{^returnType}}
socket->setStatusCode(QHttpEngine::Socket::NotFound);
socket->write(error_str.toUtf8());{{/returnType}}
if(socket->isOpen()){
@ -139,7 +143,7 @@ void {{classname}}Request::sendCustomResponse(QByteArray & res, QNetworkReply::N
Q_UNUSED(res); // TODO
Q_UNUSED(error_type); // TODO
}
void {{classname}}Request::sendCustomResponse(QIODevice *res, QNetworkReply::NetworkError error_type){
Q_UNUSED(res); // TODO
Q_UNUSED(error_type); // TODO

View File

@ -20,7 +20,7 @@ namespace {{this}} {
class {{classname}}Request : public QObject
{
Q_OBJECT
public:
{{classname}}Request(QHttpEngine::Socket *s, {{classname}}Handler* handler);
virtual ~{{classname}}Request();
@ -60,7 +60,7 @@ private:
resHeaders.insert(itr.key().toUtf8(), itr.value().toUtf8());
}
socket->setHeaders(resHeaders);
socket->writeHeaders();
socket->writeHeaders();
}
};

View File

@ -13,80 +13,73 @@
namespace {{this}} {
{{/cppNamespaceDeclarations}}
inline QHttpEngine::Socket::Method toQHttpEngineMethod(QString method){
if( method == QString("OPTIONS"))
return QHttpEngine::Socket::Method::OPTIONS;
if( method == QString("GET"))
return QHttpEngine::Socket::Method::GET;
if( method == QString("HEAD"))
return QHttpEngine::Socket::Method::HEAD;
if( method == QString("POST"))
return QHttpEngine::Socket::Method::POST;
if( method == QString("PUT"))
return QHttpEngine::Socket::Method::PUT;
if( method == QString("DELETE"))
return QHttpEngine::Socket::Method::DELETE;
if( method == QString("TRACE"))
return QHttpEngine::Socket::Method::TRACE;
if( method == QString("CONNECT"))
return QHttpEngine::Socket::Method::CONNECT;
return static_cast<QHttpEngine::Socket::Method>(-1);
{{prefix}}ApiRouter::{{prefix}}ApiRouter() {
createApiHandlers();
}
ApiRouter::ApiRouter() {
{{#apiInfo}}{{#apis}}{{classname}}ApiHandler = new {{classname}}Handler();
{{/apis}}{{/apiInfo}}
{{prefix}}ApiRouter::~{{prefix}}ApiRouter(){
qDebug() << "~ApiRouter()";{{#apiInfo}}{{#apis}}
delete {{classname}}ApiHandler;{{/apis}}{{/apiInfo}}
}
ApiRouter::~ApiRouter(){
qDebug() << "~ApiRouter()";
{{#apiInfo}}{{#apis}}delete {{classname}}ApiHandler;
{{/apis}}{{/apiInfo}}
void {{prefix}}ApiRouter::createApiHandlers() { {{#apiInfo}}{{#apis}}
{{classname}}ApiHandler = new {{classname}}Handler();{{/apis}}{{/apiInfo}}
}
void ApiRouter::setUpRoutes() {
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{^pathParams}}
Routes.insert("{{{basePathWithoutHost}}}{{{path}}}",[this](QHttpEngine::Socket *socket) {
if(toQHttpEngineMethod("{{httpMethod}}") == socket->method()){
void {{prefix}}ApiRouter::setUpRoutes() {
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{^hasPathParams}}
Routes.insert(QString("%1 %2").arg("{{httpMethod}}").arg("{{{basePathWithoutHost}}}{{{path}}}").toLower(), [this](QHttpEngine::Socket *socket) {
auto reqObj = new {{classname}}Request(socket, {{classname}}ApiHandler);
reqObj->{{nickname}}Request();
}
});{{/pathParams}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
});{{/hasPathParams}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
}
void ApiRouter::processRequest(QHttpEngine::Socket *socket){
if (Routes.contains(socket->path())) {
for(auto endpoints : Routes.values(socket->path())) {
endpoints.operator()(socket);
}
} else
{ {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{#pathParams}}
{
QString completePath("{{{basePathWithoutHost}}}{{{path}}}");
QString {{paramName}}PathParam("{");
{{paramName}}PathParam.append("{{baseName}}").append("}");
completePath.replace("/", "\\/"); // replace '/' with '\/' for regex
completePath.replace({{paramName}}PathParam, "([^\\/]*?)"); // match anything but '/''
completePath.append("$"); // End of string
QRegularExpression re(completePath, QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatch match = re.match(socket->path());
if ((toQHttpEngineMethod("{{httpMethod}}") == socket->method()) && match.hasMatch() ) {
QString pathparam = match.captured(1);
auto reqObj = new {{classname}}Request(socket, {{classname}}ApiHandler);
reqObj->{{nickname}}Request({{#hasPathParams}}{{#pathParams}}pathparam{{/pathParams}}{{/hasPathParams}});
return;
}
}{{/pathParams}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
void {{prefix}}ApiRouter::processRequest(QHttpEngine::Socket *socket){
if( handleRequest(socket) ){
return;
}
if( handleRequestAndExtractPathParam(socket) ){
return;
}
socket->setStatusCode(QHttpEngine::Socket::NotFound);
if(socket->isOpen()){
socket->writeHeaders();
socket->close();
}
return;
}
bool {{prefix}}ApiRouter::handleRequest(QHttpEngine::Socket *socket){
auto reqPath = QString("%1 %2").arg(fromQHttpEngineMethod(socket->method())).arg(socket->path()).toLower();
if ( Routes.contains(reqPath) ) {
Routes.value(reqPath).operator()(socket);
return true;
}
return false;
}
bool {{prefix}}ApiRouter::handleRequestAndExtractPathParam(QHttpEngine::Socket *socket){
auto reqPath = QString("%1 %2").arg(fromQHttpEngineMethod(socket->method())).arg(socket->path()).toLower();{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{#hasPathParams}}
{
auto completePath = QString("%1 %2").arg("{{httpMethod}}").arg("{{{basePathWithoutHost}}}{{{path}}}").toLower();
if ( reqPath.startsWith(completePath.leftRef( completePath.indexOf(QString("/{")))) ) {
QRegularExpression parExpr( R"(\{([^\/\\s]+)\})" );
completePath.replace( parExpr, R"((?<\1>[^\/\s]+))" );
completePath.append("[\\/]?$");
QRegularExpression pathExpr( completePath );
QRegularExpressionMatch match = pathExpr.match( reqPath );
if ( match.hasMatch() ){
{{#pathParams}}
QString {{baseName}} = match.captured(QString("{{baseName}}").toLower());
{{/pathParams}}
auto reqObj = new {{classname}}Request(socket, {{classname}}ApiHandler);
reqObj->{{nickname}}Request({{#pathParams}}{{baseName}}{{#hasMore}}, {{/hasMore}}{{/pathParams}});
return true;
}
}
}{{/hasPathParams}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
return false;
}
{{#cppNamespaceDeclarations}}
}
{{/cppNamespaceDeclarations}}

View File

@ -19,7 +19,7 @@
namespace {{this}} {
{{/cppNamespaceDeclarations}}
class RequestHandler : public QHttpEngine::QObjectHandler
class {{prefix}}ApiRequestHandler : public QHttpEngine::QObjectHandler
{
Q_OBJECT
signals:
@ -32,19 +32,51 @@ protected:
}
};
class ApiRouter : public QObject
class {{prefix}}ApiRouter : public QObject
{
Q_OBJECT
public:
ApiRouter();
virtual ~ApiRouter();
{{prefix}}ApiRouter();
virtual ~{{prefix}}ApiRouter();
void setUpRoutes();
void processRequest(QHttpEngine::Socket *socket);
private:
QMultiMap<QString, std::function<void(QHttpEngine::Socket *)>> Routes;
QMap<QString, std::function<void(QHttpEngine::Socket *)>> Routes;
QMultiMap<QString, std::function<void(QHttpEngine::Socket *)>> RoutesWithPathParam;
bool handleRequest(QHttpEngine::Socket *socket);
bool handleRequestAndExtractPathParam(QHttpEngine::Socket *socket);
{{#apiInfo}}{{#apis}}
{{classname}}Handler *{{classname}}ApiHandler;{{/apis}}{{/apiInfo}}
{{classname}}Handler *{{classname}}ApiHandler;{{/apis}}{{/apiInfo}}
protected:
// override this method to provide custom class derived from ApiHandler classes
virtual void createApiHandlers();
private :
inline QString fromQHttpEngineMethod(QHttpEngine::Socket::Method method){
switch( method ){
case QHttpEngine::Socket::Method::OPTIONS:
return QStringLiteral("OPTIONS");
case QHttpEngine::Socket::Method::GET:
return QStringLiteral("GET");
case QHttpEngine::Socket::Method::HEAD:
return QStringLiteral("HEAD");
case QHttpEngine::Socket::Method::POST:
return QStringLiteral("POST");
case QHttpEngine::Socket::Method::PUT:
return QStringLiteral("PUT");
case QHttpEngine::Socket::Method::DELETE:
return QStringLiteral("DELETE");
case QHttpEngine::Socket::Method::TRACE:
return QStringLiteral("TRACE");
case QHttpEngine::Socket::Method::CONNECT:
return QStringLiteral("CONNECT");
}
return QStringLiteral("");
}
};

View File

@ -125,7 +125,7 @@ namespace {{this}} {
for(auto itemkey : varmap.keys() ){
T itemVal;
fromJsonValue(itemVal, QJsonValue::fromVariant(varmap.value(itemkey)));
val.insert(itemkey, val);
val.insert(itemkey, itemVal);
}
}
return;

View File

@ -8,43 +8,43 @@
#include <QStringList>
#include <QSharedPointer>
#include <QObject>
#ifdef __linux__
#ifdef __linux__
#include <signal.h>
#include <unistd.h>
#endif
#endif
#include <qhttpengine/server.h>
#include "{{prefix}}ApiRouter.h"
#ifdef __linux__
#ifdef __linux__
void catchUnixSignals(QList<int> quitSignals) {
auto handler = [](int sig) -> void {
// blocking and not aysnc-signal-safe func are valid
qDebug() << "\nquit the application by signal " << sig;
QCoreApplication::quit();
};
sigset_t blocking_mask;
sigemptyset(&blocking_mask);
for (auto sig : quitSignals)
sigaddset(&blocking_mask, sig);
struct sigaction sa;
sa.sa_handler = handler;
sa.sa_mask = blocking_mask;
sa.sa_flags = 0;
for (auto sig : quitSignals)
sigset_t blocking_mask;
sigemptyset(&blocking_mask);
for (auto sig : quitSignals)
sigaddset(&blocking_mask, sig);
struct sigaction sa;
sa.sa_handler = handler;
sa.sa_mask = blocking_mask;
sa.sa_flags = 0;
for (auto sig : quitSignals)
sigaction(sig, &sa, nullptr);
}
#endif
#endif
int main(int argc, char * argv[])
{
QCoreApplication a(argc, argv);
#ifdef __linux__
#ifdef __linux__
QList<int> sigs({SIGQUIT, SIGINT, SIGTERM, SIGHUP});
catchUnixSignals(sigs);
#endif
#endif
// Build the command-line options
QCommandLineParser parser;
QCommandLineOption addressOption(
@ -69,11 +69,11 @@ int main(int argc, char * argv[])
// Obtain the values
QHostAddress address = QHostAddress(parser.value(addressOption));
quint16 port = static_cast<quint16>(parser.value(portOption).toInt());
QSharedPointer<{{cppNamespace}}::RequestHandler> handler(new {{cppNamespace}}::RequestHandler());
{{cppNamespace}}::ApiRouter router;
QSharedPointer<{{cppNamespace}}::{{prefix}}ApiRequestHandler> handler(new {{cppNamespace}}::{{prefix}}ApiRequestHandler());
{{cppNamespace}}::{{prefix}}ApiRouter router;
router.setUpRoutes();
QObject::connect(handler.data(), &{{cppNamespace}}::RequestHandler::requestReceived, [&](QHttpEngine::Socket *socket) {
QObject::connect(handler.data(), &{{cppNamespace}}::{{prefix}}ApiRequestHandler::requestReceived, [&](QHttpEngine::Socket *socket) {
router.processRequest(socket);
});
@ -84,6 +84,6 @@ int main(int argc, char * argv[])
qCritical("Unable to listen on the specified port.");
return 1;
}
return a.exec();
}

View File

@ -22,7 +22,7 @@ namespace {{this}} {
}
{{classname}}::~{{classname}}() {
}
void
@ -77,7 +77,7 @@ QJsonObject
{{classname}}::asJsonObject() const {
QJsonObject obj;
{{#vars}}
{{^isContainer}}{{#complexType}}{{^isString}}{{^isDateTime}}{{^isByteArray}}{{^isDate}}if({{name}}.isSet()){{/isDate}}{{/isByteArray}}{{/isDateTime}}{{/isString}}{{/complexType}}{{^complexType}}if(m_{{name}}_isSet){{/complexType}}{{#isString}}if(m_{{name}}_isSet){{/isString}}{{#isDateTime}}if(m_{{name}}_isSet){{/isDateTime}}{{#isByteArray}}if(m_{{name}}_isSet){{/isByteArray}}{{#isDate}}if(m_{{name}}_isSet){{/isDate}}{
{{^isContainer}}{{#complexType}}if({{name}}.isSet()){{/complexType}}{{^complexType}}if(m_{{name}}_isSet){{/complexType}}{
obj.insert(QString("{{baseName}}"), ::{{cppNamespace}}::toJsonValue({{name}}));
}{{/isContainer}}{{#isContainer}}
if({{name}}.size() > 0){
@ -105,7 +105,7 @@ bool
{{classname}}::isSet() const {
bool isObjectUpdated = false;
do{ {{#vars}}
{{#isContainer}}if({{name}}.size() > 0){{/isContainer}}{{^isContainer}}{{#complexType}}{{^isString}}{{^isDateTime}}{{^isByteArray}}{{^isDate}}if({{name}}.isSet()){{/isDate}}{{/isByteArray}}{{/isDateTime}}{{/isString}}{{/complexType}}{{^complexType}}if(m_{{name}}_isSet){{/complexType}}{{#isString}}if(m_{{name}}_isSet){{/isString}}{{#isDateTime}}if(m_{{name}}_isSet){{/isDateTime}}{{#isByteArray}}if(m_{{name}}_isSet){{/isByteArray}}{{#isDate}}if(m_{{name}}_isSet){{/isDate}}{{/isContainer}}{ isObjectUpdated = true; break;}
{{#isContainer}}if({{name}}.size() > 0){{/isContainer}}{{^isContainer}}{{#complexType}}if({{name}}.isSet()){{/complexType}}{{^complexType}}if(m_{{name}}_isSet){{/complexType}}{{/isContainer}}{ isObjectUpdated = true; break;}
{{/vars}}}while(false);
return isObjectUpdated;
}

View File

@ -12,9 +12,9 @@ namespace {{this}} {
class {{prefix}}Object {
public:
virtual ~{{prefix}}Object(){
}
virtual QJsonObject asJsonObject() const {
return jObj;
}

View File

@ -12,7 +12,7 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -std=c++14 -Wall -Wno-unused-varia
if(${NODEBUG} STREQUAL "OFF")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pg -g3")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pg -g3")
else (${NODEBUG} STREQUAL "OFF")
else (${NODEBUG} STREQUAL "OFF")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -s -O3")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s -O3")
endif(${NODEBUG} STREQUAL "OFF")

View File

@ -87,6 +87,10 @@ class {{controllerName}} extends Controller
// Set key with prefix in query string
$security{{name}} = $request->query->get('{{keyParamName}}');
{{/isKeyInQuery}}
{{#isKeyInCookie}}
// Set key with prefix in cookies
$security{{name}} = $request->cookies->get('{{keyParamName}}');
{{/isKeyInCookie}}
{{/isApiKey}}
{{#isBasic}}
// HTTP basic authentication required

View File

@ -38,21 +38,24 @@ class RESTClientObject(object):
def __init__(self, configuration, pools_size=4, maxsize=4):
# maxsize is number of requests to host that are allowed in parallel
# ca_certs vs cert_file vs key_file
# http://stackoverflow.com/a/23957365/2985775
# ca_certs
if configuration.ssl_ca_cert:
ca_certs = configuration.ssl_ca_cert
if configuration.verify_ssl:
# ca_certs
if configuration.ssl_ca_cert:
ca_certs = configuration.ssl_ca_cert
else:
# if not set certificate file, use Mozilla's root certificates.
ca_certs = certifi.where()
ssl_context = ssl.create_default_context(cafile=ca_certs)
if configuration.cert_file:
ssl_context.load_cert_chain(
configuration.cert_file, keyfile=configuration.key_file
)
else:
# if not set certificate file, use Mozilla's root certificates.
ca_certs = certifi.where()
ssl_context = ssl.create_default_context(cafile=ca_certs)
if configuration.cert_file:
ssl_context.load_cert_chain(
configuration.cert_file, keyfile=configuration.key_file
)
ssl_context = None
connector = aiohttp.TCPConnector(
limit=maxsize,

View File

@ -172,7 +172,7 @@ public class RubyClientCodegenTest {
@Test(description = "test nullable for properties")
public void nullableTest() {
public void nullablePropertyTest() {
final OpenAPI openAPI = new OpenAPIParser().readLocation("src/test/resources/3_0/petstore_oas3_test.yaml", null, new ParseOptions()).getOpenAPI();
final RubyClientCodegen codegen = new RubyClientCodegen();
codegen.setModuleName("OnlinePetstore");
@ -227,4 +227,49 @@ public class RubyClientCodegenTest {
Assert.assertFalse(cp5.isNullable);
}
@Test(description = "test nullable for parameters (OAS3)")
public void nullableParameterOAS3Test() {
final OpenAPI openAPI = new OpenAPIParser().readLocation("src/test/resources/3_0/petstore_oas3_test.yaml", null, new ParseOptions()).getOpenAPI();
final RubyClientCodegen codegen = new RubyClientCodegen();
codegen.setModuleName("OnlinePetstore");
final String path = "/pet/{petId}";
final Operation p = openAPI.getPaths().get(path).getPost();
final CodegenOperation op = codegen.fromOperation(path, "post", p, openAPI.getComponents().getSchemas());
Assert.assertEquals(op.pathParams.size(), 1);
CodegenParameter pp = op.pathParams.get(0);
Assert.assertTrue(pp.isNullable);
Assert.assertEquals(op.formParams.size(), 2);
CodegenParameter name = op.formParams.get(0);
Assert.assertFalse(name.isNullable);
CodegenParameter status = op.formParams.get(1);
Assert.assertTrue(status.isNullable);
}
@Test(description = "test nullable for parameters (OAS2)")
public void nullableParameterOAS2Test() {
final OpenAPI openAPI = new OpenAPIParser().readLocation("src/test/resources/2_0/petstore-nullable.yaml", null, new ParseOptions()).getOpenAPI();
final RubyClientCodegen codegen = new RubyClientCodegen();
codegen.setModuleName("OnlinePetstore");
final String path = "/pet/{petId}";
final Operation p = openAPI.getPaths().get(path).getPost();
final CodegenOperation op = codegen.fromOperation(path, "post", p, openAPI.getComponents().getSchemas());
// path parameter x-nullable test
Assert.assertEquals(op.pathParams.size(), 1);
CodegenParameter pp = op.pathParams.get(0);
Assert.assertTrue(pp.isNullable);
// form parameter x-nullable test
Assert.assertEquals(op.formParams.size(), 2);
CodegenParameter name = op.formParams.get(0);
Assert.assertFalse(name.isNullable);
CodegenParameter status = op.formParams.get(1);
// TODO comment out the following as there seems to be an issue with swagger parser not brining over the
// vendor extensions of the form parameter when creating the schema
//Assert.assertTrue(status.isNullable);
}
}

View File

@ -0,0 +1,702 @@
swagger: '2.0'
info:
description: 'This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.'
version: 1.0.0
title: OpenAPI Petstore
license:
name: Apache-2.0
url: 'http://www.apache.org/licenses/LICENSE-2.0.html'
host: petstore.swagger.io
basePath: /v2
tags:
- name: pet
description: Everything about your Pets
- name: store
description: Access to Petstore orders
- name: user
description: Operations about user
schemes:
- http
paths:
/pet:
post:
tags:
- pet
summary: Add a new pet to the store
description: ''
operationId: addPet
consumes:
- application/json
- application/xml
produces:
- application/xml
- application/json
parameters:
- in: body
name: body
description: Pet object that needs to be added to the store
required: true
schema:
$ref: '#/definitions/Pet'
responses:
'405':
description: Invalid input
security:
- petstore_auth:
- 'write:pets'
- 'read:pets'
put:
tags:
- pet
summary: Update an existing pet
description: ''
operationId: updatePet
consumes:
- application/json
- application/xml
produces:
- application/xml
- application/json
parameters:
- in: body
name: body
description: Pet object that needs to be added to the store
required: true
schema:
$ref: '#/definitions/Pet'
responses:
'400':
description: Invalid ID supplied
'404':
description: Pet not found
'405':
description: Validation exception
security:
- petstore_auth:
- 'write:pets'
- 'read:pets'
/pet/findByStatus:
get:
tags:
- pet
summary: Finds Pets by status
description: Multiple status values can be provided with comma separated strings
operationId: findPetsByStatus
produces:
- application/xml
- application/json
parameters:
- name: status
in: query
description: Status values that need to be considered for filter
required: true
type: array
items:
type: string
enum:
- available
- pending
- sold
default: available
collectionFormat: csv
responses:
'200':
description: successful operation
schema:
type: array
items:
$ref: '#/definitions/Pet'
'400':
description: Invalid status value
security:
- petstore_auth:
- 'write:pets'
- 'read:pets'
/pet/findByTags:
get:
tags:
- pet
summary: Finds Pets by tags
description: 'Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.'
operationId: findPetsByTags
produces:
- application/xml
- application/json
parameters:
- name: tags
in: query
description: Tags to filter by
required: true
type: array
items:
type: string
collectionFormat: csv
responses:
'200':
description: successful operation
schema:
type: array
items:
$ref: '#/definitions/Pet'
'400':
description: Invalid tag value
security:
- petstore_auth:
- 'write:pets'
- 'read:pets'
deprecated: true
'/pet/{petId}':
get:
tags:
- pet
summary: Find pet by ID
description: Returns a single pet
operationId: getPetById
produces:
- application/xml
- application/json
parameters:
- name: petId
in: path
description: ID of pet to return
required: true
type: integer
format: int64
responses:
'200':
description: successful operation
schema:
$ref: '#/definitions/Pet'
'400':
description: Invalid ID supplied
'404':
description: Pet not found
security:
- api_key: []
post:
tags:
- pet
summary: Updates a pet in the store with form data
description: ''
operationId: updatePetWithForm
consumes:
- application/x-www-form-urlencoded
produces:
- application/xml
- application/json
parameters:
- name: petId
in: path
description: ID of pet that needs to be updated
required: true
type: integer
format: int64
x-nullable: true
- name: name
in: formData
description: Updated name of the pet
required: false
type: string
- name: status
in: formData
description: Updated status of the pet
required: false
type: string
x-nullable: true
responses:
'405':
description: Invalid input
security:
- petstore_auth:
- 'write:pets'
- 'read:pets'
delete:
tags:
- pet
summary: Deletes a pet
description: ''
operationId: deletePet
produces:
- application/xml
- application/json
parameters:
- name: api_key
in: header
required: false
type: string
- name: petId
in: path
description: Pet id to delete
required: true
type: integer
format: int64
responses:
'400':
description: Invalid pet value
security:
- petstore_auth:
- 'write:pets'
- 'read:pets'
'/pet/{petId}/uploadImage':
post:
tags:
- pet
summary: uploads an image
description: ''
operationId: uploadFile
consumes:
- multipart/form-data
produces:
- application/json
parameters:
- name: petId
in: path
description: ID of pet to update
required: true
type: integer
format: int64
- name: additionalMetadata
in: formData
description: Additional data to pass to server
required: false
type: string
- name: file
in: formData
description: file to upload
required: false
type: file
responses:
'200':
description: successful operation
schema:
$ref: '#/definitions/ApiResponse'
security:
- petstore_auth:
- 'write:pets'
- 'read:pets'
/store/inventory:
get:
tags:
- store
summary: Returns pet inventories by status
description: Returns a map of status codes to quantities
operationId: getInventory
produces:
- application/json
parameters: []
responses:
'200':
description: successful operation
schema:
type: object
additionalProperties:
type: integer
format: int32
security:
- api_key: []
/store/order:
post:
tags:
- store
summary: Place an order for a pet
description: ''
operationId: placeOrder
produces:
- application/xml
- application/json
parameters:
- in: body
name: body
description: order placed for purchasing the pet
required: true
schema:
$ref: '#/definitions/Order'
responses:
'200':
description: successful operation
schema:
$ref: '#/definitions/Order'
'400':
description: Invalid Order
'/store/order/{orderId}':
get:
tags:
- store
summary: Find purchase order by ID
description: 'For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions'
operationId: getOrderById
produces:
- application/xml
- application/json
parameters:
- name: orderId
in: path
description: ID of pet that needs to be fetched
required: true
type: integer
maximum: 5
minimum: 1
format: int64
responses:
'200':
description: successful operation
schema:
$ref: '#/definitions/Order'
'400':
description: Invalid ID supplied
'404':
description: Order not found
delete:
tags:
- store
summary: Delete purchase order by ID
description: For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
operationId: deleteOrder
produces:
- application/xml
- application/json
parameters:
- name: orderId
in: path
description: ID of the order that needs to be deleted
required: true
type: string
responses:
'400':
description: Invalid ID supplied
'404':
description: Order not found
/user:
post:
tags:
- user
summary: Create user
description: This can only be done by the logged in user.
operationId: createUser
produces:
- application/xml
- application/json
parameters:
- in: body
name: body
description: Created user object
required: true
schema:
$ref: '#/definitions/User'
responses:
default:
description: successful operation
/user/createWithArray:
post:
tags:
- user
summary: Creates list of users with given input array
description: ''
operationId: createUsersWithArrayInput
produces:
- application/xml
- application/json
parameters:
- in: body
name: body
description: List of user object
required: true
schema:
type: array
items:
$ref: '#/definitions/User'
responses:
default:
description: successful operation
/user/createWithList:
post:
tags:
- user
summary: Creates list of users with given input array
description: ''
operationId: createUsersWithListInput
produces:
- application/xml
- application/json
parameters:
- in: body
name: body
description: List of user object
required: true
schema:
type: array
items:
$ref: '#/definitions/User'
responses:
default:
description: successful operation
/user/login:
get:
tags:
- user
summary: Logs user into the system
description: ''
operationId: loginUser
produces:
- application/xml
- application/json
parameters:
- name: username
in: query
description: The user name for login
required: true
type: string
- name: password
in: query
description: The password for login in clear text
required: true
type: string
responses:
'200':
description: successful operation
schema:
type: string
headers:
X-Rate-Limit:
type: integer
format: int32
description: calls per hour allowed by the user
X-Expires-After:
type: string
format: date-time
description: date in UTC when toekn expires
'400':
description: Invalid username/password supplied
/user/logout:
get:
tags:
- user
summary: Logs out current logged in user session
description: ''
operationId: logoutUser
produces:
- application/xml
- application/json
parameters: []
responses:
default:
description: successful operation
'/user/{username}':
get:
tags:
- user
summary: Get user by user name
description: ''
operationId: getUserByName
produces:
- application/xml
- application/json
parameters:
- name: username
in: path
description: 'The name that needs to be fetched. Use user1 for testing.'
required: true
type: string
responses:
'200':
description: successful operation
schema:
$ref: '#/definitions/User'
'400':
description: Invalid username supplied
'404':
description: User not found
put:
tags:
- user
summary: Updated user
description: This can only be done by the logged in user.
operationId: updateUser
produces:
- application/xml
- application/json
parameters:
- name: username
in: path
description: name that need to be deleted
required: true
type: string
- in: body
name: body
description: Updated user object
required: true
schema:
$ref: '#/definitions/User'
responses:
'400':
description: Invalid user supplied
'404':
description: User not found
delete:
tags:
- user
summary: Delete user
description: This can only be done by the logged in user.
operationId: deleteUser
produces:
- application/xml
- application/json
parameters:
- name: username
in: path
description: The name that needs to be deleted
required: true
type: string
responses:
'400':
description: Invalid username supplied
'404':
description: User not found
securityDefinitions:
petstore_auth:
type: oauth2
authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog'
flow: implicit
scopes:
'write:pets': modify pets in your account
'read:pets': read your pets
api_key:
type: apiKey
name: api_key
in: header
definitions:
Order:
title: Pet Order
description: An order for a pets from the pet store
type: object
properties:
id:
type: integer
format: int64
petId:
type: integer
format: int64
quantity:
type: integer
format: int32
shipDate:
type: string
format: date-time
status:
type: string
description: Order Status
enum:
- placed
- approved
- delivered
complete:
type: boolean
default: false
xml:
name: Order
Category:
title: Pet category
description: A category for a pet
type: object
properties:
id:
type: integer
format: int64
name:
type: string
xml:
name: Category
User:
title: a User
description: A User who is purchasing from the pet store
type: object
properties:
id:
type: integer
format: int64
username:
type: string
firstName:
type: string
lastName:
type: string
email:
type: string
password:
type: string
phone:
type: string
userStatus:
type: integer
format: int32
description: User Status
xml:
name: User
Tag:
title: Pet Tag
description: A tag for a pet
type: object
properties:
id:
type: integer
format: int64
name:
type: string
xml:
name: Tag
Pet:
title: a Pet
description: A pet for sale in the pet store
type: object
required:
- name
- photoUrls
properties:
id:
type: integer
format: int64
x-nullable: true
category:
$ref: '#/definitions/Category'
name:
type: string
example: doggie
x-nullable: true
photoUrls:
type: array
xml:
name: photoUrl
wrapped: true
items:
type: string
x-nullable: true
tags:
x-nullable: true
type: array
xml:
name: tag
wrapped: true
items:
$ref: '#/definitions/Tag'
status:
type: string
x-nullable: true
description: pet status in the store
enum:
- available
- pending
- sold
xml:
name: Pet
ApiResponse:
title: An uploaded response
description: Describes the result of uploading an image resource
type: object
properties:
code:
type: integer
format: int32
type:
type: string
message:
type: string

View File

@ -181,6 +181,7 @@ paths:
schema:
type: integer
format: int64
nullable: true
responses:
'405':
description: Invalid input
@ -200,6 +201,7 @@ paths:
status:
description: Updated status of the pet
type: string
nullable: true
delete:
tags:
- pet

View File

@ -33,6 +33,7 @@ import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.ExchangeStrategies;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Flux;
import java.util.Optional;
import java.io.BufferedReader;
import java.io.IOException;
@ -76,7 +77,7 @@ public class ApiClient {
}
private HttpHeaders defaultHeaders = new HttpHeaders();
private String basePath = "http://petstore.swagger.io:80/v2";
private final WebClient webClient;
@ -87,16 +88,22 @@ public class ApiClient {
public ApiClient() {
this.dateFormat = createDefaultDateFormat();
this.webClient = buildWebClient(new ObjectMapper(), this.dateFormat);
this.webClient = buildWebClient(new ObjectMapper(), dateFormat);
this.init();
}
public ApiClient(ObjectMapper mapper, DateFormat format) {
this(buildWebClient(mapper.copy(), format), format);
}
public ApiClient(WebClient webClient, ObjectMapper mapper, DateFormat format) {
this(Optional.ofNullable(webClient).orElseGet(() ->buildWebClient(mapper.copy(), format)), format);
}
private ApiClient(WebClient webClient, DateFormat format) {
this.webClient = webClient;
this.dateFormat = format;
this.init();
}
public DateFormat createDefaultDateFormat() {
@ -104,7 +111,7 @@ public class ApiClient {
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return dateFormat;
}
protected void init() {
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();
@ -133,7 +140,7 @@ public class ApiClient {
return webClient.build();
}
/**
* Get the current base path
* @return String the base path
@ -586,7 +593,7 @@ public class ApiClient {
auth.applyToParams(queryParams, headerParams);
}
}
private class ApiClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
private final Log log = LogFactory.getLog(ApiClientHttpRequestInterceptor.class);
@ -625,7 +632,7 @@ public class ApiClient {
builder.setLength(builder.length() - 1); // Get rid of trailing comma
return builder.toString();
}
private String bodyToString(InputStream body) throws IOException {
StringBuilder builder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8));

View File

@ -1 +1 @@
3.1.1-SNAPSHOT
3.2.3-SNAPSHOT

View File

@ -57,10 +57,10 @@ client = petstore_api.Client() # Client | client model
try:
# To test special tags
api_response = api_instance.test_special_tags(client)
api_response = api_instance.call_123_test_special_tags(client)
pprint(api_response)
except ApiException as e:
print("Exception when calling AnotherFakeApi->test_special_tags: %s\n" % e)
print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e)
```
@ -70,7 +70,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*AnotherFakeApi* | [**test_special_tags**](docs/AnotherFakeApi.md#test_special_tags) | **PATCH** /another-fake/dummy | To test special tags
*AnotherFakeApi* | [**call_123_test_special_tags**](docs/AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags
*FakeApi* | [**fake_outer_boolean_serialize**](docs/FakeApi.md#fake_outer_boolean_serialize) | **POST** /fake/outer/boolean |
*FakeApi* | [**fake_outer_composite_serialize**](docs/FakeApi.md#fake_outer_composite_serialize) | **POST** /fake/outer/composite |
*FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number |

View File

@ -4,15 +4,15 @@ All URIs are relative to *http://petstore.swagger.io:80/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**test_special_tags**](AnotherFakeApi.md#test_special_tags) | **PATCH** /another-fake/dummy | To test special tags
[**call_123_test_special_tags**](AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags
# **test_special_tags**
> Client test_special_tags(client)
# **call_123_test_special_tags**
> Client call_123_test_special_tags(client)
To test special tags
To test special tags
To test special tags and operation ID starting with number
### Example
```python
@ -28,10 +28,10 @@ client = petstore_api.Client() # Client | client model
try:
# To test special tags
api_response = api_instance.test_special_tags(client)
api_response = api_instance.call_123_test_special_tags(client)
pprint(api_response)
except ApiException as e:
print("Exception when calling AnotherFakeApi->test_special_tags: %s\n" % e)
print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e)
```
### Parameters

View File

@ -32,13 +32,13 @@ class AnotherFakeApi(object):
api_client = ApiClient()
self.api_client = api_client
def test_special_tags(self, client, **kwargs): # noqa: E501
def call_123_test_special_tags(self, client, **kwargs): # noqa: E501
"""To test special tags # noqa: E501
To test special tags # noqa: E501
To test special tags and operation ID starting with number # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.test_special_tags(client, async_req=True)
>>> thread = api.call_123_test_special_tags(client, async_req=True)
>>> result = thread.get()
:param async_req bool
@ -49,18 +49,18 @@ class AnotherFakeApi(object):
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.test_special_tags_with_http_info(client, **kwargs) # noqa: E501
return self.call_123_test_special_tags_with_http_info(client, **kwargs) # noqa: E501
else:
(data) = self.test_special_tags_with_http_info(client, **kwargs) # noqa: E501
(data) = self.call_123_test_special_tags_with_http_info(client, **kwargs) # noqa: E501
return data
def test_special_tags_with_http_info(self, client, **kwargs): # noqa: E501
def call_123_test_special_tags_with_http_info(self, client, **kwargs): # noqa: E501
"""To test special tags # noqa: E501
To test special tags # noqa: E501
To test special tags and operation ID starting with number # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.test_special_tags_with_http_info(client, async_req=True)
>>> thread = api.call_123_test_special_tags_with_http_info(client, async_req=True)
>>> result = thread.get()
:param async_req bool
@ -82,14 +82,14 @@ class AnotherFakeApi(object):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method test_special_tags" % key
" to method call_123_test_special_tags" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'client' is set
if ('client' not in local_var_params or
local_var_params['client'] is None):
raise ValueError("Missing the required parameter `client` when calling `test_special_tags`") # noqa: E501
raise ValueError("Missing the required parameter `client` when calling `call_123_test_special_tags`") # noqa: E501
collection_formats = {}

View File

@ -46,21 +46,24 @@ class RESTClientObject(object):
def __init__(self, configuration, pools_size=4, maxsize=4):
# maxsize is number of requests to host that are allowed in parallel
# ca_certs vs cert_file vs key_file
# http://stackoverflow.com/a/23957365/2985775
# ca_certs
if configuration.ssl_ca_cert:
ca_certs = configuration.ssl_ca_cert
if configuration.verify_ssl:
# ca_certs
if configuration.ssl_ca_cert:
ca_certs = configuration.ssl_ca_cert
else:
# if not set certificate file, use Mozilla's root certificates.
ca_certs = certifi.where()
ssl_context = ssl.create_default_context(cafile=ca_certs)
if configuration.cert_file:
ssl_context.load_cert_chain(
configuration.cert_file, keyfile=configuration.key_file
)
else:
# if not set certificate file, use Mozilla's root certificates.
ca_certs = certifi.where()
ssl_context = ssl.create_default_context(cafile=ca_certs)
if configuration.cert_file:
ssl_context.load_cert_chain(
configuration.cert_file, keyfile=configuration.key_file
)
ssl_context = None
connector = aiohttp.TCPConnector(
limit=maxsize,

View File

@ -1 +1 @@
3.1.1-SNAPSHOT
3.2.3-SNAPSHOT

View File

@ -57,10 +57,10 @@ client = petstore_api.Client() # Client | client model
try:
# To test special tags
api_response = api_instance.test_special_tags(client)
api_response = api_instance.call_123_test_special_tags(client)
pprint(api_response)
except ApiException as e:
print("Exception when calling AnotherFakeApi->test_special_tags: %s\n" % e)
print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e)
```
@ -70,7 +70,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*AnotherFakeApi* | [**test_special_tags**](docs/AnotherFakeApi.md#test_special_tags) | **PATCH** /another-fake/dummy | To test special tags
*AnotherFakeApi* | [**call_123_test_special_tags**](docs/AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags
*FakeApi* | [**fake_outer_boolean_serialize**](docs/FakeApi.md#fake_outer_boolean_serialize) | **POST** /fake/outer/boolean |
*FakeApi* | [**fake_outer_composite_serialize**](docs/FakeApi.md#fake_outer_composite_serialize) | **POST** /fake/outer/composite |
*FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number |

View File

@ -4,15 +4,15 @@ All URIs are relative to *http://petstore.swagger.io:80/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**test_special_tags**](AnotherFakeApi.md#test_special_tags) | **PATCH** /another-fake/dummy | To test special tags
[**call_123_test_special_tags**](AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags
# **test_special_tags**
> Client test_special_tags(client)
# **call_123_test_special_tags**
> Client call_123_test_special_tags(client)
To test special tags
To test special tags
To test special tags and operation ID starting with number
### Example
```python
@ -28,10 +28,10 @@ client = petstore_api.Client() # Client | client model
try:
# To test special tags
api_response = api_instance.test_special_tags(client)
api_response = api_instance.call_123_test_special_tags(client)
pprint(api_response)
except ApiException as e:
print("Exception when calling AnotherFakeApi->test_special_tags: %s\n" % e)
print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e)
```
### Parameters

View File

@ -32,13 +32,13 @@ class AnotherFakeApi(object):
api_client = ApiClient()
self.api_client = api_client
def test_special_tags(self, client, **kwargs): # noqa: E501
def call_123_test_special_tags(self, client, **kwargs): # noqa: E501
"""To test special tags # noqa: E501
To test special tags # noqa: E501
To test special tags and operation ID starting with number # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.test_special_tags(client, async_req=True)
>>> thread = api.call_123_test_special_tags(client, async_req=True)
>>> result = thread.get()
:param async_req bool
@ -49,18 +49,18 @@ class AnotherFakeApi(object):
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.test_special_tags_with_http_info(client, **kwargs) # noqa: E501
return self.call_123_test_special_tags_with_http_info(client, **kwargs) # noqa: E501
else:
(data) = self.test_special_tags_with_http_info(client, **kwargs) # noqa: E501
(data) = self.call_123_test_special_tags_with_http_info(client, **kwargs) # noqa: E501
return data
def test_special_tags_with_http_info(self, client, **kwargs): # noqa: E501
def call_123_test_special_tags_with_http_info(self, client, **kwargs): # noqa: E501
"""To test special tags # noqa: E501
To test special tags # noqa: E501
To test special tags and operation ID starting with number # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.test_special_tags_with_http_info(client, async_req=True)
>>> thread = api.call_123_test_special_tags_with_http_info(client, async_req=True)
>>> result = thread.get()
:param async_req bool
@ -82,14 +82,14 @@ class AnotherFakeApi(object):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method test_special_tags" % key
" to method call_123_test_special_tags" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'client' is set
if ('client' not in local_var_params or
local_var_params['client'] is None):
raise ValueError("Missing the required parameter `client` when calling `test_special_tags`") # noqa: E501
raise ValueError("Missing the required parameter `client` when calling `call_123_test_special_tags`") # noqa: E501
collection_formats = {}

View File

@ -1 +1 @@
3.2.0-SNAPSHOT
3.2.3-SNAPSHOT

View File

@ -57,10 +57,10 @@ client = petstore_api.Client() # Client | client model
try:
# To test special tags
api_response = api_instance.test_special_tags(client)
api_response = api_instance.call_123_test_special_tags(client)
pprint(api_response)
except ApiException as e:
print("Exception when calling AnotherFakeApi->test_special_tags: %s\n" % e)
print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e)
```
@ -70,7 +70,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*AnotherFakeApi* | [**test_special_tags**](docs/AnotherFakeApi.md#test_special_tags) | **PATCH** /another-fake/dummy | To test special tags
*AnotherFakeApi* | [**call_123_test_special_tags**](docs/AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags
*FakeApi* | [**fake_outer_boolean_serialize**](docs/FakeApi.md#fake_outer_boolean_serialize) | **POST** /fake/outer/boolean |
*FakeApi* | [**fake_outer_composite_serialize**](docs/FakeApi.md#fake_outer_composite_serialize) | **POST** /fake/outer/composite |
*FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number |

View File

@ -4,15 +4,15 @@ All URIs are relative to *http://petstore.swagger.io:80/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**test_special_tags**](AnotherFakeApi.md#test_special_tags) | **PATCH** /another-fake/dummy | To test special tags
[**call_123_test_special_tags**](AnotherFakeApi.md#call_123_test_special_tags) | **PATCH** /another-fake/dummy | To test special tags
# **test_special_tags**
> Client test_special_tags(client)
# **call_123_test_special_tags**
> Client call_123_test_special_tags(client)
To test special tags
To test special tags
To test special tags and operation ID starting with number
### Example
```python
@ -28,10 +28,10 @@ client = petstore_api.Client() # Client | client model
try:
# To test special tags
api_response = api_instance.test_special_tags(client)
api_response = api_instance.call_123_test_special_tags(client)
pprint(api_response)
except ApiException as e:
print("Exception when calling AnotherFakeApi->test_special_tags: %s\n" % e)
print("Exception when calling AnotherFakeApi->call_123_test_special_tags: %s\n" % e)
```
### Parameters

View File

@ -32,13 +32,13 @@ class AnotherFakeApi(object):
api_client = ApiClient()
self.api_client = api_client
def test_special_tags(self, client, **kwargs): # noqa: E501
def call_123_test_special_tags(self, client, **kwargs): # noqa: E501
"""To test special tags # noqa: E501
To test special tags # noqa: E501
To test special tags and operation ID starting with number # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.test_special_tags(client, async_req=True)
>>> thread = api.call_123_test_special_tags(client, async_req=True)
>>> result = thread.get()
:param async_req bool
@ -49,18 +49,18 @@ class AnotherFakeApi(object):
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.test_special_tags_with_http_info(client, **kwargs) # noqa: E501
return self.call_123_test_special_tags_with_http_info(client, **kwargs) # noqa: E501
else:
(data) = self.test_special_tags_with_http_info(client, **kwargs) # noqa: E501
(data) = self.call_123_test_special_tags_with_http_info(client, **kwargs) # noqa: E501
return data
def test_special_tags_with_http_info(self, client, **kwargs): # noqa: E501
def call_123_test_special_tags_with_http_info(self, client, **kwargs): # noqa: E501
"""To test special tags # noqa: E501
To test special tags # noqa: E501
To test special tags and operation ID starting with number # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.test_special_tags_with_http_info(client, async_req=True)
>>> thread = api.call_123_test_special_tags_with_http_info(client, async_req=True)
>>> result = thread.get()
:param async_req bool
@ -82,14 +82,14 @@ class AnotherFakeApi(object):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method test_special_tags" % key
" to method call_123_test_special_tags" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'client' is set
if ('client' not in local_var_params or
local_var_params['client'] is None):
raise ValueError("Missing the required parameter `client` when calling `test_special_tags`") # noqa: E501
raise ValueError("Missing the required parameter `client` when calling `call_123_test_special_tags`") # noqa: E501
collection_formats = {}

View File

@ -1,11 +1,11 @@
FROM alpine:latest AS build
RUN apk add --update \
RUN apk add --update \
cmake \
alpine-sdk \
openssl \
qt5-qtbase-dev \
qt5-qttools-dev
openssl \
qt5-qtbase-dev \
qt5-qttools-dev
WORKDIR /usr/server
ADD ./src ./src
@ -13,10 +13,10 @@ ADD ./CMakeLists.txt ./
RUN mkdir -p ./build
WORKDIR /usr/server/build
RUN cmake -DNODEBUG:STRING="ON" ..
RUN make
RUN make
FROM alpine:latest AS runtime
RUN apk add --update \
RUN apk add --update \
libgcc \
libstdc++ \
qt5-qtbase \

View File

@ -1,4 +1,4 @@
QHttpEngine
QHttpEngine
The MIT License (MIT)

View File

@ -1,8 +1,9 @@
# C++ Qt5 Server
## Qt5 HTTP Server based on the Qhttpengine
This server was generated by the [openapi-generator]
(https://openapi-generator.tech) project.
By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub.
-
This server was generated by the [openapi-generator](https://openapi-generator.tech) project.
By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub.
To see how to make this your own, look here:
@ -21,30 +22,36 @@ Simple set of classes for developing HTTP server applications in Qt.
To learn more about building and using the library, please visit this page:
https://ci.quickmediasolutions.com/job/qhttpengine-documentation/doxygen/
[Link](https://ci.quickmediasolutions.com/job/qhttpengine-documentation/doxygen)
### Viewing the code
You can view the code using an editor like Microsoft Visual Studio Code or you can
You can view the code using an editor like Microsoft Visual Studio Code or you can
Use QtCreator and browse for the root CMakeLists.txt and load it as a project
### Build with make
Install the tools [Linux/Debian]
```
```shell
sudo apt install cmake build-essential libssl-dev qtbase5-dev qtbase5-dev-tools git curl
```
To build, go to the `server` folder
```
make
```shell
make
```
To run the server
```
```shell
./build/src/cpp-qt5-server &
```
#### Invoke an API
```
```shell
curl -X GET http://localhost:8080/v2/store/inventory
curl -X POST http://localhost:8080/v2/store/order -H "Content-Type: application/json" -d "{ \"id\": 22, \"petId\": 1541, \"quantity\": 5, \"shipDate\": \"2018-06-16T18:31:43.870Z\", \"status\": \"placed\", \"complete\": \"true\" }"
curl -X GET http://localhost:8080/v2/pet/findByStatus
@ -52,38 +59,50 @@ curl -X GET http://localhost:8080/v2/store/inventory
```
### Run and build with docker
Building with docker multistage
If you dont have docker install [here](https://docs.docker.com/install)
Add yourself to the docker group
```
```shell
docker build --network=host -t cpp-qt5-server .
```
Running with docker
```
docker run --rm -it --name=server-container cpp-qt5-server
Running with docker
```shell
docker run --rm -it --name=server-container cpp-qt5-server
```
#### Invoking an API
Mind the IP here
```
```shell
curl -X GET http://172.17.0.2:8080/v2/store/inventory
curl -X POST http://172.17.0.2:8080/v2/store/order -H "Content-Type: application/json" -d "{ \"id\": 22, \"petId\": 1541, \"quantity\": 5, \"shipDate\": \"2018-06-16T18:31:43.870Z\", \"status\": \"placed\", \"complete\": \"true\" }"
```
use this command to get the container IP
```
```shell
docker inspect server-container | grep "IPAddress"
```
To exit from the command line
```
To exit from the command line
```shell
Ctrl + p + q
```
To stop container
```
```shell
docker stop <containername>
```
or to terminate and quit
```
```shell
Ctrl+C
```

View File

@ -12,7 +12,7 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -std=c++14 -Wall -Wno-unused-varia
if(${NODEBUG} STREQUAL "OFF")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pg -g3")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pg -g3")
else (${NODEBUG} STREQUAL "OFF")
else (${NODEBUG} STREQUAL "OFF")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -s -O3")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s -O3")
endif(${NODEBUG} STREQUAL "OFF")

View File

@ -24,270 +24,241 @@
namespace OpenAPI {
inline QHttpEngine::Socket::Method toQHttpEngineMethod(QString method){
if( method == QString("OPTIONS"))
return QHttpEngine::Socket::Method::OPTIONS;
if( method == QString("GET"))
return QHttpEngine::Socket::Method::GET;
if( method == QString("HEAD"))
return QHttpEngine::Socket::Method::HEAD;
if( method == QString("POST"))
return QHttpEngine::Socket::Method::POST;
if( method == QString("PUT"))
return QHttpEngine::Socket::Method::PUT;
if( method == QString("DELETE"))
return QHttpEngine::Socket::Method::DELETE;
if( method == QString("TRACE"))
return QHttpEngine::Socket::Method::TRACE;
if( method == QString("CONNECT"))
return QHttpEngine::Socket::Method::CONNECT;
return static_cast<QHttpEngine::Socket::Method>(-1);
OAIApiRouter::OAIApiRouter() {
createApiHandlers();
}
ApiRouter::ApiRouter() {
OAIPetApiApiHandler = new OAIPetApiHandler();
OAIStoreApiApiHandler = new OAIStoreApiHandler();
OAIUserApiApiHandler = new OAIUserApiHandler();
}
ApiRouter::~ApiRouter(){
qDebug() << "~ApiRouter()";
OAIApiRouter::~OAIApiRouter(){
qDebug() << "~ApiRouter()";
delete OAIPetApiApiHandler;
delete OAIStoreApiApiHandler;
delete OAIUserApiApiHandler;
}
void ApiRouter::setUpRoutes() {
void OAIApiRouter::createApiHandlers() {
OAIPetApiApiHandler = new OAIPetApiHandler();
OAIStoreApiApiHandler = new OAIStoreApiHandler();
OAIUserApiApiHandler = new OAIUserApiHandler();
}
void OAIApiRouter::setUpRoutes() {
Routes.insert("/v2/pet",[this](QHttpEngine::Socket *socket) {
if(toQHttpEngineMethod("POST") == socket->method()){
Routes.insert(QString("%1 %2").arg("POST").arg("/v2/pet").toLower(), [this](QHttpEngine::Socket *socket) {
auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler);
reqObj->addPetRequest();
}
});
Routes.insert("/v2/pet/findByStatus",[this](QHttpEngine::Socket *socket) {
if(toQHttpEngineMethod("GET") == socket->method()){
Routes.insert(QString("%1 %2").arg("GET").arg("/v2/pet/findByStatus").toLower(), [this](QHttpEngine::Socket *socket) {
auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler);
reqObj->findPetsByStatusRequest();
}
});
Routes.insert("/v2/pet/findByTags",[this](QHttpEngine::Socket *socket) {
if(toQHttpEngineMethod("GET") == socket->method()){
Routes.insert(QString("%1 %2").arg("GET").arg("/v2/pet/findByTags").toLower(), [this](QHttpEngine::Socket *socket) {
auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler);
reqObj->findPetsByTagsRequest();
}
});
Routes.insert("/v2/pet",[this](QHttpEngine::Socket *socket) {
if(toQHttpEngineMethod("PUT") == socket->method()){
Routes.insert(QString("%1 %2").arg("PUT").arg("/v2/pet").toLower(), [this](QHttpEngine::Socket *socket) {
auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler);
reqObj->updatePetRequest();
}
});
Routes.insert("/v2/store/inventory",[this](QHttpEngine::Socket *socket) {
if(toQHttpEngineMethod("GET") == socket->method()){
Routes.insert(QString("%1 %2").arg("GET").arg("/v2/store/inventory").toLower(), [this](QHttpEngine::Socket *socket) {
auto reqObj = new OAIStoreApiRequest(socket, OAIStoreApiApiHandler);
reqObj->getInventoryRequest();
}
});
Routes.insert("/v2/store/order",[this](QHttpEngine::Socket *socket) {
if(toQHttpEngineMethod("POST") == socket->method()){
Routes.insert(QString("%1 %2").arg("POST").arg("/v2/store/order").toLower(), [this](QHttpEngine::Socket *socket) {
auto reqObj = new OAIStoreApiRequest(socket, OAIStoreApiApiHandler);
reqObj->placeOrderRequest();
}
});
Routes.insert("/v2/user",[this](QHttpEngine::Socket *socket) {
if(toQHttpEngineMethod("POST") == socket->method()){
Routes.insert(QString("%1 %2").arg("POST").arg("/v2/user").toLower(), [this](QHttpEngine::Socket *socket) {
auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler);
reqObj->createUserRequest();
}
});
Routes.insert("/v2/user/createWithArray",[this](QHttpEngine::Socket *socket) {
if(toQHttpEngineMethod("POST") == socket->method()){
Routes.insert(QString("%1 %2").arg("POST").arg("/v2/user/createWithArray").toLower(), [this](QHttpEngine::Socket *socket) {
auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler);
reqObj->createUsersWithArrayInputRequest();
}
});
Routes.insert("/v2/user/createWithList",[this](QHttpEngine::Socket *socket) {
if(toQHttpEngineMethod("POST") == socket->method()){
Routes.insert(QString("%1 %2").arg("POST").arg("/v2/user/createWithList").toLower(), [this](QHttpEngine::Socket *socket) {
auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler);
reqObj->createUsersWithListInputRequest();
}
});
Routes.insert("/v2/user/login",[this](QHttpEngine::Socket *socket) {
if(toQHttpEngineMethod("GET") == socket->method()){
Routes.insert(QString("%1 %2").arg("GET").arg("/v2/user/login").toLower(), [this](QHttpEngine::Socket *socket) {
auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler);
reqObj->loginUserRequest();
}
});
Routes.insert("/v2/user/logout",[this](QHttpEngine::Socket *socket) {
if(toQHttpEngineMethod("GET") == socket->method()){
Routes.insert(QString("%1 %2").arg("GET").arg("/v2/user/logout").toLower(), [this](QHttpEngine::Socket *socket) {
auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler);
reqObj->logoutUserRequest();
}
});
});
}
void ApiRouter::processRequest(QHttpEngine::Socket *socket){
if (Routes.contains(socket->path())) {
for(auto endpoints : Routes.values(socket->path())) {
endpoints.operator()(socket);
}
} else
{
{
QString completePath("/v2/pet/{petId}");
QString pet_idPathParam("{");
pet_idPathParam.append("petId").append("}");
completePath.replace("/", "\\/"); // replace '/' with '\/' for regex
completePath.replace(pet_idPathParam, "([^\\/]*?)"); // match anything but '/''
completePath.append("$"); // End of string
QRegularExpression re(completePath, QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatch match = re.match(socket->path());
if ((toQHttpEngineMethod("DELETE") == socket->method()) && match.hasMatch() ) {
QString pathparam = match.captured(1);
auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler);
reqObj->deletePetRequest(pathparam);;
return;
}
}
{
QString completePath("/v2/pet/{petId}");
QString pet_idPathParam("{");
pet_idPathParam.append("petId").append("}");
completePath.replace("/", "\\/"); // replace '/' with '\/' for regex
completePath.replace(pet_idPathParam, "([^\\/]*?)"); // match anything but '/''
completePath.append("$"); // End of string
QRegularExpression re(completePath, QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatch match = re.match(socket->path());
if ((toQHttpEngineMethod("GET") == socket->method()) && match.hasMatch() ) {
QString pathparam = match.captured(1);
auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler);
reqObj->getPetByIdRequest(pathparam);;
return;
}
}
{
QString completePath("/v2/pet/{petId}");
QString pet_idPathParam("{");
pet_idPathParam.append("petId").append("}");
completePath.replace("/", "\\/"); // replace '/' with '\/' for regex
completePath.replace(pet_idPathParam, "([^\\/]*?)"); // match anything but '/''
completePath.append("$"); // End of string
QRegularExpression re(completePath, QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatch match = re.match(socket->path());
if ((toQHttpEngineMethod("POST") == socket->method()) && match.hasMatch() ) {
QString pathparam = match.captured(1);
auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler);
reqObj->updatePetWithFormRequest(pathparam);;
return;
}
}
{
QString completePath("/v2/pet/{petId}/uploadImage");
QString pet_idPathParam("{");
pet_idPathParam.append("petId").append("}");
completePath.replace("/", "\\/"); // replace '/' with '\/' for regex
completePath.replace(pet_idPathParam, "([^\\/]*?)"); // match anything but '/''
completePath.append("$"); // End of string
QRegularExpression re(completePath, QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatch match = re.match(socket->path());
if ((toQHttpEngineMethod("POST") == socket->method()) && match.hasMatch() ) {
QString pathparam = match.captured(1);
auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler);
reqObj->uploadFileRequest(pathparam);;
return;
}
}
{
QString completePath("/v2/store/order/{orderId}");
QString order_idPathParam("{");
order_idPathParam.append("orderId").append("}");
completePath.replace("/", "\\/"); // replace '/' with '\/' for regex
completePath.replace(order_idPathParam, "([^\\/]*?)"); // match anything but '/''
completePath.append("$"); // End of string
QRegularExpression re(completePath, QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatch match = re.match(socket->path());
if ((toQHttpEngineMethod("DELETE") == socket->method()) && match.hasMatch() ) {
QString pathparam = match.captured(1);
auto reqObj = new OAIStoreApiRequest(socket, OAIStoreApiApiHandler);
reqObj->deleteOrderRequest(pathparam);;
return;
}
}
{
QString completePath("/v2/store/order/{orderId}");
QString order_idPathParam("{");
order_idPathParam.append("orderId").append("}");
completePath.replace("/", "\\/"); // replace '/' with '\/' for regex
completePath.replace(order_idPathParam, "([^\\/]*?)"); // match anything but '/''
completePath.append("$"); // End of string
QRegularExpression re(completePath, QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatch match = re.match(socket->path());
if ((toQHttpEngineMethod("GET") == socket->method()) && match.hasMatch() ) {
QString pathparam = match.captured(1);
auto reqObj = new OAIStoreApiRequest(socket, OAIStoreApiApiHandler);
reqObj->getOrderByIdRequest(pathparam);;
return;
}
}
{
QString completePath("/v2/user/{username}");
QString usernamePathParam("{");
usernamePathParam.append("username").append("}");
completePath.replace("/", "\\/"); // replace '/' with '\/' for regex
completePath.replace(usernamePathParam, "([^\\/]*?)"); // match anything but '/''
completePath.append("$"); // End of string
QRegularExpression re(completePath, QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatch match = re.match(socket->path());
if ((toQHttpEngineMethod("DELETE") == socket->method()) && match.hasMatch() ) {
QString pathparam = match.captured(1);
auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler);
reqObj->deleteUserRequest(pathparam);;
return;
}
}
{
QString completePath("/v2/user/{username}");
QString usernamePathParam("{");
usernamePathParam.append("username").append("}");
completePath.replace("/", "\\/"); // replace '/' with '\/' for regex
completePath.replace(usernamePathParam, "([^\\/]*?)"); // match anything but '/''
completePath.append("$"); // End of string
QRegularExpression re(completePath, QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatch match = re.match(socket->path());
if ((toQHttpEngineMethod("GET") == socket->method()) && match.hasMatch() ) {
QString pathparam = match.captured(1);
auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler);
reqObj->getUserByNameRequest(pathparam);;
return;
}
}
{
QString completePath("/v2/user/{username}");
QString usernamePathParam("{");
usernamePathParam.append("username").append("}");
completePath.replace("/", "\\/"); // replace '/' with '\/' for regex
completePath.replace(usernamePathParam, "([^\\/]*?)"); // match anything but '/''
completePath.append("$"); // End of string
QRegularExpression re(completePath, QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatch match = re.match(socket->path());
if ((toQHttpEngineMethod("PUT") == socket->method()) && match.hasMatch() ) {
QString pathparam = match.captured(1);
auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler);
reqObj->updateUserRequest(pathparam);;
return;
}
}
void OAIApiRouter::processRequest(QHttpEngine::Socket *socket){
if( handleRequest(socket) ){
return;
}
if( handleRequestAndExtractPathParam(socket) ){
return;
}
socket->setStatusCode(QHttpEngine::Socket::NotFound);
if(socket->isOpen()){
socket->writeHeaders();
socket->close();
}
return;
}
bool OAIApiRouter::handleRequest(QHttpEngine::Socket *socket){
auto reqPath = QString("%1 %2").arg(fromQHttpEngineMethod(socket->method())).arg(socket->path()).toLower();
if ( Routes.contains(reqPath) ) {
Routes.value(reqPath).operator()(socket);
return true;
}
return false;
}
bool OAIApiRouter::handleRequestAndExtractPathParam(QHttpEngine::Socket *socket){
auto reqPath = QString("%1 %2").arg(fromQHttpEngineMethod(socket->method())).arg(socket->path()).toLower();
{
auto completePath = QString("%1 %2").arg("DELETE").arg("/v2/pet/{petId}").toLower();
if ( reqPath.startsWith(completePath.leftRef( completePath.indexOf(QString("/{")))) ) {
QRegularExpression parExpr( R"(\{([^\/\\s]+)\})" );
completePath.replace( parExpr, R"((?<\1>[^\/\s]+))" );
completePath.append("[\\/]?$");
QRegularExpression pathExpr( completePath );
QRegularExpressionMatch match = pathExpr.match( reqPath );
if ( match.hasMatch() ){
QString petId = match.captured(QString("petId").toLower());
auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler);
reqObj->deletePetRequest(petId);
return true;
}
}
}
{
auto completePath = QString("%1 %2").arg("GET").arg("/v2/pet/{petId}").toLower();
if ( reqPath.startsWith(completePath.leftRef( completePath.indexOf(QString("/{")))) ) {
QRegularExpression parExpr( R"(\{([^\/\\s]+)\})" );
completePath.replace( parExpr, R"((?<\1>[^\/\s]+))" );
completePath.append("[\\/]?$");
QRegularExpression pathExpr( completePath );
QRegularExpressionMatch match = pathExpr.match( reqPath );
if ( match.hasMatch() ){
QString petId = match.captured(QString("petId").toLower());
auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler);
reqObj->getPetByIdRequest(petId);
return true;
}
}
}
{
auto completePath = QString("%1 %2").arg("POST").arg("/v2/pet/{petId}").toLower();
if ( reqPath.startsWith(completePath.leftRef( completePath.indexOf(QString("/{")))) ) {
QRegularExpression parExpr( R"(\{([^\/\\s]+)\})" );
completePath.replace( parExpr, R"((?<\1>[^\/\s]+))" );
completePath.append("[\\/]?$");
QRegularExpression pathExpr( completePath );
QRegularExpressionMatch match = pathExpr.match( reqPath );
if ( match.hasMatch() ){
QString petId = match.captured(QString("petId").toLower());
auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler);
reqObj->updatePetWithFormRequest(petId);
return true;
}
}
}
{
auto completePath = QString("%1 %2").arg("POST").arg("/v2/pet/{petId}/uploadImage").toLower();
if ( reqPath.startsWith(completePath.leftRef( completePath.indexOf(QString("/{")))) ) {
QRegularExpression parExpr( R"(\{([^\/\\s]+)\})" );
completePath.replace( parExpr, R"((?<\1>[^\/\s]+))" );
completePath.append("[\\/]?$");
QRegularExpression pathExpr( completePath );
QRegularExpressionMatch match = pathExpr.match( reqPath );
if ( match.hasMatch() ){
QString petId = match.captured(QString("petId").toLower());
auto reqObj = new OAIPetApiRequest(socket, OAIPetApiApiHandler);
reqObj->uploadFileRequest(petId);
return true;
}
}
}
{
auto completePath = QString("%1 %2").arg("DELETE").arg("/v2/store/order/{orderId}").toLower();
if ( reqPath.startsWith(completePath.leftRef( completePath.indexOf(QString("/{")))) ) {
QRegularExpression parExpr( R"(\{([^\/\\s]+)\})" );
completePath.replace( parExpr, R"((?<\1>[^\/\s]+))" );
completePath.append("[\\/]?$");
QRegularExpression pathExpr( completePath );
QRegularExpressionMatch match = pathExpr.match( reqPath );
if ( match.hasMatch() ){
QString orderId = match.captured(QString("orderId").toLower());
auto reqObj = new OAIStoreApiRequest(socket, OAIStoreApiApiHandler);
reqObj->deleteOrderRequest(orderId);
return true;
}
}
}
{
auto completePath = QString("%1 %2").arg("GET").arg("/v2/store/order/{orderId}").toLower();
if ( reqPath.startsWith(completePath.leftRef( completePath.indexOf(QString("/{")))) ) {
QRegularExpression parExpr( R"(\{([^\/\\s]+)\})" );
completePath.replace( parExpr, R"((?<\1>[^\/\s]+))" );
completePath.append("[\\/]?$");
QRegularExpression pathExpr( completePath );
QRegularExpressionMatch match = pathExpr.match( reqPath );
if ( match.hasMatch() ){
QString orderId = match.captured(QString("orderId").toLower());
auto reqObj = new OAIStoreApiRequest(socket, OAIStoreApiApiHandler);
reqObj->getOrderByIdRequest(orderId);
return true;
}
}
}
{
auto completePath = QString("%1 %2").arg("DELETE").arg("/v2/user/{username}").toLower();
if ( reqPath.startsWith(completePath.leftRef( completePath.indexOf(QString("/{")))) ) {
QRegularExpression parExpr( R"(\{([^\/\\s]+)\})" );
completePath.replace( parExpr, R"((?<\1>[^\/\s]+))" );
completePath.append("[\\/]?$");
QRegularExpression pathExpr( completePath );
QRegularExpressionMatch match = pathExpr.match( reqPath );
if ( match.hasMatch() ){
QString username = match.captured(QString("username").toLower());
auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler);
reqObj->deleteUserRequest(username);
return true;
}
}
}
{
auto completePath = QString("%1 %2").arg("GET").arg("/v2/user/{username}").toLower();
if ( reqPath.startsWith(completePath.leftRef( completePath.indexOf(QString("/{")))) ) {
QRegularExpression parExpr( R"(\{([^\/\\s]+)\})" );
completePath.replace( parExpr, R"((?<\1>[^\/\s]+))" );
completePath.append("[\\/]?$");
QRegularExpression pathExpr( completePath );
QRegularExpressionMatch match = pathExpr.match( reqPath );
if ( match.hasMatch() ){
QString username = match.captured(QString("username").toLower());
auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler);
reqObj->getUserByNameRequest(username);
return true;
}
}
}
{
auto completePath = QString("%1 %2").arg("PUT").arg("/v2/user/{username}").toLower();
if ( reqPath.startsWith(completePath.leftRef( completePath.indexOf(QString("/{")))) ) {
QRegularExpression parExpr( R"(\{([^\/\\s]+)\})" );
completePath.replace( parExpr, R"((?<\1>[^\/\s]+))" );
completePath.append("[\\/]?$");
QRegularExpression pathExpr( completePath );
QRegularExpressionMatch match = pathExpr.match( reqPath );
if ( match.hasMatch() ){
QString username = match.captured(QString("username").toLower());
auto reqObj = new OAIUserApiRequest(socket, OAIUserApiApiHandler);
reqObj->updateUserRequest(username);
return true;
}
}
}
return false;
}
}

View File

@ -30,7 +30,7 @@
namespace OpenAPI {
class RequestHandler : public QHttpEngine::QObjectHandler
class OAIApiRequestHandler : public QHttpEngine::QObjectHandler
{
Q_OBJECT
signals:
@ -43,21 +43,53 @@ protected:
}
};
class ApiRouter : public QObject
class OAIApiRouter : public QObject
{
Q_OBJECT
public:
ApiRouter();
virtual ~ApiRouter();
OAIApiRouter();
virtual ~OAIApiRouter();
void setUpRoutes();
void processRequest(QHttpEngine::Socket *socket);
private:
QMultiMap<QString, std::function<void(QHttpEngine::Socket *)>> Routes;
QMap<QString, std::function<void(QHttpEngine::Socket *)>> Routes;
QMultiMap<QString, std::function<void(QHttpEngine::Socket *)>> RoutesWithPathParam;
bool handleRequest(QHttpEngine::Socket *socket);
bool handleRequestAndExtractPathParam(QHttpEngine::Socket *socket);
OAIPetApiHandler *OAIPetApiApiHandler;
OAIStoreApiHandler *OAIStoreApiApiHandler;
OAIUserApiHandler *OAIUserApiApiHandler;
OAIUserApiHandler *OAIUserApiApiHandler;
protected:
// override this method to provide custom class derived from ApiHandler classes
virtual void createApiHandlers();
private :
inline QString fromQHttpEngineMethod(QHttpEngine::Socket::Method method){
switch( method ){
case QHttpEngine::Socket::Method::OPTIONS:
return QStringLiteral("OPTIONS");
case QHttpEngine::Socket::Method::GET:
return QStringLiteral("GET");
case QHttpEngine::Socket::Method::HEAD:
return QStringLiteral("HEAD");
case QHttpEngine::Socket::Method::POST:
return QStringLiteral("POST");
case QHttpEngine::Socket::Method::PUT:
return QStringLiteral("PUT");
case QHttpEngine::Socket::Method::DELETE:
return QStringLiteral("DELETE");
case QHttpEngine::Socket::Method::TRACE:
return QStringLiteral("TRACE");
case QHttpEngine::Socket::Method::CONNECT:
return QStringLiteral("CONNECT");
}
return QStringLiteral("");
}
};

View File

@ -19,43 +19,43 @@
#include <QStringList>
#include <QSharedPointer>
#include <QObject>
#ifdef __linux__
#ifdef __linux__
#include <signal.h>
#include <unistd.h>
#endif
#endif
#include <qhttpengine/server.h>
#include "OAIApiRouter.h"
#ifdef __linux__
#ifdef __linux__
void catchUnixSignals(QList<int> quitSignals) {
auto handler = [](int sig) -> void {
// blocking and not aysnc-signal-safe func are valid
qDebug() << "\nquit the application by signal " << sig;
QCoreApplication::quit();
};
sigset_t blocking_mask;
sigemptyset(&blocking_mask);
for (auto sig : quitSignals)
sigaddset(&blocking_mask, sig);
struct sigaction sa;
sa.sa_handler = handler;
sa.sa_mask = blocking_mask;
sa.sa_flags = 0;
for (auto sig : quitSignals)
sigset_t blocking_mask;
sigemptyset(&blocking_mask);
for (auto sig : quitSignals)
sigaddset(&blocking_mask, sig);
struct sigaction sa;
sa.sa_handler = handler;
sa.sa_mask = blocking_mask;
sa.sa_flags = 0;
for (auto sig : quitSignals)
sigaction(sig, &sa, nullptr);
}
#endif
#endif
int main(int argc, char * argv[])
{
QCoreApplication a(argc, argv);
#ifdef __linux__
#ifdef __linux__
QList<int> sigs({SIGQUIT, SIGINT, SIGTERM, SIGHUP});
catchUnixSignals(sigs);
#endif
#endif
// Build the command-line options
QCommandLineParser parser;
QCommandLineOption addressOption(
@ -80,11 +80,11 @@ int main(int argc, char * argv[])
// Obtain the values
QHostAddress address = QHostAddress(parser.value(addressOption));
quint16 port = static_cast<quint16>(parser.value(portOption).toInt());
QSharedPointer<OpenAPI::RequestHandler> handler(new OpenAPI::RequestHandler());
OpenAPI::ApiRouter router;
QSharedPointer<OpenAPI::OAIApiRequestHandler> handler(new OpenAPI::OAIApiRequestHandler());
OpenAPI::OAIApiRouter router;
router.setUpRoutes();
QObject::connect(handler.data(), &OpenAPI::RequestHandler::requestReceived, [&](QHttpEngine::Socket *socket) {
QObject::connect(handler.data(), &OpenAPI::OAIApiRequestHandler::requestReceived, [&](QHttpEngine::Socket *socket) {
router.processRequest(socket);
});
@ -95,6 +95,6 @@ int main(int argc, char * argv[])
qCritical("Unable to listen on the specified port.");
return 1;
}
return a.exec();
}

View File

@ -31,7 +31,7 @@ OAIApiResponse::OAIApiResponse() {
}
OAIApiResponse::~OAIApiResponse() {
}
void

View File

@ -31,7 +31,7 @@ OAICategory::OAICategory() {
}
OAICategory::~OAICategory() {
}
void

View File

@ -134,7 +134,7 @@ namespace OpenAPI {
for(auto itemkey : varmap.keys() ){
T itemVal;
fromJsonValue(itemVal, QJsonValue::fromVariant(varmap.value(itemkey)));
val.insert(itemkey, val);
val.insert(itemkey, itemVal);
}
}
return;

View File

@ -21,9 +21,9 @@ namespace OpenAPI {
class OAIObject {
public:
virtual ~OAIObject(){
}
virtual QJsonObject asJsonObject() const {
return jObj;
}

View File

@ -31,7 +31,7 @@ OAIOrder::OAIOrder() {
}
OAIOrder::~OAIOrder() {
}
void

View File

@ -31,7 +31,7 @@ OAIPet::OAIPet() {
}
OAIPet::~OAIPet() {
}
void

View File

@ -31,7 +31,7 @@ OAITag::OAITag() {
}
OAITag::~OAITag() {
}
void

View File

@ -31,7 +31,7 @@ OAIUser::OAIUser() {
}
OAIUser::~OAIUser() {
}
void

View File

@ -25,7 +25,7 @@ OAIPetApiRequest::OAIPetApiRequest(QHttpEngine::Socket *s, OAIPetApiHandler* hdl
auto headers = s->headers();
for(auto itr = headers.begin(); itr != headers.end(); itr++) {
requestHeaders.insert(QString(itr.key()), QString(itr.value()));
}
}
}
OAIPetApiRequest::~OAIPetApiRequest(){
@ -33,7 +33,7 @@ OAIPetApiRequest::~OAIPetApiRequest(){
qDebug() << "OAIPetApiRequest::~OAIPetApiRequest()";
}
QMap<QString, QString>
QMap<QString, QString>
OAIPetApiRequest::getRequestHeaders() const {
return requestHeaders;
}
@ -53,7 +53,7 @@ QHttpEngine::Socket* OAIPetApiRequest::getRawSocket(){
void OAIPetApiRequest::addPetRequest(){
qDebug() << "/v2/pet";
connect(this, &OAIPetApiRequest::addPet, handler, &OAIPetApiHandler::addPet);
QJsonDocument doc;
@ -63,14 +63,14 @@ void OAIPetApiRequest::addPetRequest(){
::OpenAPI::fromJsonValue(oai_pet, obj);
emit addPet( oai_pet);
emit addPet(oai_pet);
}
void OAIPetApiRequest::deletePetRequest(const QString& pet_idstr){
qDebug() << "/v2/pet/{petId}";
connect(this, &OAIPetApiRequest::deletePet, handler, &OAIPetApiHandler::deletePet);
qint64 pet_id;
fromStringValue(pet_idstr, pet_id);
@ -81,59 +81,59 @@ void OAIPetApiRequest::deletePetRequest(const QString& pet_idstr){
}
emit deletePet( pet_id, api_key);
emit deletePet(pet_id, api_key);
}
void OAIPetApiRequest::findPetsByStatusRequest(){
qDebug() << "/v2/pet/findByStatus";
connect(this, &OAIPetApiRequest::findPetsByStatus, handler, &OAIPetApiHandler::findPetsByStatus);
QList<QString> status;
QList<QString> status;
if(socket->queryString().keys().contains("status")){
fromStringValue(socket->queryString().values("status"), status);
}
emit findPetsByStatus( status);
emit findPetsByStatus(status);
}
void OAIPetApiRequest::findPetsByTagsRequest(){
qDebug() << "/v2/pet/findByTags";
connect(this, &OAIPetApiRequest::findPetsByTags, handler, &OAIPetApiHandler::findPetsByTags);
QList<QString> tags;
QList<QString> tags;
if(socket->queryString().keys().contains("tags")){
fromStringValue(socket->queryString().values("tags"), tags);
}
emit findPetsByTags( tags);
emit findPetsByTags(tags);
}
void OAIPetApiRequest::getPetByIdRequest(const QString& pet_idstr){
qDebug() << "/v2/pet/{petId}";
connect(this, &OAIPetApiRequest::getPetById, handler, &OAIPetApiHandler::getPetById);
qint64 pet_id;
fromStringValue(pet_idstr, pet_id);
emit getPetById( pet_id);
emit getPetById(pet_id);
}
void OAIPetApiRequest::updatePetRequest(){
qDebug() << "/v2/pet";
connect(this, &OAIPetApiRequest::updatePet, handler, &OAIPetApiHandler::updatePet);
QJsonDocument doc;
@ -143,14 +143,14 @@ void OAIPetApiRequest::updatePetRequest(){
::OpenAPI::fromJsonValue(oai_pet, obj);
emit updatePet( oai_pet);
emit updatePet(oai_pet);
}
void OAIPetApiRequest::updatePetWithFormRequest(const QString& pet_idstr){
qDebug() << "/v2/pet/{petId}";
connect(this, &OAIPetApiRequest::updatePetWithForm, handler, &OAIPetApiHandler::updatePetWithForm);
qint64 pet_id;
fromStringValue(pet_idstr, pet_id);
@ -158,14 +158,14 @@ void OAIPetApiRequest::updatePetWithFormRequest(const QString& pet_idstr){
QString name;
QString status;
emit updatePetWithForm( pet_id, name, status);
emit updatePetWithForm(pet_id, name, status);
}
void OAIPetApiRequest::uploadFileRequest(const QString& pet_idstr){
qDebug() << "/v2/pet/{petId}/uploadImage";
connect(this, &OAIPetApiRequest::uploadFile, handler, &OAIPetApiHandler::uploadFile);
qint64 pet_id;
fromStringValue(pet_idstr, pet_id);
@ -173,13 +173,13 @@ void OAIPetApiRequest::uploadFileRequest(const QString& pet_idstr){
QString additional_metadata;
QIODevice* file;
emit uploadFile( pet_id, additional_metadata, file);
emit uploadFile(pet_id, additional_metadata, file);
}
void OAIPetApiRequest::addPetResponse(){
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::OK);
if(socket->isOpen()){
socket->close();
@ -187,7 +187,7 @@ void OAIPetApiRequest::addPetResponse(){
}
void OAIPetApiRequest::deletePetResponse(){
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::OK);
if(socket->isOpen()){
socket->close();
@ -222,7 +222,7 @@ void OAIPetApiRequest::getPetByIdResponse(const OAIPet& res){
}
void OAIPetApiRequest::updatePetResponse(){
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::OK);
if(socket->isOpen()){
socket->close();
@ -230,7 +230,7 @@ void OAIPetApiRequest::updatePetResponse(){
}
void OAIPetApiRequest::updatePetWithFormResponse(){
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::OK);
if(socket->isOpen()){
socket->close();
@ -249,7 +249,7 @@ void OAIPetApiRequest::uploadFileResponse(const OAIApiResponse& res){
void OAIPetApiRequest::addPetError(QNetworkReply::NetworkError error_type, QString& error_str){
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::NotFound);
socket->write(error_str.toUtf8());
if(socket->isOpen()){
@ -259,7 +259,7 @@ void OAIPetApiRequest::addPetError(QNetworkReply::NetworkError error_type, QStri
void OAIPetApiRequest::deletePetError(QNetworkReply::NetworkError error_type, QString& error_str){
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::NotFound);
socket->write(error_str.toUtf8());
if(socket->isOpen()){
@ -302,7 +302,7 @@ void OAIPetApiRequest::getPetByIdError(const OAIPet& res, QNetworkReply::Network
void OAIPetApiRequest::updatePetError(QNetworkReply::NetworkError error_type, QString& error_str){
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::NotFound);
socket->write(error_str.toUtf8());
if(socket->isOpen()){
@ -312,7 +312,7 @@ void OAIPetApiRequest::updatePetError(QNetworkReply::NetworkError error_type, QS
void OAIPetApiRequest::updatePetWithFormError(QNetworkReply::NetworkError error_type, QString& error_str){
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::NotFound);
socket->write(error_str.toUtf8());
if(socket->isOpen()){
@ -336,7 +336,7 @@ void OAIPetApiRequest::sendCustomResponse(QByteArray & res, QNetworkReply::Netwo
Q_UNUSED(res); // TODO
Q_UNUSED(error_type); // TODO
}
void OAIPetApiRequest::sendCustomResponse(QIODevice *res, QNetworkReply::NetworkError error_type){
Q_UNUSED(res); // TODO
Q_UNUSED(error_type); // TODO

View File

@ -31,7 +31,7 @@ namespace OpenAPI {
class OAIPetApiRequest : public QObject
{
Q_OBJECT
public:
OAIPetApiRequest(QHttpEngine::Socket *s, OAIPetApiHandler* handler);
virtual ~OAIPetApiRequest();
@ -99,7 +99,7 @@ private:
resHeaders.insert(itr.key().toUtf8(), itr.value().toUtf8());
}
socket->setHeaders(resHeaders);
socket->writeHeaders();
socket->writeHeaders();
}
};

View File

@ -25,7 +25,7 @@ OAIStoreApiRequest::OAIStoreApiRequest(QHttpEngine::Socket *s, OAIStoreApiHandle
auto headers = s->headers();
for(auto itr = headers.begin(); itr != headers.end(); itr++) {
requestHeaders.insert(QString(itr.key()), QString(itr.value()));
}
}
}
OAIStoreApiRequest::~OAIStoreApiRequest(){
@ -33,7 +33,7 @@ OAIStoreApiRequest::~OAIStoreApiRequest(){
qDebug() << "OAIStoreApiRequest::~OAIStoreApiRequest()";
}
QMap<QString, QString>
QMap<QString, QString>
OAIStoreApiRequest::getRequestHeaders() const {
return requestHeaders;
}
@ -53,20 +53,20 @@ QHttpEngine::Socket* OAIStoreApiRequest::getRawSocket(){
void OAIStoreApiRequest::deleteOrderRequest(const QString& order_idstr){
qDebug() << "/v2/store/order/{orderId}";
connect(this, &OAIStoreApiRequest::deleteOrder, handler, &OAIStoreApiHandler::deleteOrder);
QString order_id;
fromStringValue(order_idstr, order_id);
emit deleteOrder( order_id);
emit deleteOrder(order_id);
}
void OAIStoreApiRequest::getInventoryRequest(){
qDebug() << "/v2/store/inventory";
connect(this, &OAIStoreApiRequest::getInventory, handler, &OAIStoreApiHandler::getInventory);
@ -77,20 +77,20 @@ void OAIStoreApiRequest::getInventoryRequest(){
void OAIStoreApiRequest::getOrderByIdRequest(const QString& order_idstr){
qDebug() << "/v2/store/order/{orderId}";
connect(this, &OAIStoreApiRequest::getOrderById, handler, &OAIStoreApiHandler::getOrderById);
qint64 order_id;
fromStringValue(order_idstr, order_id);
emit getOrderById( order_id);
emit getOrderById(order_id);
}
void OAIStoreApiRequest::placeOrderRequest(){
qDebug() << "/v2/store/order";
connect(this, &OAIStoreApiRequest::placeOrder, handler, &OAIStoreApiHandler::placeOrder);
QJsonDocument doc;
@ -100,13 +100,13 @@ void OAIStoreApiRequest::placeOrderRequest(){
::OpenAPI::fromJsonValue(oai_order, obj);
emit placeOrder( oai_order);
emit placeOrder(oai_order);
}
void OAIStoreApiRequest::deleteOrderResponse(){
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::OK);
if(socket->isOpen()){
socket->close();
@ -143,7 +143,7 @@ void OAIStoreApiRequest::placeOrderResponse(const OAIOrder& res){
void OAIStoreApiRequest::deleteOrderError(QNetworkReply::NetworkError error_type, QString& error_str){
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::NotFound);
socket->write(error_str.toUtf8());
if(socket->isOpen()){
@ -189,7 +189,7 @@ void OAIStoreApiRequest::sendCustomResponse(QByteArray & res, QNetworkReply::Net
Q_UNUSED(res); // TODO
Q_UNUSED(error_type); // TODO
}
void OAIStoreApiRequest::sendCustomResponse(QIODevice *res, QNetworkReply::NetworkError error_type){
Q_UNUSED(res); // TODO
Q_UNUSED(error_type); // TODO

View File

@ -30,7 +30,7 @@ namespace OpenAPI {
class OAIStoreApiRequest : public QObject
{
Q_OBJECT
public:
OAIStoreApiRequest(QHttpEngine::Socket *s, OAIStoreApiHandler* handler);
virtual ~OAIStoreApiRequest();
@ -82,7 +82,7 @@ private:
resHeaders.insert(itr.key().toUtf8(), itr.value().toUtf8());
}
socket->setHeaders(resHeaders);
socket->writeHeaders();
socket->writeHeaders();
}
};

View File

@ -25,7 +25,7 @@ OAIUserApiRequest::OAIUserApiRequest(QHttpEngine::Socket *s, OAIUserApiHandler*
auto headers = s->headers();
for(auto itr = headers.begin(); itr != headers.end(); itr++) {
requestHeaders.insert(QString(itr.key()), QString(itr.value()));
}
}
}
OAIUserApiRequest::~OAIUserApiRequest(){
@ -33,7 +33,7 @@ OAIUserApiRequest::~OAIUserApiRequest(){
qDebug() << "OAIUserApiRequest::~OAIUserApiRequest()";
}
QMap<QString, QString>
QMap<QString, QString>
OAIUserApiRequest::getRequestHeaders() const {
return requestHeaders;
}
@ -53,7 +53,7 @@ QHttpEngine::Socket* OAIUserApiRequest::getRawSocket(){
void OAIUserApiRequest::createUserRequest(){
qDebug() << "/v2/user";
connect(this, &OAIUserApiRequest::createUser, handler, &OAIUserApiHandler::createUser);
QJsonDocument doc;
@ -63,18 +63,18 @@ void OAIUserApiRequest::createUserRequest(){
::OpenAPI::fromJsonValue(oai_user, obj);
emit createUser( oai_user);
emit createUser(oai_user);
}
void OAIUserApiRequest::createUsersWithArrayInputRequest(){
qDebug() << "/v2/user/createWithArray";
connect(this, &OAIUserApiRequest::createUsersWithArrayInput, handler, &OAIUserApiHandler::createUsersWithArrayInput);
QJsonDocument doc;
QList<OAIUser> oai_user;
QList<OAIUser> oai_user;
if(socket->readJson(doc)){
QJsonArray jsonArray = doc.array();
foreach(QJsonValue obj, jsonArray) {
@ -85,18 +85,18 @@ void OAIUserApiRequest::createUsersWithArrayInputRequest(){
}
emit createUsersWithArrayInput( oai_user);
emit createUsersWithArrayInput(oai_user);
}
void OAIUserApiRequest::createUsersWithListInputRequest(){
qDebug() << "/v2/user/createWithList";
connect(this, &OAIUserApiRequest::createUsersWithListInput, handler, &OAIUserApiHandler::createUsersWithListInput);
QJsonDocument doc;
QList<OAIUser> oai_user;
QList<OAIUser> oai_user;
if(socket->readJson(doc)){
QJsonArray jsonArray = doc.array();
foreach(QJsonValue obj, jsonArray) {
@ -107,61 +107,61 @@ void OAIUserApiRequest::createUsersWithListInputRequest(){
}
emit createUsersWithListInput( oai_user);
emit createUsersWithListInput(oai_user);
}
void OAIUserApiRequest::deleteUserRequest(const QString& usernamestr){
qDebug() << "/v2/user/{username}";
connect(this, &OAIUserApiRequest::deleteUser, handler, &OAIUserApiHandler::deleteUser);
QString username;
fromStringValue(usernamestr, username);
emit deleteUser( username);
emit deleteUser(username);
}
void OAIUserApiRequest::getUserByNameRequest(const QString& usernamestr){
qDebug() << "/v2/user/{username}";
connect(this, &OAIUserApiRequest::getUserByName, handler, &OAIUserApiHandler::getUserByName);
QString username;
fromStringValue(usernamestr, username);
emit getUserByName( username);
emit getUserByName(username);
}
void OAIUserApiRequest::loginUserRequest(){
qDebug() << "/v2/user/login";
connect(this, &OAIUserApiRequest::loginUser, handler, &OAIUserApiHandler::loginUser);
QString username;
QString username;
if(socket->queryString().keys().contains("username")){
fromStringValue(socket->queryString().value("username"), username);
}
QString password;
QString password;
if(socket->queryString().keys().contains("password")){
fromStringValue(socket->queryString().value("password"), password);
}
emit loginUser( username, password);
emit loginUser(username, password);
}
void OAIUserApiRequest::logoutUserRequest(){
qDebug() << "/v2/user/logout";
connect(this, &OAIUserApiRequest::logoutUser, handler, &OAIUserApiHandler::logoutUser);
@ -172,7 +172,7 @@ void OAIUserApiRequest::logoutUserRequest(){
void OAIUserApiRequest::updateUserRequest(const QString& usernamestr){
qDebug() << "/v2/user/{username}";
connect(this, &OAIUserApiRequest::updateUser, handler, &OAIUserApiHandler::updateUser);
QString username;
fromStringValue(usernamestr, username);
@ -184,13 +184,13 @@ void OAIUserApiRequest::updateUserRequest(const QString& usernamestr){
::OpenAPI::fromJsonValue(oai_user, obj);
emit updateUser( username, oai_user);
emit updateUser(username, oai_user);
}
void OAIUserApiRequest::createUserResponse(){
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::OK);
if(socket->isOpen()){
socket->close();
@ -198,7 +198,7 @@ void OAIUserApiRequest::createUserResponse(){
}
void OAIUserApiRequest::createUsersWithArrayInputResponse(){
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::OK);
if(socket->isOpen()){
socket->close();
@ -206,7 +206,7 @@ void OAIUserApiRequest::createUsersWithArrayInputResponse(){
}
void OAIUserApiRequest::createUsersWithListInputResponse(){
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::OK);
if(socket->isOpen()){
socket->close();
@ -214,7 +214,7 @@ void OAIUserApiRequest::createUsersWithListInputResponse(){
}
void OAIUserApiRequest::deleteUserResponse(){
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::OK);
if(socket->isOpen()){
socket->close();
@ -232,15 +232,14 @@ void OAIUserApiRequest::getUserByNameResponse(const OAIUser& res){
void OAIUserApiRequest::loginUserResponse(const QString& res){
writeResponseHeaders();
QJsonDocument resDoc(::OpenAPI::toJsonValue(res).toObject());
socket->writeJson(resDoc);
socket->write(::OpenAPI::toStringValue(res).toUtf8());
if(socket->isOpen()){
socket->close();
}
}
void OAIUserApiRequest::logoutUserResponse(){
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::OK);
if(socket->isOpen()){
socket->close();
@ -248,7 +247,7 @@ void OAIUserApiRequest::logoutUserResponse(){
}
void OAIUserApiRequest::updateUserResponse(){
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::OK);
if(socket->isOpen()){
socket->close();
@ -258,7 +257,7 @@ void OAIUserApiRequest::updateUserResponse(){
void OAIUserApiRequest::createUserError(QNetworkReply::NetworkError error_type, QString& error_str){
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::NotFound);
socket->write(error_str.toUtf8());
if(socket->isOpen()){
@ -268,7 +267,7 @@ void OAIUserApiRequest::createUserError(QNetworkReply::NetworkError error_type,
void OAIUserApiRequest::createUsersWithArrayInputError(QNetworkReply::NetworkError error_type, QString& error_str){
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::NotFound);
socket->write(error_str.toUtf8());
if(socket->isOpen()){
@ -278,7 +277,7 @@ void OAIUserApiRequest::createUsersWithArrayInputError(QNetworkReply::NetworkErr
void OAIUserApiRequest::createUsersWithListInputError(QNetworkReply::NetworkError error_type, QString& error_str){
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::NotFound);
socket->write(error_str.toUtf8());
if(socket->isOpen()){
@ -288,7 +287,7 @@ void OAIUserApiRequest::createUsersWithListInputError(QNetworkReply::NetworkErro
void OAIUserApiRequest::deleteUserError(QNetworkReply::NetworkError error_type, QString& error_str){
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::NotFound);
socket->write(error_str.toUtf8());
if(socket->isOpen()){
@ -311,8 +310,7 @@ void OAIUserApiRequest::loginUserError(const QString& res, QNetworkReply::Networ
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();
Q_UNUSED(error_str); // response will be used instead of error string
QJsonDocument resDoc(::OpenAPI::toJsonValue(res).toObject());
socket->writeJson(resDoc);
socket->write(::OpenAPI::toStringValue(res).toUtf8());
if(socket->isOpen()){
socket->close();
}
@ -320,7 +318,7 @@ void OAIUserApiRequest::loginUserError(const QString& res, QNetworkReply::Networ
void OAIUserApiRequest::logoutUserError(QNetworkReply::NetworkError error_type, QString& error_str){
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::NotFound);
socket->write(error_str.toUtf8());
if(socket->isOpen()){
@ -330,7 +328,7 @@ void OAIUserApiRequest::logoutUserError(QNetworkReply::NetworkError error_type,
void OAIUserApiRequest::updateUserError(QNetworkReply::NetworkError error_type, QString& error_str){
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::NotFound);
socket->write(error_str.toUtf8());
if(socket->isOpen()){
@ -343,7 +341,7 @@ void OAIUserApiRequest::sendCustomResponse(QByteArray & res, QNetworkReply::Netw
Q_UNUSED(res); // TODO
Q_UNUSED(error_type); // TODO
}
void OAIUserApiRequest::sendCustomResponse(QIODevice *res, QNetworkReply::NetworkError error_type){
Q_UNUSED(res); // TODO
Q_UNUSED(error_type); // TODO

View File

@ -30,7 +30,7 @@ namespace OpenAPI {
class OAIUserApiRequest : public QObject
{
Q_OBJECT
public:
OAIUserApiRequest(QHttpEngine::Socket *s, OAIUserApiHandler* handler);
virtual ~OAIUserApiRequest();
@ -98,7 +98,7 @@ private:
resHeaders.insert(itr.key().toUtf8(), itr.value().toUtf8());
}
socket->setHeaders(resHeaders);
socket->writeHeaders();
socket->writeHeaders();
}
};