From c498008cd2fd098fea75ed657fddaa79ac215ae4 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Mon, 5 Aug 2024 15:38:57 +0800 Subject: [PATCH 1/4] add option for download progress, add test --- .github/workflows/samples-cpp-qt-client.yaml | 9 +- .../cpp-qt-client-addDownloadProgress.yaml | 9 + docs/generators/cpp-qt-client.md | 1 + .../codegen/languages/CppQtClientCodegen.java | 2 + .../.openapi-generator-ignore | 23 + .../.openapi-generator/FILES | 24 + .../.openapi-generator/VERSION | 1 + .../cpp-qt-addDownloadProgress/README.md | 150 ++++++ .../client/CMakeLists.txt | 77 +++ .../client/Config.cmake.in | 5 + .../client/PFXCategory.cpp | 130 +++++ .../client/PFXCategory.h | 70 +++ .../client/PFXEnum.h | 63 +++ .../client/PFXHelpers.cpp | 435 +++++++++++++++ .../client/PFXHelpers.h | 287 ++++++++++ .../client/PFXHttpFileElement.cpp | 147 +++++ .../client/PFXHttpFileElement.h | 47 ++ .../client/PFXHttpRequest.cpp | 502 ++++++++++++++++++ .../client/PFXHttpRequest.h | 110 ++++ .../client/PFXOauth.cpp | 345 ++++++++++++ .../client/PFXOauth.h | 180 +++++++ .../client/PFXObject.h | 79 +++ .../client/PFXPet.cpp | 250 +++++++++ .../client/PFXPet.h | 111 ++++ .../client/PFXPetApi.cpp | 373 +++++++++++++ .../client/PFXPetApi.h | 113 ++++ .../client/PFXServerConfiguration.h | 82 +++ .../client/PFXServerVariable.h | 58 ++ .../client/PFXTag.cpp | 130 +++++ .../client/PFXTag.h | 70 +++ .../client/PFXclient.pri | 31 ++ 31 files changed, 3911 insertions(+), 3 deletions(-) create mode 100644 bin/configs/cpp-qt-client-addDownloadProgress.yaml create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/.openapi-generator-ignore create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/.openapi-generator/FILES create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/.openapi-generator/VERSION create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/README.md create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/CMakeLists.txt create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/Config.cmake.in create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXCategory.cpp create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXCategory.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXEnum.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHelpers.cpp create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHelpers.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHttpFileElement.cpp create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHttpFileElement.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHttpRequest.cpp create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHttpRequest.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXOauth.cpp create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXOauth.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXObject.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPet.cpp create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPet.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPetApi.cpp create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPetApi.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXServerConfiguration.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXServerVariable.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXTag.cpp create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXTag.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXclient.pri diff --git a/.github/workflows/samples-cpp-qt-client.yaml b/.github/workflows/samples-cpp-qt-client.yaml index 44dacd8fe709..d8a1013f2c3f 100644 --- a/.github/workflows/samples-cpp-qt-client.yaml +++ b/.github/workflows/samples-cpp-qt-client.yaml @@ -3,10 +3,10 @@ name: Samples cpp qt client on: push: branches: - - "samples/client/petstore/cpp-qt/**" + - "samples/client/petstore/cpp-qt*/**" pull_request: paths: - - "samples/client/petstore/cpp-qt/**" + - "samples/client/petstore/cpp-qt*/**" env: GRADLE_VERSION: 6.9 @@ -16,6 +16,9 @@ jobs: name: Build cpp qt client strategy: matrix: + sample: + - samples/client/petstore/cpp-qt + - samples/client/petstore/cpp-qt-addDownloadProgress os: - ubuntu-latest - macOS-latest @@ -29,5 +32,5 @@ jobs: version: "6.7.1" target: "desktop" - name: Build - working-directory: "samples/client/petstore/cpp-qt" + working-directory: ${{ matrix.sample }} run: cmake . && cmake --build . --verbose diff --git a/bin/configs/cpp-qt-client-addDownloadProgress.yaml b/bin/configs/cpp-qt-client-addDownloadProgress.yaml new file mode 100644 index 000000000000..02bb91f8cd7a --- /dev/null +++ b/bin/configs/cpp-qt-client-addDownloadProgress.yaml @@ -0,0 +1,9 @@ +generatorName: cpp-qt-client +outputDir: samples/client/petstore/cpp-qt-addDownloadProgress +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-addpet-only.yaml +templateDir: modules/openapi-generator/src/main/resources/cpp-qt-client +additionalProperties: + packageName: CppQtPetstoreClient + cppNamespace: test_namespace + modelNamePrefix: PFX + addDownloadProgress: true diff --git a/docs/generators/cpp-qt-client.md b/docs/generators/cpp-qt-client.md index 76ffcff4068e..ad64db7463b3 100644 --- a/docs/generators/cpp-qt-client.md +++ b/docs/generators/cpp-qt-client.md @@ -18,6 +18,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | +|addDownloadProgress|Add support for Qt download progress| |false| |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |contentCompression|Enable Compressed Content Encoding for requests and responses| |false| |cppNamespace|C++ namespace (convention: name::space::for::api).| |OpenAPI| diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtClientCodegen.java index 048e6ebf949b..49fe90d08ad0 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtClientCodegen.java @@ -40,6 +40,7 @@ public class CppQtClientCodegen extends CppQtAbstractCodegen implements CodegenC // source folder where to write the files protected String sourceFolder = "client"; @Setter protected boolean optionalProjectFileFlag = true; + @Setter protected boolean addDownloadProgress = false; public CppQtClientCodegen() { super(); @@ -98,6 +99,7 @@ public CppQtClientCodegen() { // CLI options addOption(CodegenConstants.PACKAGE_NAME, "C++ package (library) name.", DEFAULT_PACKAGE_NAME); addSwitch(CodegenConstants.OPTIONAL_PROJECT_FILE, OPTIONAL_PROJECT_FILE_DESC, this.optionalProjectFileFlag); + addSwitch("addDownloadProgress", "Add support for Qt download progress", this.addDownloadProgress); supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + "Helpers.h")); supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, PREFIX + "Helpers.cpp")); diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/.openapi-generator-ignore b/samples/client/petstore/cpp-qt-addDownloadProgress/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/.openapi-generator/FILES b/samples/client/petstore/cpp-qt-addDownloadProgress/.openapi-generator/FILES new file mode 100644 index 000000000000..3018f9cad25f --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/.openapi-generator/FILES @@ -0,0 +1,24 @@ +README.md +client/CMakeLists.txt +client/Config.cmake.in +client/PFXCategory.cpp +client/PFXCategory.h +client/PFXEnum.h +client/PFXHelpers.cpp +client/PFXHelpers.h +client/PFXHttpFileElement.cpp +client/PFXHttpFileElement.h +client/PFXHttpRequest.cpp +client/PFXHttpRequest.h +client/PFXOauth.cpp +client/PFXOauth.h +client/PFXObject.h +client/PFXPet.cpp +client/PFXPet.h +client/PFXPetApi.cpp +client/PFXPetApi.h +client/PFXServerConfiguration.h +client/PFXServerVariable.h +client/PFXTag.cpp +client/PFXTag.h +client/PFXclient.pri diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/.openapi-generator/VERSION b/samples/client/petstore/cpp-qt-addDownloadProgress/.openapi-generator/VERSION new file mode 100644 index 000000000000..6116b14d2c59 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.8.0-SNAPSHOT diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/README.md b/samples/client/petstore/cpp-qt-addDownloadProgress/README.md new file mode 100644 index 000000000000..702954814627 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/README.md @@ -0,0 +1,150 @@ +# C++ Qt API client + +# + +OpenAPI Petstore + +- API version: 1.0.0 +- Generator version: 7.8.0-SNAPSHOT + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + + +*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* + + +## Requirements + +Building the API client library requires: + +1. CMake 3.2+ +2. Qt +3. C++ Compiler + +## Getting Started + +example.h: +```c++ + +#include +#include "../client/PFXPetApi.h" + +using namespace test_namespace; + +class Example : public QObject { + Q_OBJECT + PFXPet create(); +public Q_SLOTS: + void exampleFunction1(); +}; + +``` + +example.cpp: +```c++ + +#include "../client/PFXPetApi.h" +#include "example.h" +#include +#include + +PFXPet Example::create(){ + PFXPet obj; + return obj; +} + +void Example::exampleFunction1(){ + PFXPetApi apiInstance; + + //OAuth Authentication supported right now + + QEventLoop loop; + connect(&apiInstance, &PFXPetApi::addPetSignal, [&]() { + loop.quit(); + }); + connect(&apiInstance, &PFXPetApi::addPetSignalE, [&](QNetworkReply::NetworkError, QString error_str) { + qDebug() << "Error happened while issuing request : " << error_str; + loop.quit(); + }); + + PFXPet pfx_pet = create(); // PFXPet | Pet object that needs to be added to the store + apiInstance.addPet(pfx_pet); + QTimer::singleShot(5000, &loop, &QEventLoop::quit); + loop.exec(); + } + +``` + +## Documentation for Servers + +Parameterized Servers are supported. Define a server in the API for each endpoint with arbitrary numbers of variables: + +```yaml +servers: +- url: http://{server}:{port}/{basePath} + description: Description of the Server + variables: + server: + enum: + - 'petstore' + - 'qa-petstore' + - 'dev-petstore' + default: 'petstore' + port: + enum: + - '3000' + - '1000' + default: '3000' + basePath: + default: v1 +``` +To change the default variable, use this function in each Api: +```c++ +int setDefaultServerValue(int serverIndex,const QString &operation, const QString &variable,const QString &val); +``` +The parameter "serverIndex" will choose a server from the server list for each endpoint. There is always at least one server with index 0. The Parameter "operation" should be the desired endpoint operationid. +Variable is the name of the variable you wish to change and the value is the new default Value. +The function will return -1 when the variable does not exists, -2 if value is not defined in the variable enum and -3 if the operation is not found. + +If your endpoint has multiple server objects in the servers array, you can set the server that will be used with this function: +```c++ +void setServerIndex(const QString &operation, int serverIndex); +``` +Parameter "operation" should be your operationid. "serverIndex" is the index you want to set as your default server. The function will check if there is a server with your index. +Here is an example of multiple servers in the servers array. The first server will have index 0 and the second will have index 1. +```yaml +servers: +- url: http://{server}:8080/ + description: Description of the Server + variables: + server: + enum: + - 'petstore' + - 'qa-petstore' + - 'dev-petstore' + default: 'petstore' +- url: https://localhost:8080/v1 +``` + +## Documentation for Authorization + +Authentication schemes defined for the API: +### petstore_auth + + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + + +## Author + + + + +## License + +Apache-2.0 for more information visit [Apache-2.0](https://www.apache.org/licenses/LICENSE-2.0.html) \ No newline at end of file diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/CMakeLists.txt b/samples/client/petstore/cpp-qt-addDownloadProgress/client/CMakeLists.txt new file mode 100644 index 000000000000..b0c5ce51145d --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/CMakeLists.txt @@ -0,0 +1,77 @@ +cmake_minimum_required(VERSION 3.5) + +project(CppQtPetstoreClient) + +set(CMAKE_AUTOMOC ON) + +find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Core Network Gui) +find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core Network Gui) + +include(GNUInstallDirs) +include(CMakePackageConfigHelpers) + +add_library(${PROJECT_NAME} + PFXCategory.h + PFXPet.h + PFXTag.h + PFXPetApi.h + PFXHelpers.h + PFXHttpRequest.h + PFXObject.h + PFXEnum.h + PFXHttpFileElement.h + PFXServerConfiguration.h + PFXServerVariable.h + PFXOauth.h + PFXCategory.cpp + PFXPet.cpp + PFXTag.cpp + PFXPetApi.cpp + PFXHelpers.cpp + PFXHttpRequest.cpp + PFXHttpFileElement.cpp + PFXOauth.cpp + ) + +target_include_directories(${PROJECT_NAME} + PUBLIC + $ + $ +) + +target_link_libraries(${PROJECT_NAME} + PUBLIC + Qt${QT_VERSION_MAJOR}::Core + Qt${QT_VERSION_MAJOR}::Network + Qt${QT_VERSION_MAJOR}::Gui + +) + +configure_package_config_file(${CMAKE_CURRENT_SOURCE_DIR}/Config.cmake.in + "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" + INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}" +) + +install( + TARGETS ${PROJECT_NAME} + EXPORT ${PROJECT_NAME}Targets + LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" + ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" + RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" + INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}" +) + +install( + FILES ${HEADER_FILES} + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME} +) + +install( + FILES "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} +) + +install( + EXPORT ${PROJECT_NAME}Targets + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} +) diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/Config.cmake.in b/samples/client/petstore/cpp-qt-addDownloadProgress/client/Config.cmake.in new file mode 100644 index 000000000000..9015c2ba5eef --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/Config.cmake.in @@ -0,0 +1,5 @@ +@PACKAGE_INIT@ + +include(${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@Targets.cmake) + +check_required_components("@PROJECT_NAME@") diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXCategory.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXCategory.cpp new file mode 100644 index 000000000000..1651c44c1c35 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXCategory.cpp @@ -0,0 +1,130 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "PFXCategory.h" + +#include +#include +#include +#include + +#include "PFXHelpers.h" + +namespace test_namespace { + +PFXCategory::PFXCategory(QString json) { + this->initializeModel(); + this->fromJson(json); +} + +PFXCategory::PFXCategory() { + this->initializeModel(); +} + +PFXCategory::~PFXCategory() {} + +void PFXCategory::initializeModel() { + + m_id_isSet = false; + m_id_isValid = false; + + m_name_isSet = false; + m_name_isValid = false; +} + +void PFXCategory::fromJson(QString jsonString) { + QByteArray array(jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void PFXCategory::fromJsonObject(QJsonObject json) { + + m_id_isValid = ::test_namespace::fromJsonValue(m_id, json[QString("id")]); + m_id_isSet = !json[QString("id")].isNull() && m_id_isValid; + + m_name_isValid = ::test_namespace::fromJsonValue(m_name, json[QString("name")]); + m_name_isSet = !json[QString("name")].isNull() && m_name_isValid; +} + +QString PFXCategory::asJson() const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject PFXCategory::asJsonObject() const { + QJsonObject obj; + if (m_id_isSet) { + obj.insert(QString("id"), ::test_namespace::toJsonValue(m_id)); + } + if (m_name_isSet) { + obj.insert(QString("name"), ::test_namespace::toJsonValue(m_name)); + } + return obj; +} + +qint64 PFXCategory::getId() const { + return m_id; +} +void PFXCategory::setId(const qint64 &id) { + m_id = id; + m_id_isSet = true; +} + +bool PFXCategory::is_id_Set() const{ + return m_id_isSet; +} + +bool PFXCategory::is_id_Valid() const{ + return m_id_isValid; +} + +QString PFXCategory::getName() const { + return m_name; +} +void PFXCategory::setName(const QString &name) { + m_name = name; + m_name_isSet = true; +} + +bool PFXCategory::is_name_Set() const{ + return m_name_isSet; +} + +bool PFXCategory::is_name_Valid() const{ + return m_name_isValid; +} + +bool PFXCategory::isSet() const { + bool isObjectUpdated = false; + do { + if (m_id_isSet) { + isObjectUpdated = true; + break; + } + + if (m_name_isSet) { + isObjectUpdated = true; + break; + } + } while (false); + return isObjectUpdated; +} + +bool PFXCategory::isValid() const { + // only required properties are required for the object to be considered valid + return true; +} + +} // namespace test_namespace diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXCategory.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXCategory.h new file mode 100644 index 000000000000..d86eee9a2626 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXCategory.h @@ -0,0 +1,70 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * PFXCategory.h + * + * A category for a pet + */ + +#ifndef PFXCategory_H +#define PFXCategory_H + +#include + +#include + +#include "PFXEnum.h" +#include "PFXObject.h" + +namespace test_namespace { + +class PFXCategory : public PFXObject { +public: + PFXCategory(); + PFXCategory(QString json); + ~PFXCategory() override; + + QString asJson() const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + qint64 getId() const; + void setId(const qint64 &id); + bool is_id_Set() const; + bool is_id_Valid() const; + + QString getName() const; + void setName(const QString &name); + bool is_name_Set() const; + bool is_name_Valid() const; + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void initializeModel(); + + qint64 m_id; + bool m_id_isSet; + bool m_id_isValid; + + QString m_name; + bool m_name_isSet; + bool m_name_isValid; +}; + +} // namespace test_namespace + +Q_DECLARE_METATYPE(test_namespace::PFXCategory) + +#endif // PFXCategory_H diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXEnum.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXEnum.h new file mode 100644 index 000000000000..c3d19c1a7e29 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXEnum.h @@ -0,0 +1,63 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#ifndef PFX_ENUM_H +#define PFX_ENUM_H + +#include +#include +#include + +namespace test_namespace { + +class PFXEnum { +public: + PFXEnum() {} + + PFXEnum(QString jsonString) { + fromJson(jsonString); + } + + virtual ~PFXEnum() {} + + virtual QJsonValue asJsonValue() const { + return QJsonValue(jstr); + } + + virtual QString asJson() const { + return jstr; + } + + virtual void fromJson(QString jsonString) { + jstr = jsonString; + } + + virtual void fromJsonValue(QJsonValue jval) { + jstr = jval.toString(); + } + + virtual bool isSet() const { + return false; + } + + virtual bool isValid() const { + return true; + } + +private: + QString jstr; +}; + +} // namespace test_namespace + +Q_DECLARE_METATYPE(test_namespace::PFXEnum) + +#endif // PFX_ENUM_H diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHelpers.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHelpers.cpp new file mode 100644 index 000000000000..464f53c6b300 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHelpers.cpp @@ -0,0 +1,435 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include +#include +#include "PFXHelpers.h" + +namespace test_namespace { + +class PFXSerializerSettings { +public: + struct CustomDateTimeFormat{ + bool isStringSet = false; + QString formatString; + bool isEnumSet = false; + Qt::DateFormat formatEnum; + }; + + static CustomDateTimeFormat getCustomDateTimeFormat() { + return getInstance()->customDateTimeFormat; + } + + static void setDateTimeFormatString(const QString &dtFormat){ + getInstance()->customDateTimeFormat.isStringSet = true; + getInstance()->customDateTimeFormat.isEnumSet = false; + getInstance()->customDateTimeFormat.formatString = dtFormat; + } + + static void setDateTimeFormatEnum(const Qt::DateFormat &dtFormat){ + getInstance()->customDateTimeFormat.isEnumSet = true; + getInstance()->customDateTimeFormat.isStringSet = false; + getInstance()->customDateTimeFormat.formatEnum = dtFormat; + } + + static PFXSerializerSettings *getInstance(){ + if(instance == nullptr){ + instance = new PFXSerializerSettings(); + } + return instance; + } + +private: + explicit PFXSerializerSettings(){ + instance = this; + customDateTimeFormat.isStringSet = false; + customDateTimeFormat.isEnumSet = false; + } + static PFXSerializerSettings *instance; + CustomDateTimeFormat customDateTimeFormat; +}; + +PFXSerializerSettings * PFXSerializerSettings::instance = nullptr; + +bool setDateTimeFormat(const QString &dateTimeFormat){ + bool success = false; + auto dt = QDateTime::fromString(QDateTime::currentDateTime().toString(dateTimeFormat), dateTimeFormat); + if (dt.isValid()) { + success = true; + PFXSerializerSettings::setDateTimeFormatString(dateTimeFormat); + } + return success; +} + +bool setDateTimeFormat(const Qt::DateFormat &dateTimeFormat){ + bool success = false; + auto dt = QDateTime::fromString(QDateTime::currentDateTime().toString(dateTimeFormat), dateTimeFormat); + if (dt.isValid()) { + success = true; + PFXSerializerSettings::setDateTimeFormatEnum(dateTimeFormat); + } + return success; +} + +QString toStringValue(const QString &value) { + return value; +} + +QString toStringValue(const QDateTime &value) { + if (PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().isStringSet) { + return value.toString(PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().formatString); + } + + if (PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().isEnumSet) { + return value.toString(PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().formatEnum); + } + + // ISO 8601 + return value.toString(Qt::ISODate); +} + +QString toStringValue(const QByteArray &value) { + return QString(value); +} + +QString toStringValue(const QDate &value) { + // ISO 8601 + return value.toString(Qt::DateFormat::ISODate); +} + +QString toStringValue(const qint32 &value) { + return QString::number(value); +} + +QString toStringValue(const qint64 &value) { + return QString::number(value); +} + +QString toStringValue(const bool &value) { + return QString(value ? "true" : "false"); +} + +QString toStringValue(const float &value) { + return QString::number(static_cast(value)); +} + +QString toStringValue(const double &value) { + return QString::number(value); +} + +QString toStringValue(const PFXObject &value) { + return value.asJson(); +} + +QString toStringValue(const PFXEnum &value) { + return value.asJson(); +} + +QString toStringValue(const PFXHttpFileElement &value) { + return value.asJson(); +} + +QJsonValue toJsonValue(const QString &value) { + return QJsonValue(value); +} + +QJsonValue toJsonValue(const QDateTime &value) { + if (PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().isStringSet) { + return QJsonValue(value.toString(PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().formatString)); + } + + if (PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().isEnumSet) { + return QJsonValue(value.toString(PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().formatEnum)); + } + + // ISO 8601 + return QJsonValue(value.toString(Qt::ISODate)); +} + +QJsonValue toJsonValue(const QByteArray &value) { + return QJsonValue(QString(value.toBase64())); +} + +QJsonValue toJsonValue(const QDate &value) { + return QJsonValue(value.toString(Qt::ISODate)); +} + +QJsonValue toJsonValue(const qint32 &value) { + return QJsonValue(value); +} + +QJsonValue toJsonValue(const qint64 &value) { + return QJsonValue(value); +} + +QJsonValue toJsonValue(const bool &value) { + return QJsonValue(value); +} + +QJsonValue toJsonValue(const float &value) { + return QJsonValue(static_cast(value)); +} + +QJsonValue toJsonValue(const double &value) { + return QJsonValue(value); +} + +QJsonValue toJsonValue(const PFXObject &value) { + return value.asJsonObject(); +} + +QJsonValue toJsonValue(const PFXEnum &value) { + return value.asJsonValue(); +} + +QJsonValue toJsonValue(const PFXHttpFileElement &value) { + return value.asJsonValue(); +} + +QJsonValue toJsonValue(const QJsonValue &value) { + return value; +} + +bool fromStringValue(const QString &inStr, QString &value) { + value.clear(); + value.append(inStr); + return !inStr.isEmpty(); +} + +bool fromStringValue(const QString &inStr, QDateTime &value) { + if (inStr.isEmpty()) { + return false; + } else { + QDateTime dateTime; + if (PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().isStringSet) { + dateTime = QDateTime::fromString(inStr, PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().formatString); + } else if (PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().isEnumSet) { + dateTime = QDateTime::fromString(inStr, PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().formatEnum); + } else { + dateTime = QDateTime::fromString(inStr, Qt::ISODate); + } + + if (dateTime.isValid()) { + value.setDate(dateTime.date()); + value.setTime(dateTime.time()); + } else { + qDebug() << "DateTime is invalid"; + } + return dateTime.isValid(); + } +} + +bool fromStringValue(const QString &inStr, QByteArray &value) { + if (inStr.isEmpty()) { + return false; + } else { + value.clear(); + value.append(inStr.toUtf8()); + return !value.isEmpty(); + } +} + +bool fromStringValue(const QString &inStr, QDate &value) { + if (inStr.isEmpty()) { + return false; + } else { + auto date = QDate::fromString(inStr, Qt::DateFormat::ISODate); + if (date.isValid()) { + value.setDate(date.year(), date.month(), date.day()); + } else { + qDebug() << "Date is invalid"; + } + return date.isValid(); + } +} + +bool fromStringValue(const QString &inStr, qint32 &value) { + bool ok = false; + value = QVariant(inStr).toInt(&ok); + return ok; +} + +bool fromStringValue(const QString &inStr, qint64 &value) { + bool ok = false; + value = QVariant(inStr).toLongLong(&ok); + return ok; +} + +bool fromStringValue(const QString &inStr, bool &value) { + value = QVariant(inStr).toBool(); + return ((inStr == "true") || (inStr == "false")); +} + +bool fromStringValue(const QString &inStr, float &value) { + bool ok = false; + value = QVariant(inStr).toFloat(&ok); + return ok; +} + +bool fromStringValue(const QString &inStr, double &value) { + bool ok = false; + value = QVariant(inStr).toDouble(&ok); + return ok; +} + +bool fromStringValue(const QString &inStr, PFXObject &value) +{ + QJsonParseError err; + QJsonDocument::fromJson(inStr.toUtf8(),&err); + if ( err.error == QJsonParseError::NoError ){ + value.fromJson(inStr); + return true; + } + return false; +} + +bool fromStringValue(const QString &inStr, PFXEnum &value) { + value.fromJson(inStr); + return true; +} + +bool fromStringValue(const QString &inStr, PFXHttpFileElement &value) { + return value.fromStringValue(inStr); +} + +bool fromJsonValue(QString &value, const QJsonValue &jval) { + bool ok = true; + if (!jval.isUndefined() && !jval.isNull()) { + if (jval.isString()) { + value = jval.toString(); + } else if (jval.isBool()) { + value = jval.toBool() ? "true" : "false"; + } else if (jval.isDouble()) { + value = QString::number(jval.toDouble()); + } else { + ok = false; + } + } else { + ok = false; + } + return ok; +} + +bool fromJsonValue(QDateTime &value, const QJsonValue &jval) { + bool ok = true; + if (!jval.isUndefined() && !jval.isNull() && jval.isString()) { + if (PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().isStringSet) { + value = QDateTime::fromString(jval.toString(), PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().formatString); + } else if (PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().isEnumSet) { + value = QDateTime::fromString(jval.toString(), PFXSerializerSettings::getInstance()->getCustomDateTimeFormat().formatEnum); + } else { + value = QDateTime::fromString(jval.toString(), Qt::ISODate); + } + ok = value.isValid(); + } else { + ok = false; + } + return ok; +} + +bool fromJsonValue(QByteArray &value, const QJsonValue &jval) { + bool ok = true; + if (!jval.isUndefined() && !jval.isNull() && jval.isString()) { + value = QByteArray::fromBase64(QByteArray::fromStdString(jval.toString().toStdString())); + ok = value.size() > 0; + } else { + ok = false; + } + return ok; +} + +bool fromJsonValue(QDate &value, const QJsonValue &jval) { + bool ok = true; + if (!jval.isUndefined() && !jval.isNull() && jval.isString()) { + value = QDate::fromString(jval.toString(), Qt::ISODate); + ok = value.isValid(); + } else { + ok = false; + } + return ok; +} + +bool fromJsonValue(qint32 &value, const QJsonValue &jval) { + bool ok = true; + if (!jval.isUndefined() && !jval.isNull() && !jval.isObject() && !jval.isArray()) { + value = jval.toInt(); + } else { + ok = false; + } + return ok; +} + +bool fromJsonValue(qint64 &value, const QJsonValue &jval) { + bool ok = true; + if (!jval.isUndefined() && !jval.isNull() && !jval.isObject() && !jval.isArray()) { + value = jval.toVariant().toLongLong(); + } else { + ok = false; + } + return ok; +} + +bool fromJsonValue(bool &value, const QJsonValue &jval) { + bool ok = true; + if (jval.isBool()) { + value = jval.toBool(); + } else { + ok = false; + } + return ok; +} + +bool fromJsonValue(float &value, const QJsonValue &jval) { + bool ok = true; + if (jval.isDouble()) { + value = static_cast(jval.toDouble()); + } else { + ok = false; + } + return ok; +} + +bool fromJsonValue(double &value, const QJsonValue &jval) { + bool ok = true; + if (jval.isDouble()) { + value = jval.toDouble(); + } else { + ok = false; + } + return ok; +} + +bool fromJsonValue(PFXObject &value, const QJsonValue &jval) { + bool ok = true; + if (jval.isObject()) { + value.fromJsonObject(jval.toObject()); + ok = value.isValid(); + } else { + ok = false; + } + return ok; +} + +bool fromJsonValue(PFXEnum &value, const QJsonValue &jval) { + value.fromJsonValue(jval); + return true; +} + +bool fromJsonValue(PFXHttpFileElement &value, const QJsonValue &jval) { + return value.fromJsonValue(jval); +} + +bool fromJsonValue(QJsonValue &value, const QJsonValue &jval) { + value = jval; + return true; +} + +} // namespace test_namespace diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHelpers.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHelpers.h new file mode 100644 index 000000000000..3503fff75236 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHelpers.h @@ -0,0 +1,287 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#ifndef PFX_HELPERS_H +#define PFX_HELPERS_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "PFXEnum.h" +#include "PFXHttpFileElement.h" +#include "PFXObject.h" + +namespace test_namespace { + +bool setDateTimeFormat(const QString &format); +bool setDateTimeFormat(const Qt::DateFormat &format); + +template +QString toStringValue(const QList &val); + +template +QString toStringValue(const QSet &val); + +template +bool fromStringValue(const QList &inStr, QList &val); + +template +bool fromStringValue(const QSet &inStr, QList &val); + +template +bool fromStringValue(const QMap &inStr, QMap &val); + +template +QJsonValue toJsonValue(const QList &val); + +template +QJsonValue toJsonValue(const QSet &val); + +template +QJsonValue toJsonValue(const QMap &val); + +template +bool fromJsonValue(QList &val, const QJsonValue &jval); + +template +bool fromJsonValue(QSet &val, const QJsonValue &jval); + +template +bool fromJsonValue(QMap &val, const QJsonValue &jval); + +QString toStringValue(const QString &value); +QString toStringValue(const QDateTime &value); +QString toStringValue(const QByteArray &value); +QString toStringValue(const QDate &value); +QString toStringValue(const qint32 &value); +QString toStringValue(const qint64 &value); +QString toStringValue(const bool &value); +QString toStringValue(const float &value); +QString toStringValue(const double &value); +QString toStringValue(const PFXObject &value); +QString toStringValue(const PFXEnum &value); +QString toStringValue(const PFXHttpFileElement &value); + +template +QString toStringValue(const QList &val) { + QString strArray; + for (const auto &item : val) { + strArray.append(toStringValue(item) + ","); + } + if (val.count() > 0) { + strArray.chop(1); + } + return strArray; +} + +template +QString toStringValue(const QSet &val) { + QString strArray; + for (const auto &item : val) { + strArray.append(toStringValue(item) + ","); + } + if (val.count() > 0) { + strArray.chop(1); + } + return strArray; +} + +QJsonValue toJsonValue(const QString &value); +QJsonValue toJsonValue(const QDateTime &value); +QJsonValue toJsonValue(const QByteArray &value); +QJsonValue toJsonValue(const QDate &value); +QJsonValue toJsonValue(const qint32 &value); +QJsonValue toJsonValue(const qint64 &value); +QJsonValue toJsonValue(const bool &value); +QJsonValue toJsonValue(const float &value); +QJsonValue toJsonValue(const double &value); +QJsonValue toJsonValue(const PFXObject &value); +QJsonValue toJsonValue(const PFXEnum &value); +QJsonValue toJsonValue(const PFXHttpFileElement &value); +QJsonValue toJsonValue(const QJsonValue &value); + +template +QJsonValue toJsonValue(const QList &val) { + QJsonArray jArray; + for (const auto &item : val) { + jArray.append(toJsonValue(item)); + } + return jArray; +} + +template +QJsonValue toJsonValue(const QSet &val) { + QJsonArray jArray; + for (const auto &item : val) { + jArray.append(toJsonValue(item)); + } + return jArray; +} + +template +QJsonValue toJsonValue(const QMap &val) { + QJsonObject jObject; + for (const auto &itemkey : val.keys()) { + jObject.insert(itemkey, toJsonValue(val.value(itemkey))); + } + return jObject; +} + +bool fromStringValue(const QString &inStr, QString &value); +bool fromStringValue(const QString &inStr, QDateTime &value); +bool fromStringValue(const QString &inStr, QByteArray &value); +bool fromStringValue(const QString &inStr, QDate &value); +bool fromStringValue(const QString &inStr, qint32 &value); +bool fromStringValue(const QString &inStr, qint64 &value); +bool fromStringValue(const QString &inStr, bool &value); +bool fromStringValue(const QString &inStr, float &value); +bool fromStringValue(const QString &inStr, double &value); +bool fromStringValue(const QString &inStr, PFXObject &value); +bool fromStringValue(const QString &inStr, PFXEnum &value); +bool fromStringValue(const QString &inStr, PFXHttpFileElement &value); + +template +bool fromStringValue(const QList &inStr, QList &val) { + bool ok = (inStr.count() > 0); + for (const auto &item : inStr) { + T itemVal; + ok &= fromStringValue(item, itemVal); + val.push_back(itemVal); + } + return ok; +} + +template +bool fromStringValue(const QSet &inStr, QList &val) { + bool ok = (inStr.count() > 0); + for (const auto &item : inStr) { + T itemVal; + ok &= fromStringValue(item, itemVal); + val.push_back(itemVal); + } + return ok; +} + +template +bool fromStringValue(const QMap &inStr, QMap &val) { + bool ok = (inStr.count() > 0); + for (const auto &itemkey : inStr.keys()) { + T itemVal; + ok &= fromStringValue(inStr.value(itemkey), itemVal); + val.insert(itemkey, itemVal); + } + return ok; +} + +bool fromJsonValue(QString &value, const QJsonValue &jval); +bool fromJsonValue(QDateTime &value, const QJsonValue &jval); +bool fromJsonValue(QByteArray &value, const QJsonValue &jval); +bool fromJsonValue(QDate &value, const QJsonValue &jval); +bool fromJsonValue(qint32 &value, const QJsonValue &jval); +bool fromJsonValue(qint64 &value, const QJsonValue &jval); +bool fromJsonValue(bool &value, const QJsonValue &jval); +bool fromJsonValue(float &value, const QJsonValue &jval); +bool fromJsonValue(double &value, const QJsonValue &jval); +bool fromJsonValue(PFXObject &value, const QJsonValue &jval); +bool fromJsonValue(PFXEnum &value, const QJsonValue &jval); +bool fromJsonValue(PFXHttpFileElement &value, const QJsonValue &jval); +bool fromJsonValue(QJsonValue &value, const QJsonValue &jval); + +template +bool fromJsonValue(QList &val, const QJsonValue &jval) { + bool ok = true; + if (jval.isArray()) { + for (const auto jitem : jval.toArray()) { + T item; + ok &= fromJsonValue(item, jitem); + val.push_back(item); + } + } else { + ok = false; + } + return ok; +} + +template +bool fromJsonValue(QSet &val, const QJsonValue &jval) { + bool ok = true; + if (jval.isArray()) { + for (const auto jitem : jval.toArray()) { + T item; + ok &= fromJsonValue(item, jitem); + val.insert(item); + } + } else { + ok = false; + } + return ok; +} + +template +bool fromJsonValue(QMap &val, const QJsonValue &jval) { + bool ok = true; + if (jval.isObject()) { + auto varmap = jval.toObject().toVariantMap(); + if (varmap.count() > 0) { + for (const auto &itemkey : varmap.keys()) { + T itemVal; + ok &= fromJsonValue(itemVal, QJsonValue::fromVariant(varmap.value(itemkey))); + val.insert(itemkey, itemVal); + } + } + } else { + ok = false; + } + return ok; +} + +template +class OptionalParam { +public: + T m_Value; + bool m_isNull = false; + bool m_hasValue; +public: + OptionalParam(){ + m_hasValue = false; + } + OptionalParam(const T &val, bool isNull = false){ + m_hasValue = true; + m_Value = val; + m_isNull = isNull; + } + bool hasValue() const { + return m_hasValue; + } + T value() const{ + return m_Value; + } + + QString stringValue() const { + if (m_isNull) { + return QStringLiteral(""); + } else { + return toStringValue(value()); + } + } +}; + +} // namespace test_namespace + +#endif // PFX_HELPERS_H diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHttpFileElement.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHttpFileElement.cpp new file mode 100644 index 000000000000..088836d16c74 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHttpFileElement.cpp @@ -0,0 +1,147 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include +#include +#include +#include + +#include "PFXHttpFileElement.h" + +namespace test_namespace { + +void PFXHttpFileElement::setMimeType(const QString &mime) { + mime_type = mime; +} + +void PFXHttpFileElement::setFileName(const QString &name) { + local_filename = name; +} + +void PFXHttpFileElement::setVariableName(const QString &name) { + variable_name = name; +} + +void PFXHttpFileElement::setRequestFileName(const QString &name) { + request_filename = name; +} + +bool PFXHttpFileElement::isSet() const { + return !local_filename.isEmpty() || !request_filename.isEmpty(); +} + +QString PFXHttpFileElement::asJson() const { + QFile file(local_filename); + QByteArray bArray; + bool result = false; + if (file.exists()) { + result = file.open(QIODevice::ReadOnly); + bArray = file.readAll(); + file.close(); + } + if (!result) { + qDebug() << "Error opening file " << local_filename; + } + return QString(bArray); +} + +QJsonValue PFXHttpFileElement::asJsonValue() const { + QFile file(local_filename); + QByteArray bArray; + bool result = false; + if (file.exists()) { + result = file.open(QIODevice::ReadOnly); + bArray = file.readAll(); + file.close(); + } + if (!result) { + qDebug() << "Error opening file " << local_filename; + } + return QJsonDocument::fromJson(bArray.data()).object(); +} + +bool PFXHttpFileElement::fromStringValue(const QString &instr) { + QFile file(local_filename); + bool result = false; + if (file.exists()) { + file.remove(); + } + result = file.open(QIODevice::WriteOnly); + file.write(instr.toUtf8()); + file.close(); + if (!result) { + qDebug() << "Error creating file " << local_filename; + } + return result; +} + +bool PFXHttpFileElement::fromJsonValue(const QJsonValue &jval) { + QFile file(local_filename); + bool result = false; + if (file.exists()) { + file.remove(); + } + result = file.open(QIODevice::WriteOnly); + file.write(QJsonDocument(jval.toObject()).toJson()); + file.close(); + if (!result) { + qDebug() << "Error creating file " << local_filename; + } + return result; +} + +QByteArray PFXHttpFileElement::asByteArray() const { + QFile file(local_filename); + QByteArray bArray; + bool result = false; + if (file.exists()) { + result = file.open(QIODevice::ReadOnly); + bArray = file.readAll(); + file.close(); + } + if (!result) { + qDebug() << "Error opening file " << local_filename; + } + return bArray; +} + +bool PFXHttpFileElement::fromByteArray(const QByteArray &bytes) { + QFile file(local_filename); + bool result = false; + if (file.exists()) { + file.remove(); + } + result = file.open(QIODevice::WriteOnly); + file.write(bytes); + file.close(); + if (!result) { + qDebug() << "Error creating file " << local_filename; + } + return result; +} + +bool PFXHttpFileElement::saveToFile(const QString &varName, const QString &localFName, const QString &reqFname, const QString &mime, const QByteArray &bytes) { + setMimeType(mime); + setFileName(localFName); + setVariableName(varName); + setRequestFileName(reqFname); + return fromByteArray(bytes); +} + +QByteArray PFXHttpFileElement::loadFromFile(const QString &varName, const QString &localFName, const QString &reqFname, const QString &mime) { + setMimeType(mime); + setFileName(localFName); + setVariableName(varName); + setRequestFileName(reqFname); + return asByteArray(); +} + +} // namespace test_namespace diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHttpFileElement.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHttpFileElement.h new file mode 100644 index 000000000000..799a8c2c02a0 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHttpFileElement.h @@ -0,0 +1,47 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#ifndef PFX_HTTP_FILE_ELEMENT_H +#define PFX_HTTP_FILE_ELEMENT_H + +#include +#include +#include + +namespace test_namespace { + +class PFXHttpFileElement { + +public: + QString variable_name; + QString local_filename; + QString request_filename; + QString mime_type; + void setMimeType(const QString &mime); + void setFileName(const QString &name); + void setVariableName(const QString &name); + void setRequestFileName(const QString &name); + bool isSet() const; + bool fromStringValue(const QString &instr); + bool fromJsonValue(const QJsonValue &jval); + bool fromByteArray(const QByteArray &bytes); + bool saveToFile(const QString &variable_name, const QString &local_filename, const QString &request_filename, const QString &mime, const QByteArray &bytes); + QString asJson() const; + QJsonValue asJsonValue() const; + QByteArray asByteArray() const; + QByteArray loadFromFile(const QString &variable_name, const QString &local_filename, const QString &request_filename, const QString &mime); +}; + +} // namespace test_namespace + +Q_DECLARE_METATYPE(test_namespace::PFXHttpFileElement) + +#endif // PFX_HTTP_FILE_ELEMENT_H diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHttpRequest.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHttpRequest.cpp new file mode 100644 index 000000000000..4e36e7a596f0 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHttpRequest.cpp @@ -0,0 +1,502 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + + +#include "PFXHttpRequest.h" + +namespace test_namespace { + +PFXHttpRequestInput::PFXHttpRequestInput() { + initialize(); +} + +PFXHttpRequestInput::PFXHttpRequestInput(QString v_url_str, QString v_http_method) { + initialize(); + url_str = v_url_str; + http_method = v_http_method; +} + +void PFXHttpRequestInput::initialize() { + var_layout = NOT_SET; + url_str = ""; + http_method = "GET"; +} + +void PFXHttpRequestInput::add_var(QString key, QString value) { + vars[key] = value; +} + +void PFXHttpRequestInput::add_file(QString variable_name, QString local_filename, QString request_filename, QString mime_type) { + PFXHttpFileElement file; + file.variable_name = variable_name; + file.local_filename = local_filename; + file.request_filename = request_filename; + file.mime_type = mime_type; + files.append(file); +} + +PFXHttpRequestWorker::PFXHttpRequestWorker(QObject *parent, QNetworkAccessManager *_manager) + : QObject(parent), manager(_manager), timeOutTimer(this), isResponseCompressionEnabled(false), isRequestCompressionEnabled(false), httpResponseCode(-1) { + +#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) + randomGenerator = QRandomGenerator(QDateTime::currentDateTime().toSecsSinceEpoch()); +#else + qsrand(QDateTime::currentDateTime().toTime_t()); +#endif + + if (manager == nullptr) { + manager = new QNetworkAccessManager(this); + } + workingDirectory = QDir::currentPath(); + timeOutTimer.setSingleShot(true); +} + +PFXHttpRequestWorker::~PFXHttpRequestWorker() { + QObject::disconnect(&timeOutTimer, &QTimer::timeout, nullptr, nullptr); + timeOutTimer.stop(); + for (const auto &item : multiPartFields) { + if (item != nullptr) { + delete item; + } + } +} + +QMap PFXHttpRequestWorker::getResponseHeaders() const { + return headers; +} + +PFXHttpFileElement PFXHttpRequestWorker::getHttpFileElement(const QString &fieldname) { + if (!files.isEmpty()) { + if (fieldname.isEmpty()) { + return files.first(); + } else if (files.contains(fieldname)) { + return files[fieldname]; + } + } + return PFXHttpFileElement(); +} + +QByteArray *PFXHttpRequestWorker::getMultiPartField(const QString &fieldname) { + if (!multiPartFields.isEmpty()) { + if (fieldname.isEmpty()) { + return multiPartFields.first(); + } else if (multiPartFields.contains(fieldname)) { + return multiPartFields[fieldname]; + } + } + return nullptr; +} + +void PFXHttpRequestWorker::setTimeOut(int timeOutMs) { + timeOutTimer.setInterval(timeOutMs); + if(timeOutTimer.interval() == 0) { + QObject::disconnect(&timeOutTimer, &QTimer::timeout, nullptr, nullptr); + } +} + +void PFXHttpRequestWorker::setWorkingDirectory(const QString &path) { + if (!path.isEmpty()) { + workingDirectory = path; + } +} + +void PFXHttpRequestWorker::setResponseCompressionEnabled(bool enable) { + isResponseCompressionEnabled = enable; +} + +void PFXHttpRequestWorker::setRequestCompressionEnabled(bool enable) { + isRequestCompressionEnabled = enable; +} + +int PFXHttpRequestWorker::getHttpResponseCode() const{ + return httpResponseCode; +} + +QString PFXHttpRequestWorker::http_attribute_encode(QString attribute_name, QString input) { + // result structure follows RFC 5987 + bool need_utf_encoding = false; + QString result = ""; + QByteArray input_c = input.toLocal8Bit(); + char c; + for (int i = 0; i < input_c.length(); i++) { + c = input_c.at(i); + if (c == '\\' || c == '/' || c == '\0' || c < ' ' || c > '~') { + // ignore and request utf-8 version + need_utf_encoding = true; + } else if (c == '"') { + result += "\\\""; + } else { + result += c; + } + } + + if (result.length() == 0) { + need_utf_encoding = true; + } + + if (!need_utf_encoding) { + // return simple version + return QString("%1=\"%2\"").arg(attribute_name, result); + } + + QString result_utf8 = ""; + for (int i = 0; i < input_c.length(); i++) { + c = input_c.at(i); + if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) { + result_utf8 += c; + } else { + result_utf8 += "%" + QString::number(static_cast(input_c.at(i)), 16).toUpper(); + } + } + + // return enhanced version with UTF-8 support + return QString("%1=\"%2\"; %1*=utf-8''%3").arg(attribute_name, result, result_utf8); +} + +void PFXHttpRequestWorker::execute(PFXHttpRequestInput *input) { + + // reset variables + QNetworkReply *reply = nullptr; + QByteArray request_content = ""; + response = ""; + error_type = QNetworkReply::NoError; + error_str = ""; + bool isFormData = false; + + // decide on the variable layout + + if (input->files.length() > 0) { + input->var_layout = MULTIPART; + } + if (input->var_layout == NOT_SET) { + input->var_layout = input->http_method == "GET" || input->http_method == "HEAD" ? ADDRESS : URL_ENCODED; + } + + // prepare request content + + QString boundary = ""; + + if (input->var_layout == ADDRESS || input->var_layout == URL_ENCODED) { + // variable layout is ADDRESS or URL_ENCODED + + if (input->vars.count() > 0) { + bool first = true; + isFormData = true; + for (QString key : input->vars.keys()) { + if (!first) { + request_content.append("&"); + } + first = false; + + request_content.append(QUrl::toPercentEncoding(key)); + request_content.append("="); + request_content.append(QUrl::toPercentEncoding(input->vars.value(key))); + } + + if (input->var_layout == ADDRESS) { + input->url_str += "?" + request_content; + request_content = ""; + } + } + } else { + // variable layout is MULTIPART + + boundary = QString("__-----------------------%1%2") + #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) + .arg(QDateTime::currentDateTime().toSecsSinceEpoch()) + .arg(randomGenerator.generate()); + #else + .arg(QDateTime::currentDateTime().toTime_t()) + .arg(qrand()); + #endif + QString boundary_delimiter = "--"; + QString new_line = "\r\n"; + + // add variables + for (QString key : input->vars.keys()) { + // add boundary + request_content.append(boundary_delimiter.toUtf8()); + request_content.append(boundary.toUtf8()); + request_content.append(new_line.toUtf8()); + + // add header + request_content.append("Content-Disposition: form-data; "); + request_content.append(http_attribute_encode("name", key).toUtf8()); + request_content.append(new_line.toUtf8()); + request_content.append("Content-Type: text/plain"); + request_content.append(new_line.toUtf8()); + + // add header to body splitter + request_content.append(new_line.toUtf8()); + + // add variable content + request_content.append(input->vars.value(key).toUtf8()); + request_content.append(new_line.toUtf8()); + } + + // add files + for (QList::iterator file_info = input->files.begin(); file_info != input->files.end(); file_info++) { + QFileInfo fi(file_info->local_filename); + + // ensure necessary variables are available + if (file_info->local_filename == nullptr + || file_info->local_filename.isEmpty() + || file_info->variable_name == nullptr + || file_info->variable_name.isEmpty() + || !fi.exists() + || !fi.isFile() + || !fi.isReadable()) { + // silent abort for the current file + continue; + } + + QFile file(file_info->local_filename); + if (!file.open(QIODevice::ReadOnly)) { + // silent abort for the current file + continue; + } + + // ensure filename for the request + if (file_info->request_filename == nullptr || file_info->request_filename.isEmpty()) { + file_info->request_filename = fi.fileName(); + if (file_info->request_filename.isEmpty()) { + file_info->request_filename = "file"; + } + } + + // add boundary + request_content.append(boundary_delimiter.toUtf8()); + request_content.append(boundary.toUtf8()); + request_content.append(new_line.toUtf8()); + + // add header + request_content.append( + QString("Content-Disposition: form-data; %1; %2").arg(http_attribute_encode("name", file_info->variable_name), http_attribute_encode("filename", file_info->request_filename)).toUtf8()); + request_content.append(new_line.toUtf8()); + + if (file_info->mime_type != nullptr && !file_info->mime_type.isEmpty()) { + request_content.append("Content-Type: "); + request_content.append(file_info->mime_type.toUtf8()); + request_content.append(new_line.toUtf8()); + } + + request_content.append("Content-Transfer-Encoding: binary"); + request_content.append(new_line.toUtf8()); + + // add header to body splitter + request_content.append(new_line.toUtf8()); + + // add file content + request_content.append(file.readAll()); + request_content.append(new_line.toUtf8()); + + file.close(); + } + + // add end of body + request_content.append(boundary_delimiter.toUtf8()); + request_content.append(boundary.toUtf8()); + request_content.append(boundary_delimiter.toUtf8()); + } + + if (input->request_body.size() > 0) { + qDebug() << "got a request body"; + request_content.clear(); + if(!isFormData && (input->var_layout != MULTIPART) && isRequestCompressionEnabled){ + request_content.append(compress(input->request_body, 7, PFXCompressionType::Gzip)); + } else { + request_content.append(input->request_body); + } + } + // prepare connection + + QNetworkRequest request = QNetworkRequest(QUrl(input->url_str)); + if (PFXHttpRequestWorker::sslDefaultConfiguration != nullptr) { + request.setSslConfiguration(*PFXHttpRequestWorker::sslDefaultConfiguration); + } + request.setRawHeader("User-Agent", "OpenAPI-Generator/1.0.0/cpp-qt"); + for (QString key : input->headers.keys()) { request.setRawHeader(key.toStdString().c_str(), input->headers.value(key).toStdString().c_str()); } + + if (request_content.size() > 0 && !isFormData && (input->var_layout != MULTIPART)) { + if (!input->headers.contains("Content-Type")) { + request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); + } else { + request.setHeader(QNetworkRequest::ContentTypeHeader, input->headers.value("Content-Type")); + } + if(isRequestCompressionEnabled){ + request.setRawHeader("Content-Encoding", "gzip"); + } + } else if (input->var_layout == URL_ENCODED) { + request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + } else if (input->var_layout == MULTIPART) { + request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data; boundary=" + boundary); + } + + if(isResponseCompressionEnabled){ + request.setRawHeader("Accept-Encoding", "gzip"); + } else { + request.setRawHeader("Accept-Encoding", "identity"); + } + + if (input->http_method == "GET") { + reply = manager->get(request); + } else if (input->http_method == "POST") { + reply = manager->post(request, request_content); + } else if (input->http_method == "PUT") { + reply = manager->put(request, request_content); + } else if (input->http_method == "HEAD") { + reply = manager->head(request); + } else if (input->http_method == "DELETE") { + reply = manager->deleteResource(request); + } else { +#if (QT_VERSION >= 0x050800) + reply = manager->sendCustomRequest(request, input->http_method.toLatin1(), request_content); +#else + QBuffer *buffer = new QBuffer; + buffer->setData(request_content); + buffer->open(QIODevice::ReadOnly); + + reply = manager->sendCustomRequest(request, input->http_method.toLatin1(), buffer); + buffer->setParent(reply); +#endif + } + if (reply != nullptr) { + reply->setParent(this); + connect(reply, &QNetworkReply::downloadProgress, this, &PFXHttpRequestWorker::downloadProgress); + connect(reply, &QNetworkReply::finished, [this, reply] { + on_reply_finished(reply); + }); + } + if (timeOutTimer.interval() > 0) { + QObject::connect(&timeOutTimer, &QTimer::timeout, [this, reply] { + on_reply_timeout(reply); + }); + timeOutTimer.start(); + } +} + +void PFXHttpRequestWorker::on_reply_finished(QNetworkReply *reply) { + bool codeSts = false; + if(timeOutTimer.isActive()) { + QObject::disconnect(&timeOutTimer, &QTimer::timeout, nullptr, nullptr); + timeOutTimer.stop(); + } + error_type = reply->error(); + error_str = reply->errorString(); + if (reply->rawHeaderPairs().count() > 0) { + for (const auto &item : reply->rawHeaderPairs()) { + headers.insert(item.first, item.second); + } + } + auto rescode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(&codeSts); + if(codeSts){ + httpResponseCode = rescode; + } else{ + httpResponseCode = -1; + } + process_response(reply); + reply->deleteLater(); + Q_EMIT on_execution_finished(this); +} + +void PFXHttpRequestWorker::on_reply_timeout(QNetworkReply *reply) { + error_type = QNetworkReply::TimeoutError; + response = ""; + error_str = "Timed out waiting for response"; + disconnect(reply, nullptr, nullptr, nullptr); + reply->abort(); + reply->deleteLater(); + Q_EMIT on_execution_finished(this); +} + +void PFXHttpRequestWorker::process_response(QNetworkReply *reply) { + QString contentDispositionHdr; + QString contentTypeHdr; + QString contentEncodingHdr; + + for(auto hdr: getResponseHeaders().keys()){ + if(hdr.compare(QString("Content-Disposition"), Qt::CaseInsensitive) == 0){ + contentDispositionHdr = getResponseHeaders().value(hdr); + } + if(hdr.compare(QString("Content-Type"), Qt::CaseInsensitive) == 0){ + contentTypeHdr = getResponseHeaders().value(hdr); + } + if(hdr.compare(QString("Content-Encoding"), Qt::CaseInsensitive) == 0){ + contentEncodingHdr = getResponseHeaders().value(hdr); + } + } + + if (!contentDispositionHdr.isEmpty()) { + auto contentDisposition = contentDispositionHdr.split(QString(";"), Qt::SkipEmptyParts); + auto contentType = + !contentTypeHdr.isEmpty() ? contentTypeHdr.split(QString(";"), Qt::SkipEmptyParts).first() : QString(); + if ((contentDisposition.count() > 0) && (contentDisposition.first() == QString("attachment"))) { + QString filename = QUuid::createUuid().toString(); + for (const auto &file : contentDisposition) { + if (file.contains(QString("filename"))) { + filename = file.split(QString("="), Qt::SkipEmptyParts).at(1); + break; + } + } + PFXHttpFileElement felement; + felement.saveToFile(QString(), workingDirectory + QDir::separator() + filename, filename, contentType, reply->readAll()); + files.insert(filename, felement); + } + + } else if (!contentTypeHdr.isEmpty()) { + auto contentType = contentTypeHdr.split(QString(";"), Qt::SkipEmptyParts); + if ((contentType.count() > 0) && (contentType.first() == QString("multipart/form-data"))) { + // TODO : Handle Multipart responses + } else { + if(!contentEncodingHdr.isEmpty()){ + auto encoding = contentEncodingHdr.split(QString(";"), Qt::SkipEmptyParts); + if(encoding.count() > 0){ + auto compressionTypes = encoding.first().split(',', Qt::SkipEmptyParts); + if(compressionTypes.contains("gzip", Qt::CaseInsensitive) || compressionTypes.contains("deflate", Qt::CaseInsensitive)){ + response = decompress(reply->readAll()); + } else if(compressionTypes.contains("identity", Qt::CaseInsensitive)){ + response = reply->readAll(); + } + } + } + else { + response = reply->readAll(); + } + } + } +} + +QByteArray PFXHttpRequestWorker::decompress(const QByteArray& data){ + + Q_UNUSED(data); + return QByteArray(); +} + +QByteArray PFXHttpRequestWorker::compress(const QByteArray& input, int level, PFXCompressionType compressType) { + + Q_UNUSED(input); + Q_UNUSED(level); + Q_UNUSED(compressType); + return QByteArray(); +} + +QSslConfiguration *PFXHttpRequestWorker::sslDefaultConfiguration; + +} // namespace test_namespace diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHttpRequest.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHttpRequest.h new file mode 100644 index 000000000000..e44027c91c14 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXHttpRequest.h @@ -0,0 +1,110 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/** + * Based on http://www.creativepulse.gr/en/blog/2014/restful-api-requests-using-qt-cpp-for-linux-mac-osx-ms-windows + * By Alex Stylianos + * + **/ + +#ifndef PFX_HTTPREQUESTWORKER_H +#define PFX_HTTPREQUESTWORKER_H + +#include +#include +#include +#include +#include +#include +#include + +#include "PFXHttpFileElement.h" + +namespace test_namespace { + +enum PFXHttpRequestVarLayout { + NOT_SET, + ADDRESS, + URL_ENCODED, + MULTIPART +}; + +class PFXHttpRequestInput { + +public: + QString url_str; + QString http_method; + PFXHttpRequestVarLayout var_layout; + QMap vars; + QMap headers; + QList files; + QByteArray request_body; + + PFXHttpRequestInput(); + PFXHttpRequestInput(QString v_url_str, QString v_http_method); + void initialize(); + void add_var(QString key, QString value); + void add_file(QString variable_name, QString local_filename, QString request_filename, QString mime_type); +}; + +class PFXHttpRequestWorker : public QObject { + Q_OBJECT + +public: + explicit PFXHttpRequestWorker(QObject *parent = nullptr, QNetworkAccessManager *manager = nullptr); + virtual ~PFXHttpRequestWorker(); + + QByteArray response; + QNetworkReply::NetworkError error_type; + QString error_str; + + QMap getResponseHeaders() const; + QString http_attribute_encode(QString attribute_name, QString input); + void execute(PFXHttpRequestInput *input); + static QSslConfiguration *sslDefaultConfiguration; + void setTimeOut(int timeOutMs); + void setWorkingDirectory(const QString &path); + PFXHttpFileElement getHttpFileElement(const QString &fieldname = QString()); + QByteArray *getMultiPartField(const QString &fieldname = QString()); + void setResponseCompressionEnabled(bool enable); + void setRequestCompressionEnabled(bool enable); + int getHttpResponseCode() const; + +Q_SIGNALS: + void on_execution_finished(PFXHttpRequestWorker *worker); + void downloadProgress(qint64 bytesReceived, qint64 bytesTotal); + +private: + enum PFXCompressionType{ + Zlib, + Gzip + }; + QNetworkAccessManager *manager; + QMap headers; + QMap files; + QMap multiPartFields; + QString workingDirectory; + QTimer timeOutTimer; + bool isResponseCompressionEnabled; + bool isRequestCompressionEnabled; + int httpResponseCode; + QRandomGenerator randomGenerator; + + void on_reply_timeout(QNetworkReply *reply); + void on_reply_finished(QNetworkReply *reply); + void process_response(QNetworkReply *reply); + QByteArray decompress(const QByteArray& data); + QByteArray compress(const QByteArray& input, int level, PFXCompressionType compressType); +}; + +} // namespace test_namespace + +#endif // PFX_HTTPREQUESTWORKER_H diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXOauth.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXOauth.cpp new file mode 100644 index 000000000000..c22d3a849997 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXOauth.cpp @@ -0,0 +1,345 @@ +#include "PFXOauth.h" + +namespace test_namespace { + +/* + * Base class to perform oauth2 flows + * + */ + + +void OauthBase::onFinish(QNetworkReply *rep) +{ + //TODO emit error signal when token is wrong + QJsonDocument document = QJsonDocument::fromJson(rep->readAll()); + QJsonObject rootObj = document.object(); + QString token = rootObj.find("access_token").value().toString(); + QString scope = rootObj.find("scope").value().toString(); + QString type = rootObj.find("token_type").value().toString(); + int expiresIn = rootObj.find("expires_in").value().toInt(); + addToken(oauthToken(token, expiresIn, scope, type)); +} + +oauthToken OauthBase::getToken(QString scope) +{ + auto tokenIt = m_oauthTokenMap.find(scope); + return tokenIt != m_oauthTokenMap.end() ? tokenIt.value() : oauthToken(); +} + +void OauthBase::addToken(oauthToken token) +{ + m_oauthTokenMap.insert(token.getScope(),token); + Q_EMIT tokenReceived(); + +} + +void OauthBase::removeToken(QString scope) +{ + m_oauthTokenMap.remove(scope); +} + +/* + * Class to perform the authorization code flow + * + */ + +OauthCode::OauthCode(QObject *parent) : OauthBase(parent){} + +void OauthCode::link(){ + connect(&m_server, SIGNAL(dataReceived(QMap)), this, SLOT(onVerificationReceived(QMap))); + connect(this, SIGNAL(authenticationNeeded()), this, SLOT(authenticationNeededCallback())); + connect(this, SIGNAL(tokenReceived()), &m_server, SLOT(stop())); +} + +void OauthCode::unlink() +{ + disconnect(this, nullptr, nullptr, nullptr); + disconnect(&m_server, nullptr, nullptr, nullptr); +} + +void OauthCode::setVariables(QString authUrl, QString tokenUrl, QString scope, QString state, QString redirectUri, QString clientId, QString clientSecret, QString accessType){ + + m_authUrl = QUrl(authUrl); + m_tokenUrl = QUrl(tokenUrl); + m_scope = scope; + m_accessType = accessType; + m_state = state; + m_redirectUri = redirectUri; + m_clientId = clientId; + m_clientSecret = clientSecret; + +} + +void OauthCode::authenticationNeededCallback() +{ + QDesktopServices::openUrl(QUrl(m_authUrl.toString() + "?scope=" + m_scope + (m_accessType=="" ? "" : "&access_type=" + m_accessType) + "&response_type=code" + "&state=" + m_state + "&redirect_uri=" + m_redirectUri + "&client_id=" + m_clientId)); + m_server.start(); +} + +void OauthCode::onVerificationReceived(const QMap response) { + + // Save access code + QString state(response.value("state")); + QString scope(response.value("scope")); + QString code(response.value("code")); + + //create query with the required fields + QUrlQuery postData; + postData.addQueryItem("grant_type", "authorization_code"); + postData.addQueryItem("client_id", m_clientId); + postData.addQueryItem("client_secret", m_clientSecret); + postData.addQueryItem("code", code); + postData.addQueryItem("redirect_uri", m_redirectUri); + QNetworkAccessManager * manager = new QNetworkAccessManager(this); + + QNetworkRequest request(m_tokenUrl); + + request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + + connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(onFinish(QNetworkReply *))); + + manager->post(request, postData.query().toUtf8()); +} + +/* + * Class to perform the implicit flow + * + */ + +OauthImplicit::OauthImplicit(QObject *parent) : OauthBase(parent){} + +void OauthImplicit::link() +{ + //TODO correct linking + connect(&m_server, SIGNAL(dataReceived(QMap)), this, SLOT(ImplicitTokenReceived(QMap))); + connect(this, SIGNAL(authenticationNeeded()), this, SLOT(authenticationNeededCallback())); + connect(this, SIGNAL(tokenReceived()), &m_server, SLOT(stop())); + m_linked = true; +} + +void OauthImplicit::unlink() +{ + disconnect(this, nullptr, nullptr, nullptr); + disconnect(&m_server, nullptr, nullptr, nullptr); + m_linked = false; +} + +void OauthImplicit::setVariables(QString authUrl, QString scope, QString state, QString redirectUri, QString clientId, QString accessType){ + + m_authUrl = QUrl(authUrl); + m_scope = scope; + m_accessType = accessType; + m_state = state; + m_redirectUri = redirectUri; + m_clientId = clientId; + +} + +void OauthImplicit::authenticationNeededCallback() +{ + QDesktopServices::openUrl(QUrl(m_authUrl.toString() + "?scope=" + m_scope + (m_accessType=="" ? "" : "&access_type=" + m_accessType) + "&response_type=token" + "&state=" + m_state + "&redirect_uri=" + m_redirectUri + "&client_id=" + m_clientId)); + m_server.start(); +} + +void OauthImplicit::ImplicitTokenReceived(const QMap response) +{ + QString token = response.find("access_token").value(); + QString scope = response.find("scope").value(); + QString type = response.find("token_type").value(); + int expiresIn = response.find("expires_in").value().toInt(); + addToken(oauthToken(token, expiresIn, scope, type)); +} + + +/* + * Class to perform the client credentials flow + * + */ +OauthCredentials::OauthCredentials(QObject *parent) : OauthBase(parent){} +void OauthCredentials::link() +{ + connect(this, SIGNAL(authenticationNeeded()), this, SLOT(authenticationNeededCallback())); +} + +void OauthCredentials::unlink() +{ + disconnect(this, nullptr, nullptr, nullptr); +} + +void OauthCredentials::setVariables(QString tokenUrl, QString scope, QString clientId, QString clientSecret){ + + m_tokenUrl = QUrl(tokenUrl); + m_scope = scope; + m_clientId = clientId; + m_clientSecret = clientSecret; + +} + +void OauthCredentials::authenticationNeededCallback() +{ + //create query with the required fields + QUrlQuery postData; + postData.addQueryItem("grant_type", "client_credentials"); + postData.addQueryItem("client_id", m_clientId); + postData.addQueryItem("client_secret", m_clientSecret); + postData.addQueryItem("scope", m_scope); + QNetworkAccessManager * manager = new QNetworkAccessManager(this); + + QNetworkRequest request(m_tokenUrl); + + request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + + connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(onFinish(QNetworkReply *))); + + manager->post(request, postData.query().toUtf8()); +} + +/* + * Class to perform the resource owner password flow + * + */ +OauthPassword::OauthPassword(QObject *parent) : OauthBase(parent){} +void OauthPassword::link() +{ + connect(this, SIGNAL(authenticationNeeded()), this, SLOT(authenticationNeededCallback())); +} + +void OauthPassword::unlink() +{ + disconnect(this, nullptr, nullptr, nullptr); +} + +void OauthPassword::setVariables(QString tokenUrl, QString scope, QString clientId, QString clientSecret, QString username, QString password){ + + m_tokenUrl = QUrl(tokenUrl); + m_scope = scope; + m_clientId = clientId; + m_clientSecret = clientSecret; + m_username = username; + m_password = password; + +} +void OauthPassword::authenticationNeededCallback() +{ + //create query with the required fields + QUrlQuery postData; + postData.addQueryItem("grant_type", "password"); + postData.addQueryItem("username", m_username); + postData.addQueryItem("password", m_password); + postData.addQueryItem("client_id", m_clientId); + postData.addQueryItem("client_secret", m_clientSecret); + postData.addQueryItem("scope", m_scope); + QNetworkAccessManager * manager = new QNetworkAccessManager(this); + + QNetworkRequest request(m_tokenUrl); + + request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + + connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(onFinish(QNetworkReply *))); + + manager->post(request, postData.query().toUtf8()); +} + + +/* + * Class that provides a simple reply server + * + */ + +ReplyServer::ReplyServer(QObject *parent) : QTcpServer(parent) +{ + connect(this, SIGNAL(newConnection()), this, SLOT(onConnected())); + m_reply ="you can close this window now!"; +} + +void ReplyServer::start() +{ + if(!listen(QHostAddress::Any, 9999)) + { + qDebug() << "Server could not start"; + } + else + { + qDebug() << "Server started!"; + } +} + +void ReplyServer::stop() +{ + qDebug() << "Stopping the Server..."; + QTcpServer::close(); +} + +void ReplyServer::onConnected() +{ + // need to grab the socket + QTcpSocket *socket = nextPendingConnection(); + connect(socket, SIGNAL(readyRead()), this, SLOT(read()), Qt::UniqueConnection); + connect(socket, SIGNAL(disconnected()), socket, SLOT(deleteLater())); + +} + +void ReplyServer::read() +{ + QTcpSocket *socket = qobject_cast(sender()); + if (!socket) { + qDebug() << "No socket available"; + return; + } + qDebug() << "Socket connected"; + + QTextStream os(socket); + os.setAutoDetectUnicode(true); + os << "HTTP/1.0 200 Ok\r\n" + "Content-Type: text/html; charset=\"utf-8\"\r\n" + "\r\n" + <<"\ + \ + \ + \ + \ + \ +

You can close this window now!

\ + \ + "; + + QByteArray data = socket->readLine(); + QString splitGetLine = QString(data); + splitGetLine.remove("GET"); + splitGetLine.remove("HTTP/1.1"); + splitGetLine.remove("\r\n"); + splitGetLine.remove(" "); + //prefix is needed to extract query params + QUrl getTokenUrl("http://" + splitGetLine); + QList< QPair > tokens; + + QUrlQuery query(getTokenUrl); + tokens = query.queryItems(); + + + QMap queryParams; + for (auto tokenPair : tokens) { + QString key = QUrl::fromPercentEncoding(QByteArray().append(tokenPair.first.trimmed().toLatin1())); + QString value = QUrl::fromPercentEncoding(QByteArray().append(tokenPair.second.trimmed().toLatin1())); + queryParams.insert(key, value); + } + if (!queryParams.contains("state")) { + + socket->close(); + return; + } + socket->close(); + + Q_EMIT dataReceived(queryParams); +} + +} // namespace test_namespace diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXOauth.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXOauth.h new file mode 100644 index 000000000000..9038d05940c2 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXOauth.h @@ -0,0 +1,180 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/** + * Providing a Oauth2 Class and a ReplyServer for the Oauth2 authorization code flow. + */ +#ifndef PFX_OAUTH2_H +#define PFX_OAUTH2_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_namespace { + +class oauthToken +{ +public: + oauthToken(QString token, int expiresIn, QString scope, QString tokenType) : m_token(token), m_scope(scope), m_type(tokenType){ + m_validUntil = time(nullptr) + expiresIn; + } + oauthToken(){ + m_validUntil = time(nullptr) - 1; + } + QString getToken(){return m_token;}; + QString getScope(){return m_scope;}; + QString getType(){return m_type;}; + bool isValid(){return time(nullptr) < m_validUntil;}; + +private: + QString m_token; + time_t m_validUntil; + QString m_scope; + QString m_type; +}; + +class ReplyServer : public QTcpServer +{ + Q_OBJECT +public: + explicit ReplyServer(QObject *parent = nullptr); + void setReply(QByteArray reply){m_reply = reply;}; + void run(); +private: + QByteArray m_reply; + +Q_SIGNALS: + void dataReceived(QMap); + +public Q_SLOTS: + void onConnected(); + void read(); + void start(); + void stop(); +}; + +//Base class +class OauthBase : public QObject +{ + Q_OBJECT +public: + OauthBase(QObject* parent = nullptr) : QObject(parent) {}; + oauthToken getToken(QString scope); + void addToken(oauthToken token); + void removeToken(QString scope); + bool linked(){return m_linked;}; + virtual void link()=0; + virtual void unlink()=0; + +protected: + QMap m_oauthTokenMap; + QUrl m_authUrl; + QUrl m_tokenUrl; + QString m_scope, m_accessType, m_state, m_redirectUri, m_clientId, m_clientSecret; + bool m_linked; + +public Q_SLOTS: + virtual void authenticationNeededCallback()=0; + void onFinish(QNetworkReply *rep); + +Q_SIGNALS: + void authenticationNeeded(); + void tokenReceived(); +}; + +// Authorization code flow +class OauthCode : public OauthBase +{ + Q_OBJECT +public: + OauthCode(QObject *parent = nullptr); + void link() override; + void unlink() override; + void setVariables(QString authUrl, QString tokenUrl, QString scope, QString state, QString redirectUri, QString clientId, QString clientSecret, QString accessType = ""); + +private: + ReplyServer m_server; + +public Q_SLOTS: + void authenticationNeededCallback() override; + void onVerificationReceived(const QMap response); + +}; + +// Implicit flow +class OauthImplicit : public OauthBase +{ + Q_OBJECT +public: + OauthImplicit(QObject *parent = nullptr); + void link() override; + void unlink() override; + void setVariables(QString authUrl, QString scope, QString state, QString redirectUri, QString clientId, QString accessType = ""); + +private: + ReplyServer m_server; + +public Q_SLOTS: + void authenticationNeededCallback() override; + void ImplicitTokenReceived(const QMap response); +}; + +//client credentials flow +class OauthCredentials : public OauthBase +{ + Q_OBJECT +public: + OauthCredentials(QObject *parent = nullptr); + void link() override; + void unlink() override; + void setVariables(QString tokenUrl, QString scope, QString clientId, QString clientSecret); + +public Q_SLOTS: + void authenticationNeededCallback() override; + +}; + +//resource owner password flow +class OauthPassword : public OauthBase +{ + Q_OBJECT +public: + OauthPassword(QObject *parent = nullptr); + void link() override; + void unlink() override; + void setVariables(QString tokenUrl, QString scope, QString clientId, QString clientSecret, QString username, QString password); + +private: + QString m_username, m_password; + +public Q_SLOTS: + void authenticationNeededCallback() override; + +}; + + +} // namespace test_namespace +#endif // PFX_OAUTH2_H diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXObject.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXObject.h new file mode 100644 index 000000000000..7b2e81b53440 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXObject.h @@ -0,0 +1,79 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#ifndef PFX_OBJECT_H +#define PFX_OBJECT_H + +#include +#include +#include + +namespace test_namespace { + +class PFXObject { +public: + PFXObject() {} + + PFXObject(QString jsonString) { + fromJson(jsonString); + } + + virtual ~PFXObject() {} + + virtual QJsonObject asJsonObject() const { + return jObj; + } + + virtual QString asJson() const { + QJsonDocument doc(jObj); + return doc.toJson(QJsonDocument::Compact); + } + + virtual void fromJson(QString jsonString) { + QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8()); + jObj = doc.object(); + } + + virtual void fromJsonObject(QJsonObject json) { + jObj = json; + } + + virtual bool isSet() const { + return false; + } + + virtual bool isValid() const { + return true; + } + +private: + QJsonObject jObj; +}; + +inline bool operator==(const PFXObject& left, const PFXObject& right){ + return (left.asJsonObject() == right.asJsonObject()); +} + +inline +#if QT_VERSION < 0x060000 +uint +#else +size_t +#endif +qHash(const PFXObject& obj, uint seed = 0) noexcept{ + return qHash(obj.asJsonObject(), seed); +} + +} // namespace test_namespace + +Q_DECLARE_METATYPE(test_namespace::PFXObject) + +#endif // PFX_OBJECT_H diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPet.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPet.cpp new file mode 100644 index 000000000000..6f99209ba90a --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPet.cpp @@ -0,0 +1,250 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "PFXPet.h" + +#include +#include +#include +#include + +#include "PFXHelpers.h" + +namespace test_namespace { + +PFXPet::PFXPet(QString json) { + this->initializeModel(); + this->fromJson(json); +} + +PFXPet::PFXPet() { + this->initializeModel(); +} + +PFXPet::~PFXPet() {} + +void PFXPet::initializeModel() { + + m_id_isSet = false; + m_id_isValid = false; + + m_category_isSet = false; + m_category_isValid = false; + + m_name_isSet = false; + m_name_isValid = false; + + m_photo_urls_isSet = false; + m_photo_urls_isValid = false; + + m_tags_isSet = false; + m_tags_isValid = false; + + m_status_isSet = false; + m_status_isValid = false; +} + +void PFXPet::fromJson(QString jsonString) { + QByteArray array(jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void PFXPet::fromJsonObject(QJsonObject json) { + + m_id_isValid = ::test_namespace::fromJsonValue(m_id, json[QString("id")]); + m_id_isSet = !json[QString("id")].isNull() && m_id_isValid; + + m_category_isValid = ::test_namespace::fromJsonValue(m_category, json[QString("category")]); + m_category_isSet = !json[QString("category")].isNull() && m_category_isValid; + + m_name_isValid = ::test_namespace::fromJsonValue(m_name, json[QString("name")]); + m_name_isSet = !json[QString("name")].isNull() && m_name_isValid; + + m_photo_urls_isValid = ::test_namespace::fromJsonValue(m_photo_urls, json[QString("photoUrls")]); + m_photo_urls_isSet = !json[QString("photoUrls")].isNull() && m_photo_urls_isValid; + + m_tags_isValid = ::test_namespace::fromJsonValue(m_tags, json[QString("tags")]); + m_tags_isSet = !json[QString("tags")].isNull() && m_tags_isValid; + + m_status_isValid = ::test_namespace::fromJsonValue(m_status, json[QString("status")]); + m_status_isSet = !json[QString("status")].isNull() && m_status_isValid; +} + +QString PFXPet::asJson() const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject PFXPet::asJsonObject() const { + QJsonObject obj; + if (m_id_isSet) { + obj.insert(QString("id"), ::test_namespace::toJsonValue(m_id)); + } + if (m_category.isSet()) { + obj.insert(QString("category"), ::test_namespace::toJsonValue(m_category)); + } + if (m_name_isSet) { + obj.insert(QString("name"), ::test_namespace::toJsonValue(m_name)); + } + if (m_photo_urls.size() > 0) { + obj.insert(QString("photoUrls"), ::test_namespace::toJsonValue(m_photo_urls)); + } + if (m_tags.size() > 0) { + obj.insert(QString("tags"), ::test_namespace::toJsonValue(m_tags)); + } + if (m_status_isSet) { + obj.insert(QString("status"), ::test_namespace::toJsonValue(m_status)); + } + return obj; +} + +qint64 PFXPet::getId() const { + return m_id; +} +void PFXPet::setId(const qint64 &id) { + m_id = id; + m_id_isSet = true; +} + +bool PFXPet::is_id_Set() const{ + return m_id_isSet; +} + +bool PFXPet::is_id_Valid() const{ + return m_id_isValid; +} + +PFXCategory PFXPet::getCategory() const { + return m_category; +} +void PFXPet::setCategory(const PFXCategory &category) { + m_category = category; + m_category_isSet = true; +} + +bool PFXPet::is_category_Set() const{ + return m_category_isSet; +} + +bool PFXPet::is_category_Valid() const{ + return m_category_isValid; +} + +QString PFXPet::getName() const { + return m_name; +} +void PFXPet::setName(const QString &name) { + m_name = name; + m_name_isSet = true; +} + +bool PFXPet::is_name_Set() const{ + return m_name_isSet; +} + +bool PFXPet::is_name_Valid() const{ + return m_name_isValid; +} + +QList PFXPet::getPhotoUrls() const { + return m_photo_urls; +} +void PFXPet::setPhotoUrls(const QList &photo_urls) { + m_photo_urls = photo_urls; + m_photo_urls_isSet = true; +} + +bool PFXPet::is_photo_urls_Set() const{ + return m_photo_urls_isSet; +} + +bool PFXPet::is_photo_urls_Valid() const{ + return m_photo_urls_isValid; +} + +QList PFXPet::getTags() const { + return m_tags; +} +void PFXPet::setTags(const QList &tags) { + m_tags = tags; + m_tags_isSet = true; +} + +bool PFXPet::is_tags_Set() const{ + return m_tags_isSet; +} + +bool PFXPet::is_tags_Valid() const{ + return m_tags_isValid; +} + +QString PFXPet::getStatus() const { + return m_status; +} +void PFXPet::setStatus(const QString &status) { + m_status = status; + m_status_isSet = true; +} + +bool PFXPet::is_status_Set() const{ + return m_status_isSet; +} + +bool PFXPet::is_status_Valid() const{ + return m_status_isValid; +} + +bool PFXPet::isSet() const { + bool isObjectUpdated = false; + do { + if (m_id_isSet) { + isObjectUpdated = true; + break; + } + + if (m_category.isSet()) { + isObjectUpdated = true; + break; + } + + if (m_name_isSet) { + isObjectUpdated = true; + break; + } + + if (m_photo_urls.size() > 0) { + isObjectUpdated = true; + break; + } + + if (m_tags.size() > 0) { + isObjectUpdated = true; + break; + } + + if (m_status_isSet) { + isObjectUpdated = true; + break; + } + } while (false); + return isObjectUpdated; +} + +bool PFXPet::isValid() const { + // only required properties are required for the object to be considered valid + return m_name_isValid && m_photo_urls_isValid && true; +} + +} // namespace test_namespace diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPet.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPet.h new file mode 100644 index 000000000000..93adfc59e1db --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPet.h @@ -0,0 +1,111 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * PFXPet.h + * + * A pet for sale in the pet store + */ + +#ifndef PFXPet_H +#define PFXPet_H + +#include + +#include "PFXCategory.h" +#include "PFXTag.h" +#include +#include + +#include "PFXEnum.h" +#include "PFXObject.h" + +namespace test_namespace { +class PFXCategory; +class PFXTag; + +class PFXPet : public PFXObject { +public: + PFXPet(); + PFXPet(QString json); + ~PFXPet() override; + + QString asJson() const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + qint64 getId() const; + void setId(const qint64 &id); + bool is_id_Set() const; + bool is_id_Valid() const; + + PFXCategory getCategory() const; + void setCategory(const PFXCategory &category); + bool is_category_Set() const; + bool is_category_Valid() const; + + QString getName() const; + void setName(const QString &name); + bool is_name_Set() const; + bool is_name_Valid() const; + + QList getPhotoUrls() const; + void setPhotoUrls(const QList &photo_urls); + bool is_photo_urls_Set() const; + bool is_photo_urls_Valid() const; + + QList getTags() const; + void setTags(const QList &tags); + bool is_tags_Set() const; + bool is_tags_Valid() const; + + Q_DECL_DEPRECATED QString getStatus() const; + Q_DECL_DEPRECATED void setStatus(const QString &status); + Q_DECL_DEPRECATED bool is_status_Set() const; + Q_DECL_DEPRECATED bool is_status_Valid() const; + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void initializeModel(); + + qint64 m_id; + bool m_id_isSet; + bool m_id_isValid; + + PFXCategory m_category; + bool m_category_isSet; + bool m_category_isValid; + + QString m_name; + bool m_name_isSet; + bool m_name_isValid; + + QList m_photo_urls; + bool m_photo_urls_isSet; + bool m_photo_urls_isValid; + + QList m_tags; + bool m_tags_isSet; + bool m_tags_isValid; + + QString m_status; + bool m_status_isSet; + bool m_status_isValid; +}; + +} // namespace test_namespace + +Q_DECLARE_METATYPE(test_namespace::PFXPet) + +#endif // PFXPet_H diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPetApi.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPetApi.cpp new file mode 100644 index 000000000000..8d09108a9c61 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPetApi.cpp @@ -0,0 +1,373 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "PFXPetApi.h" +#include "PFXServerConfiguration.h" +#include +#include + +namespace test_namespace { + +PFXPetApi::PFXPetApi(const int timeOut) + : _timeOut(timeOut), + _manager(nullptr), + _isResponseCompressionEnabled(false), + _isRequestCompressionEnabled(false) { + initializeServerConfigs(); +} + +PFXPetApi::~PFXPetApi() { +} + +void PFXPetApi::initializeServerConfigs() { + //Default server + QList defaultConf = QList(); + //varying endpoint server + defaultConf.append(PFXServerConfiguration( + QUrl("http://petstore.swagger.io/v2"), + "No description provided", + QMap())); + _serverConfigs.insert("addPet", defaultConf); + _serverIndices.insert("addPet", 0); +} + +/** +* returns 0 on success and -1, -2 or -3 on failure. +* -1 when the variable does not exist and -2 if the value is not defined in the enum and -3 if the operation or server index is not found +*/ +int PFXPetApi::setDefaultServerValue(int serverIndex, const QString &operation, const QString &variable, const QString &value) { + auto it = _serverConfigs.find(operation); + if (it != _serverConfigs.end() && serverIndex < it.value().size()) { + return _serverConfigs[operation][serverIndex].setDefaultValue(variable,value); + } + return -3; +} +void PFXPetApi::setServerIndex(const QString &operation, int serverIndex) { + if (_serverIndices.contains(operation) && serverIndex < _serverConfigs.find(operation).value().size()) { + _serverIndices[operation] = serverIndex; + } +} + +void PFXPetApi::setApiKey(const QString &apiKeyName, const QString &apiKey) { + _apiKeys.insert(apiKeyName, apiKey); +} + +void PFXPetApi::setBearerToken(const QString &token) { + _bearerToken = token; +} + +void PFXPetApi::setUsername(const QString &username) { + _username = username; +} + +void PFXPetApi::setPassword(const QString &password) { + _password = password; +} + + +void PFXPetApi::setTimeOut(const int timeOut) { + _timeOut = timeOut; +} + +void PFXPetApi::setWorkingDirectory(const QString &path) { + _workingDirectory = path; +} + +void PFXPetApi::setNetworkAccessManager(QNetworkAccessManager* manager) { + _manager = manager; +} + +/** + * Appends a new ServerConfiguration to the config map for a specific operation. + * @param operation The id to the target operation. + * @param url A string that contains the URL of the server + * @param description A String that describes the server + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + * returns the index of the new server config on success and -1 if the operation is not found + */ +int PFXPetApi::addServerConfiguration(const QString &operation, const QUrl &url, const QString &description, const QMap &variables) { + if (_serverConfigs.contains(operation)) { + _serverConfigs[operation].append(PFXServerConfiguration( + url, + description, + variables)); + return _serverConfigs[operation].size()-1; + } else { + return -1; + } +} + +/** + * Appends a new ServerConfiguration to the config map for a all operations and sets the index to that server. + * @param url A string that contains the URL of the server + * @param description A String that describes the server + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ +void PFXPetApi::setNewServerForAllOperations(const QUrl &url, const QString &description, const QMap &variables) { + for (auto keyIt = _serverIndices.keyBegin(); keyIt != _serverIndices.keyEnd(); keyIt++) { + setServerIndex(*keyIt, addServerConfiguration(*keyIt, url, description, variables)); + } +} + +/** + * Appends a new ServerConfiguration to the config map for an operations and sets the index to that server. + * @param URL A string that contains the URL of the server + * @param description A String that describes the server + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ +void PFXPetApi::setNewServer(const QString &operation, const QUrl &url, const QString &description, const QMap &variables) { + setServerIndex(operation, addServerConfiguration(operation, url, description, variables)); +} + +void PFXPetApi::addHeaders(const QString &key, const QString &value) { + _defaultHeaders.insert(key, value); +} + +void PFXPetApi::enableRequestCompression() { + _isRequestCompressionEnabled = true; +} + +void PFXPetApi::enableResponseCompression() { + _isResponseCompressionEnabled = true; +} + +void PFXPetApi::abortRequests() { + Q_EMIT abortRequestsSignal(); +} + +QString PFXPetApi::getParamStylePrefix(const QString &style) { + if (style == "matrix") { + return ";"; + } else if (style == "label") { + return "."; + } else if (style == "form") { + return "&"; + } else if (style == "simple") { + return ""; + } else if (style == "spaceDelimited") { + return "&"; + } else if (style == "pipeDelimited") { + return "&"; + } else { + return "none"; + } +} + +QString PFXPetApi::getParamStyleSuffix(const QString &style) { + if (style == "matrix") { + return "="; + } else if (style == "label") { + return ""; + } else if (style == "form") { + return "="; + } else if (style == "simple") { + return ""; + } else if (style == "spaceDelimited") { + return "="; + } else if (style == "pipeDelimited") { + return "="; + } else { + return "none"; + } +} + +QString PFXPetApi::getParamStyleDelimiter(const QString &style, const QString &name, bool isExplode) { + + if (style == "matrix") { + return (isExplode) ? ";" + name + "=" : ","; + + } else if (style == "label") { + return (isExplode) ? "." : ","; + + } else if (style == "form") { + return (isExplode) ? "&" + name + "=" : ","; + + } else if (style == "simple") { + return ","; + } else if (style == "spaceDelimited") { + return (isExplode) ? "&" + name + "=" : " "; + + } else if (style == "pipeDelimited") { + return (isExplode) ? "&" + name + "=" : "|"; + + } else if (style == "deepObject") { + return (isExplode) ? "&" : "none"; + + } else { + return "none"; + } +} + +void PFXPetApi::addPet(const PFXPet &pfx_pet) { + QString fullPath = QString(_serverConfigs["addPet"][_serverIndices.value("addPet")].URL()+"/pet"); + + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "POST"); + + { + + + QByteArray output = pfx_pet.asJson().toUtf8(); + input.request_body.append(output); + } + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXPetApi::addPetProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::addPetCallback); + connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + _OauthMethod = 1; + _implicitFlow.link(); + _passwordFlow.unlink(); + _authFlow.unlink(); + _credentialFlow.unlink(); + QStringList scope; + scope.append("write:pets"); + scope.append("read:pets"); + auto token = _implicitFlow.getToken(scope.join(" ")); + if(token.isValid()) + input.headers.insert("Authorization", "Bearer " + token.getToken()); + + _latestWorker = new PFXHttpRequestWorker(this, _manager); + _latestWorker->setTimeOut(_timeOut); + _latestWorker->setWorkingDirectory(_workingDirectory); + + connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::addPetCallback); + connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); + connect(_latestWorker, &QObject::destroyed, [this](){ + if(findChildren().count() == 0){ + Q_EMIT allPendingRequestsCompleted(); + } + }); + + _latestInput = input; + _latestScope = scope; + + + + worker->execute(&input); +} + +void PFXPetApi::addPetCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + PFXPet output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT addPetSignal(output); + Q_EMIT addPetSignalFull(worker, output); + } else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){ + connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable())); + QStringList scope; + scope.append("write:pets"); + scope.append("read:pets"); + QString scopeStr = scope.join(" "); + QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog"); + //TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like + _implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId"); + Q_EMIT _implicitFlow.authenticationNeeded(); + + + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT addPetSignalE(output, error_type, error_str); + Q_EMIT addPetSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT addPetSignalError(output, error_type, error_str); + Q_EMIT addPetSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXPetApi::tokenAvailable(){ + + oauthToken token; + switch (_OauthMethod) { + case 1: //implicit flow + token = _implicitFlow.getToken(_latestScope.join(" ")); + if(token.isValid()){ + _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); + _latestWorker->execute(&_latestInput); + }else{ + _implicitFlow.removeToken(_latestScope.join(" ")); + qDebug() << "Could not retrieve a valid token"; + } + break; + case 2: //authorization flow + token = _authFlow.getToken(_latestScope.join(" ")); + if(token.isValid()){ + _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); + _latestWorker->execute(&_latestInput); + }else{ + _authFlow.removeToken(_latestScope.join(" ")); + qDebug() << "Could not retrieve a valid token"; + } + break; + case 3: //client credentials flow + token = _credentialFlow.getToken(_latestScope.join(" ")); + if(token.isValid()){ + _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); + _latestWorker->execute(&_latestInput); + }else{ + _credentialFlow.removeToken(_latestScope.join(" ")); + qDebug() << "Could not retrieve a valid token"; + } + break; + case 4: //resource owner password flow + token = _passwordFlow.getToken(_latestScope.join(" ")); + if(token.isValid()){ + _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); + _latestWorker->execute(&_latestInput); + }else{ + _credentialFlow.removeToken(_latestScope.join(" ")); + qDebug() << "Could not retrieve a valid token"; + } + break; + default: + qDebug() << "No Oauth method set!"; + break; + } +} +} // namespace test_namespace diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPetApi.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPetApi.h new file mode 100644 index 000000000000..f096872e95b8 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPetApi.h @@ -0,0 +1,113 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#ifndef PFX_PFXPetApi_H +#define PFX_PFXPetApi_H + +#include "PFXHelpers.h" +#include "PFXHttpRequest.h" +#include "PFXServerConfiguration.h" +#include "PFXOauth.h" + +#include "PFXPet.h" +#include + +#include +#include +#include +#include +#include + +namespace test_namespace { + +class PFXPetApi : public QObject { + Q_OBJECT + +public: + PFXPetApi(const int timeOut = 0); + ~PFXPetApi(); + + void initializeServerConfigs(); + int setDefaultServerValue(int serverIndex,const QString &operation, const QString &variable,const QString &val); + void setServerIndex(const QString &operation, int serverIndex); + void setApiKey(const QString &apiKeyName, const QString &apiKey); + void setBearerToken(const QString &token); + void setUsername(const QString &username); + void setPassword(const QString &password); + void setTimeOut(const int timeOut); + void setWorkingDirectory(const QString &path); + void setNetworkAccessManager(QNetworkAccessManager* manager); + int addServerConfiguration(const QString &operation, const QUrl &url, const QString &description = "", const QMap &variables = QMap()); + void setNewServerForAllOperations(const QUrl &url, const QString &description = "", const QMap &variables = QMap()); + void setNewServer(const QString &operation, const QUrl &url, const QString &description = "", const QMap &variables = QMap()); + void addHeaders(const QString &key, const QString &value); + void enableRequestCompression(); + void enableResponseCompression(); + void abortRequests(); + QString getParamStylePrefix(const QString &style); + QString getParamStyleSuffix(const QString &style); + QString getParamStyleDelimiter(const QString &style, const QString &name, bool isExplode); + + /** + * @param[in] pfx_pet PFXPet [required] + */ + void addPet(const PFXPet &pfx_pet); + + +private: + QMap _serverIndices; + QMap> _serverConfigs; + QMap _apiKeys; + QString _bearerToken; + QString _username; + QString _password; + int _timeOut; + QString _workingDirectory; + QNetworkAccessManager* _manager; + QMap _defaultHeaders; + bool _isResponseCompressionEnabled; + bool _isRequestCompressionEnabled; + PFXHttpRequestInput _latestInput; + PFXHttpRequestWorker *_latestWorker; + QStringList _latestScope; + OauthCode _authFlow; + OauthImplicit _implicitFlow; + OauthCredentials _credentialFlow; + OauthPassword _passwordFlow; + int _OauthMethod = 0; + + void addPetCallback(PFXHttpRequestWorker *worker); + +Q_SIGNALS: + + void addPetSignal(PFXPet summary); + + void addPetProgress(qint64 bytesReceived, qint64 bytesTotal); + + void addPetSignalFull(PFXHttpRequestWorker *worker, PFXPet summary); + + Q_DECL_DEPRECATED_X("Use addPetSignalError() instead") + void addPetSignalE(PFXPet summary, QNetworkReply::NetworkError error_type, QString error_str); + void addPetSignalError(PFXPet summary, QNetworkReply::NetworkError error_type, const QString &error_str); + + Q_DECL_DEPRECATED_X("Use addPetSignalErrorFull() instead") + void addPetSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void addPetSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + + void abortRequestsSignal(); + void allPendingRequestsCompleted(); + +public Q_SLOTS: + void tokenAvailable(); +}; + +} // namespace test_namespace +#endif diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXServerConfiguration.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXServerConfiguration.h new file mode 100644 index 000000000000..12541d41cfce --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXServerConfiguration.h @@ -0,0 +1,82 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/** + * Representing a Server configuration. + */ +#ifndef PFX_SERVERVCONFIGURATION_H +#define PFX_SERVERVCONFIGURATION_H + +#include +#include +#include +#include +#include +#include "PFXServerVariable.h" + +namespace test_namespace { + +class PFXServerConfiguration { +public: + /** + * @param url A URL to the target host. + * @param description A description of the host designated by the URL. + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ + PFXServerConfiguration(const QUrl &url, const QString &description, const QMap &variables) + : _description(description), + _variables(variables), + _url(url){} + PFXServerConfiguration(){} + ~PFXServerConfiguration(){} + + /** + * Format URL template using given variables. + * + * @param variables A map between a variable name and its value. + * @return Formatted URL. + */ + QString URL() { + QString url = _url.toString(); + if(!_variables.empty()){ + // go through variables and replace placeholders + for (auto const& v : _variables.keys()) { + QString name = v; + PFXServerVariable serverVariable = _variables.value(v); + QString value = serverVariable._defaultValue; + + if (!serverVariable._enumValues.empty() && !serverVariable._enumValues.contains(value)) { + throw std::runtime_error(QString("The variable " + name + " in the server URL has invalid value " + value + ".").toUtf8().toStdString()); + } + QRegularExpression regex(QString("\\{" + name + "\\}")); + url = url.replace(regex, value); + + } + return url; + } + return url; + } + + int setDefaultValue(const QString &variable,const QString &value){ + if(_variables.contains(variable)) + return _variables[variable].setDefaultValue(value); + return -1; + } + + QString _description; + QMap _variables; + QUrl _url; + +}; + +} // namespace test_namespace + +#endif // PFX_SERVERVCONFIGURATION_H diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXServerVariable.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXServerVariable.h new file mode 100644 index 000000000000..ed76e24ba378 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXServerVariable.h @@ -0,0 +1,58 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/** + * Representing a Server Variable for server URL template substitution. + */ +#ifndef PFX_SERVERVARIABLE_H +#define PFX_SERVERVARIABLE_H +#include +#include + +namespace test_namespace { + +class PFXServerVariable { +public: + + /** + * @param description A description for the server variable. + * @param defaultValue The default value to use for substitution. + * @param enumValues An enumeration of string values to be used if the substitution options are from a limited set. + */ + PFXServerVariable(const QString &description, const QString &defaultValue, const QSet &enumValues) + : _defaultValue(defaultValue), + _description(description), + _enumValues(enumValues){} + + PFXServerVariable(){} + ~PFXServerVariable(){} + + int setDefaultValue(const QString& value){ + if( _enumValues.contains(value)){ + _defaultValue = value; + return 0; + } + return -2; + } + + QString getDefaultValue(){return _defaultValue;} + QSet getEnumValues(){return _enumValues;} + + + QString _defaultValue; + QString _description; + QSet _enumValues; + +}; + +} // namespace test_namespace + +#endif // PFX_SERVERVARIABLE_H diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXTag.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXTag.cpp new file mode 100644 index 000000000000..ea32dc814765 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXTag.cpp @@ -0,0 +1,130 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "PFXTag.h" + +#include +#include +#include +#include + +#include "PFXHelpers.h" + +namespace test_namespace { + +PFXTag::PFXTag(QString json) { + this->initializeModel(); + this->fromJson(json); +} + +PFXTag::PFXTag() { + this->initializeModel(); +} + +PFXTag::~PFXTag() {} + +void PFXTag::initializeModel() { + + m_id_isSet = false; + m_id_isValid = false; + + m_name_isSet = false; + m_name_isValid = false; +} + +void PFXTag::fromJson(QString jsonString) { + QByteArray array(jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void PFXTag::fromJsonObject(QJsonObject json) { + + m_id_isValid = ::test_namespace::fromJsonValue(m_id, json[QString("id")]); + m_id_isSet = !json[QString("id")].isNull() && m_id_isValid; + + m_name_isValid = ::test_namespace::fromJsonValue(m_name, json[QString("name")]); + m_name_isSet = !json[QString("name")].isNull() && m_name_isValid; +} + +QString PFXTag::asJson() const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject PFXTag::asJsonObject() const { + QJsonObject obj; + if (m_id_isSet) { + obj.insert(QString("id"), ::test_namespace::toJsonValue(m_id)); + } + if (m_name_isSet) { + obj.insert(QString("name"), ::test_namespace::toJsonValue(m_name)); + } + return obj; +} + +qint64 PFXTag::getId() const { + return m_id; +} +void PFXTag::setId(const qint64 &id) { + m_id = id; + m_id_isSet = true; +} + +bool PFXTag::is_id_Set() const{ + return m_id_isSet; +} + +bool PFXTag::is_id_Valid() const{ + return m_id_isValid; +} + +QString PFXTag::getName() const { + return m_name; +} +void PFXTag::setName(const QString &name) { + m_name = name; + m_name_isSet = true; +} + +bool PFXTag::is_name_Set() const{ + return m_name_isSet; +} + +bool PFXTag::is_name_Valid() const{ + return m_name_isValid; +} + +bool PFXTag::isSet() const { + bool isObjectUpdated = false; + do { + if (m_id_isSet) { + isObjectUpdated = true; + break; + } + + if (m_name_isSet) { + isObjectUpdated = true; + break; + } + } while (false); + return isObjectUpdated; +} + +bool PFXTag::isValid() const { + // only required properties are required for the object to be considered valid + return true; +} + +} // namespace test_namespace diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXTag.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXTag.h new file mode 100644 index 000000000000..808aab4519e0 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXTag.h @@ -0,0 +1,70 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * PFXTag.h + * + * A tag for a pet + */ + +#ifndef PFXTag_H +#define PFXTag_H + +#include + +#include + +#include "PFXEnum.h" +#include "PFXObject.h" + +namespace test_namespace { + +class PFXTag : public PFXObject { +public: + PFXTag(); + PFXTag(QString json); + ~PFXTag() override; + + QString asJson() const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + qint64 getId() const; + void setId(const qint64 &id); + bool is_id_Set() const; + bool is_id_Valid() const; + + QString getName() const; + void setName(const QString &name); + bool is_name_Set() const; + bool is_name_Valid() const; + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void initializeModel(); + + qint64 m_id; + bool m_id_isSet; + bool m_id_isValid; + + QString m_name; + bool m_name_isSet; + bool m_name_isValid; +}; + +} // namespace test_namespace + +Q_DECLARE_METATYPE(test_namespace::PFXTag) + +#endif // PFXTag_H diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXclient.pri b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXclient.pri new file mode 100644 index 000000000000..3e4cdfe7449d --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXclient.pri @@ -0,0 +1,31 @@ +QT += network + +HEADERS += \ +# Models + $${PWD}/PFXCategory.h \ + $${PWD}/PFXPet.h \ + $${PWD}/PFXTag.h \ +# APIs + $${PWD}/PFXPetApi.h \ +# Others + $${PWD}/PFXHelpers.h \ + $${PWD}/PFXHttpRequest.h \ + $${PWD}/PFXObject.h \ + $${PWD}/PFXEnum.h \ + $${PWD}/PFXHttpFileElement.h \ + $${PWD}/PFXServerConfiguration.h \ + $${PWD}/PFXServerVariable.h \ + $${PWD}/PFXOauth.h + +SOURCES += \ +# Models + $${PWD}/PFXCategory.cpp \ + $${PWD}/PFXPet.cpp \ + $${PWD}/PFXTag.cpp \ +# APIs + $${PWD}/PFXPetApi.cpp \ +# Others + $${PWD}/PFXHelpers.cpp \ + $${PWD}/PFXHttpRequest.cpp \ + $${PWD}/PFXHttpFileElement.cpp \ + $${PWD}/PFXOauth.cpp From 881d36880a480e0db86bdea45ad90bcbefa4d1ff Mon Sep 17 00:00:00 2001 From: William Cheng Date: Mon, 5 Aug 2024 15:46:32 +0800 Subject: [PATCH 2/4] add cmake file --- .../cpp-qt-addDownloadProgress/CMakeLists.txt | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/CMakeLists.txt diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/CMakeLists.txt b/samples/client/petstore/cpp-qt-addDownloadProgress/CMakeLists.txt new file mode 100644 index 000000000000..938da937a9cf --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/CMakeLists.txt @@ -0,0 +1,31 @@ +cmake_minimum_required(VERSION 3.2) + +project(cpp-qt-petstore) +set(CMAKE_VERBOSE_MAKEFILE ON) +set(CMAKE_INCLUDE_CURRENT_DIR ON) +set(CMAKE_AUTOMOC ON) + +find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Core Network Gui Test) + +if(MSVC) + add_compile_options(/W4 /WX) +else() + add_compile_options(-Wall -Wextra -Werror) +endif() + +add_subdirectory(client) + +find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Test) + +add_executable(cpp-qt-petstore + PetStore/main.cpp + PetStore/PetApiTests.cpp + PetStore/StoreApiTests.cpp + PetStore/UserApiTests.cpp + ) + +target_link_libraries(cpp-qt-petstore PRIVATE CppQtPetstoreClient Qt${QT_VERSION_MAJOR}::Test) + +enable_testing() + +add_test(NAME cpp-qt-petstore-test COMMAND cpp-qt-petstore) From 8944cf87ae30e34ba04298986411ba1b3c17195f Mon Sep 17 00:00:00 2001 From: William Cheng Date: Mon, 5 Aug 2024 15:50:40 +0800 Subject: [PATCH 3/4] remove test --- .../petstore/cpp-qt-addDownloadProgress/CMakeLists.txt | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/CMakeLists.txt b/samples/client/petstore/cpp-qt-addDownloadProgress/CMakeLists.txt index 938da937a9cf..3ddc4ebcd90a 100644 --- a/samples/client/petstore/cpp-qt-addDownloadProgress/CMakeLists.txt +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/CMakeLists.txt @@ -17,12 +17,7 @@ add_subdirectory(client) find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Test) -add_executable(cpp-qt-petstore - PetStore/main.cpp - PetStore/PetApiTests.cpp - PetStore/StoreApiTests.cpp - PetStore/UserApiTests.cpp - ) +add_executable(cpp-qt-petstore) target_link_libraries(cpp-qt-petstore PRIVATE CppQtPetstoreClient Qt${QT_VERSION_MAJOR}::Test) From 09ba14dec5ed71cf1431c7e2ee92b1c7cc607e34 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Mon, 5 Aug 2024 15:55:04 +0800 Subject: [PATCH 4/4] update --- .../cpp-qt-client-addDownloadProgress.yaml | 2 +- .../.openapi-generator/FILES | 14 + .../cpp-qt-addDownloadProgress/CMakeLists.txt | 7 +- .../PetStore/PetApiTests.cpp | 235 ++++ .../PetStore/PetApiTests.h | 17 + .../PetStore/PetStore.pro | 31 + .../PetStore/StoreApiTests.cpp | 85 ++ .../PetStore/StoreApiTests.h | 14 + .../PetStore/UserApiTests.cpp | 199 +++ .../PetStore/UserApiTests.h | 21 + .../PetStore/main.cpp | 22 + .../cpp-qt-addDownloadProgress/README.md | 7 + .../build-and-test.bash | 48 + .../client/CMakeLists.txt | 14 + .../client/PFXApiResponse.cpp | 160 +++ .../client/PFXApiResponse.h | 79 ++ .../client/PFXOrder.cpp | 250 ++++ .../client/PFXOrder.h | 107 ++ .../client/PFXPet.h | 8 +- .../client/PFXPetApi.cpp | 1108 ++++++++++++++++- .../client/PFXPetApi.h | 136 +- .../client/PFXPrimitivesApi.cpp | 406 ++++++ .../client/PFXPrimitivesApi.h | 127 ++ .../client/PFXStoreApi.cpp | 589 +++++++++ .../client/PFXStoreApi.h | 157 +++ .../client/PFXTestAnyType.cpp | 130 ++ .../client/PFXTestAnyType.h | 71 ++ .../client/PFXUser.cpp | 310 +++++ .../client/PFXUser.h | 124 ++ .../client/PFXUserApi.cpp | 918 ++++++++++++++ .../client/PFXUserApi.h | 218 ++++ .../client/PFXclient.pri | 14 + .../cpp-qt-addDownloadProgress/pom.xml | 43 + 33 files changed, 5655 insertions(+), 16 deletions(-) create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/PetApiTests.cpp create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/PetApiTests.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/PetStore.pro create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/StoreApiTests.cpp create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/StoreApiTests.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/UserApiTests.cpp create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/UserApiTests.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/main.cpp create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/build-and-test.bash create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXApiResponse.cpp create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXApiResponse.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXOrder.cpp create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXOrder.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPrimitivesApi.cpp create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPrimitivesApi.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXStoreApi.cpp create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXStoreApi.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXTestAnyType.cpp create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXTestAnyType.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXUser.cpp create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXUser.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXUserApi.cpp create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXUserApi.h create mode 100644 samples/client/petstore/cpp-qt-addDownloadProgress/pom.xml diff --git a/bin/configs/cpp-qt-client-addDownloadProgress.yaml b/bin/configs/cpp-qt-client-addDownloadProgress.yaml index 02bb91f8cd7a..93ca65779b70 100644 --- a/bin/configs/cpp-qt-client-addDownloadProgress.yaml +++ b/bin/configs/cpp-qt-client-addDownloadProgress.yaml @@ -1,6 +1,6 @@ generatorName: cpp-qt-client outputDir: samples/client/petstore/cpp-qt-addDownloadProgress -inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-addpet-only.yaml +inputSpec: modules/openapi-generator/src/test/resources/3_0/cpp-qt/petstore.yaml templateDir: modules/openapi-generator/src/main/resources/cpp-qt-client additionalProperties: packageName: CppQtPetstoreClient diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/.openapi-generator/FILES b/samples/client/petstore/cpp-qt-addDownloadProgress/.openapi-generator/FILES index 3018f9cad25f..08a3d055d2e4 100644 --- a/samples/client/petstore/cpp-qt-addDownloadProgress/.openapi-generator/FILES +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/.openapi-generator/FILES @@ -1,6 +1,8 @@ README.md client/CMakeLists.txt client/Config.cmake.in +client/PFXApiResponse.cpp +client/PFXApiResponse.h client/PFXCategory.cpp client/PFXCategory.h client/PFXEnum.h @@ -13,12 +15,24 @@ client/PFXHttpRequest.h client/PFXOauth.cpp client/PFXOauth.h client/PFXObject.h +client/PFXOrder.cpp +client/PFXOrder.h client/PFXPet.cpp client/PFXPet.h client/PFXPetApi.cpp client/PFXPetApi.h +client/PFXPrimitivesApi.cpp +client/PFXPrimitivesApi.h client/PFXServerConfiguration.h client/PFXServerVariable.h +client/PFXStoreApi.cpp +client/PFXStoreApi.h client/PFXTag.cpp client/PFXTag.h +client/PFXTestAnyType.cpp +client/PFXTestAnyType.h +client/PFXUser.cpp +client/PFXUser.h +client/PFXUserApi.cpp +client/PFXUserApi.h client/PFXclient.pri diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/CMakeLists.txt b/samples/client/petstore/cpp-qt-addDownloadProgress/CMakeLists.txt index 3ddc4ebcd90a..938da937a9cf 100644 --- a/samples/client/petstore/cpp-qt-addDownloadProgress/CMakeLists.txt +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/CMakeLists.txt @@ -17,7 +17,12 @@ add_subdirectory(client) find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Test) -add_executable(cpp-qt-petstore) +add_executable(cpp-qt-petstore + PetStore/main.cpp + PetStore/PetApiTests.cpp + PetStore/StoreApiTests.cpp + PetStore/UserApiTests.cpp + ) target_link_libraries(cpp-qt-petstore PRIVATE CppQtPetstoreClient Qt${QT_VERSION_MAJOR}::Test) diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/PetApiTests.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/PetApiTests.cpp new file mode 100644 index 000000000000..223debe59588 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/PetApiTests.cpp @@ -0,0 +1,235 @@ +#include "PetApiTests.h" + +#include +#include + +PFXPet PetApiTests::createRandomPet() { + PFXPet pet; + qint64 id = QDateTime::currentMSecsSinceEpoch(); + pet.setName("monster"); + pet.setId(id); + pet.setStatus("freaky"); + return pet; +} + +void PetApiTests::findPetsByStatusTest() { + PFXPetApi api; + QEventLoop loop; + bool petFound = false; + + connect(&api, &PFXPetApi::findPetsByStatusSignal, [&](QList pets) { + petFound = true; + foreach (PFXPet pet, pets) { + QVERIFY(pet.getStatus().startsWith("available") || pet.getStatus().startsWith("sold")); + } + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXPetApi::findPetsByStatusSignalError, [&](QList, QNetworkReply::NetworkError, const QString &error_str) { + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + + api.findPetsByStatus({"available", "sold"}); + + QTimer::singleShot(5000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(petFound, "didn't finish within timeout"); +} + +void PetApiTests::createAndGetPetTest() { + PFXPetApi api; + api.setApiKey("api_key","special-key"); + QEventLoop loop; + bool petCreated = false; + + connect(&api, &PFXPetApi::addPetSignal, [&]() { + // pet created + petCreated = true; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXPetApi::addPetSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + + + PFXPet pet = createRandomPet(); + qint64 id = pet.getId(); + + api.addPet(pet); + QTimer::singleShot(14000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(petCreated, "didn't finish within timeout"); + + bool petFetched = false; + + connect(&api, &PFXPetApi::getPetByIdSignal, [&](PFXPet pet) { + QTimer::singleShot(0, &loop, &QEventLoop::quit); + QVERIFY(pet.getId() > 0); +// QVERIFY(pet.getStatus().compare("freaky") == 0); + petFetched = true; + }); + connect(&api, &PFXPetApi::getPetByIdSignalError, [&](PFXPet, QNetworkReply::NetworkError, const QString &error_str) { + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + api.getPetById(id); + QTimer::singleShot(14000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(petFetched, "didn't finish within timeout"); +} + +void PetApiTests::updatePetTest() { + PFXPetApi api; + + PFXPet pet = createRandomPet(); + PFXPet petToCheck; + qint64 id = pet.getId(); + QEventLoop loop; + bool petAdded = false; + + connect(&api, &PFXPetApi::addPetSignal, [&]() { + petAdded = true; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXPetApi::addPetSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + // create pet + api.addPet(pet); + QTimer::singleShot(5000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(petAdded, "didn't finish within timeout"); + + // fetch it + + bool petFetched = false; + connect(&api, &PFXPetApi::getPetByIdSignal, this, [&](PFXPet pet) { + petFetched = true; + petToCheck = pet; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXPetApi::getPetByIdSignalError, this, [&](PFXPet, QNetworkReply::NetworkError, const QString &error_str) { + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + // create pet + api.getPetById(id); + QTimer::singleShot(5000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(petFetched, "didn't finish within timeout"); + + // update it + bool petUpdated = false; + connect(&api, &PFXPetApi::updatePetSignal, [&]() { + petUpdated = true; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXPetApi::updatePetSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + + // update pet + petToCheck.setStatus(QString("scary")); + api.updatePet(petToCheck); + QTimer::singleShot(5000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(petUpdated, "didn't finish within timeout"); + + // check it + bool petFetched2 = false; + connect(&api, &PFXPetApi::getPetByIdSignal, [&](PFXPet pet) { + petFetched2 = true; + QVERIFY(pet.getId() == petToCheck.getId()); + QVERIFY(pet.getStatus().compare(petToCheck.getStatus()) == 0); + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXPetApi::getPetByIdSignalError, [&](PFXPet, QNetworkReply::NetworkError, const QString &error_str) { + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + api.getPetById(id); + QTimer::singleShot(5000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(petFetched2, "didn't finish within timeout"); +} + +void PetApiTests::updatePetWithFormTest() { + PFXPetApi api; + + PFXPet pet = createRandomPet(); + PFXPet petToCheck; + qint64 id = pet.getId(); + QEventLoop loop; + + // create pet + bool petAdded = false; + connect(&api, &PFXPetApi::addPetSignal, [&]() { + petAdded = true; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXPetApi::addPetSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + + api.addPet(pet); + QTimer::singleShot(5000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(petAdded, "didn't finish within timeout"); + + // fetch it + bool petFetched = false; + connect(&api, &PFXPetApi::getPetByIdSignal, [&](PFXPet pet) { + petFetched = true; + petToCheck = pet; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXPetApi::getPetByIdSignalError, [&](PFXPet, QNetworkReply::NetworkError, const QString &error_str) { + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + + api.getPetById(id); + QTimer::singleShot(5000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(petFetched, "didn't finish within timeout"); + + // update it + bool petUpdated = false; + connect(&api, &PFXPetApi::updatePetWithFormSignal, [&]() { + petUpdated = true; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXPetApi::updatePetWithFormSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + + QString name("gorilla"); + api.updatePetWithForm(id, name); + QTimer::singleShot(5000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(petUpdated, "didn't finish within timeout"); + + // fetch it + bool petUpdated2 = false; + connect(&api, &PFXPetApi::getPetByIdSignal, [&](PFXPet pet) { + Q_UNUSED(pet); + petUpdated2 = true; +// QVERIFY(pet.getName().compare(QString("gorilla")) == 0); + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXPetApi::getPetByIdSignalError, [&](PFXPet, QNetworkReply::NetworkError, const QString &error_str) { + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + + api.getPetById(id); + QTimer::singleShot(5000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(petUpdated2, "didn't finish within timeout"); +} + diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/PetApiTests.h b/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/PetApiTests.h new file mode 100644 index 000000000000..77b6bd48ae39 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/PetApiTests.h @@ -0,0 +1,17 @@ +#pragma once + +#include "../client/PFXPetApi.h" + +using namespace test_namespace; + +class PetApiTests : public QObject { + Q_OBJECT + + PFXPet createRandomPet(); + +private Q_SLOTS: + void findPetsByStatusTest(); + void createAndGetPetTest(); + void updatePetTest(); + void updatePetWithFormTest(); +}; diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/PetStore.pro b/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/PetStore.pro new file mode 100644 index 000000000000..6ac197536fba --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/PetStore.pro @@ -0,0 +1,31 @@ +#------------------------------------------------- +# +# Project created by QtCreator 2015-05-14T20:56:31 +# +#------------------------------------------------- + +QT += core gui testlib network + +TARGET = PetStore +CONFIG += console +CONFIG -= app_bundle + +CONFIG += c++11 + +TEMPLATE = app + +include(../client/PFXclient.pri) + +INCLUDEPATH += ../client + +SOURCES += main.cpp \ + PetApiTests.cpp \ + StoreApiTests.cpp \ + UserApiTests.cpp + +HEADERS += PetApiTests.h \ + StoreApiTests.h \ + UserApiTests.h + +# Disable optimisation for better valgrind report +QMAKE_CXXFLAGS_DEBUG += -O0 diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/StoreApiTests.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/StoreApiTests.cpp new file mode 100644 index 000000000000..982121fc9dae --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/StoreApiTests.cpp @@ -0,0 +1,85 @@ +#include "StoreApiTests.h" + +#include +#include +#include + +void StoreApiTests::placeOrderTest() { + PFXStoreApi api; +// api.setUsername("TestName"); +// api.setPassword("TestPassword"); + QEventLoop loop; + bool orderPlaced = false; + + connect(&api, &PFXStoreApi::placeOrderSignal, [&](PFXOrder order) { + orderPlaced = true; +// QVERIFY(order.getPetId() == 10000); +// QVERIFY((order.getId() == 500)); + qDebug() << order.getShipDate(); + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXStoreApi::placeOrderSignalError, [&](PFXOrder, QNetworkReply::NetworkError, const QString &error_str) { + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + + PFXOrder order; + order.setId(500); + order.setQuantity(10); + order.setPetId(10000); + order.setComplete(false); + order.setStatus("shipping"); + order.setShipDate(QDateTime::currentDateTime()); + api.placeOrder(order); + QTimer::singleShot(14000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(orderPlaced, "didn't finish within timeout"); +} + +void StoreApiTests::getOrderByIdTest() { + PFXStoreApi api; + api.setApiKey("api_key_2","testKey"); + QEventLoop loop; + bool orderFetched = false; + + connect(&api, &PFXStoreApi::getOrderByIdSignal, [&](PFXOrder order) { + orderFetched = true; +// QVERIFY(order.getPetId() == 10000); +// QVERIFY((order.getId() == 500)); + qDebug() << order.getShipDate(); + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXStoreApi::getOrderByIdSignalError, [&](PFXOrder, QNetworkReply::NetworkError, const QString &error_str) { + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + + api.getOrderById(500); + QTimer::singleShot(14000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(orderFetched, "didn't finish within timeout"); +} + +void StoreApiTests::getInventoryTest() { + PFXStoreApi api; + api.setApiKey("api_key","special-key"); + QEventLoop loop; + bool inventoryFetched = false; + + connect(&api, &PFXStoreApi::getInventorySignal, [&](QMap status) { + inventoryFetched = true; + for (const auto &key : status.keys()) { + qDebug() << (key) << " Quantities " << status.value(key); + } + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXStoreApi::getInventorySignalError, [&](QMap, QNetworkReply::NetworkError, const QString &error_str) { + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + + api.getInventory(); + QTimer::singleShot(14000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(inventoryFetched, "didn't finish within timeout"); +} diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/StoreApiTests.h b/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/StoreApiTests.h new file mode 100644 index 000000000000..b1ca91b3b924 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/StoreApiTests.h @@ -0,0 +1,14 @@ +#pragma once + +#include "../client/PFXStoreApi.h" + +using namespace test_namespace; + +class StoreApiTests : public QObject { + Q_OBJECT + +private Q_SLOTS: + void placeOrderTest(); + void getOrderByIdTest(); + void getInventoryTest(); +}; diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/UserApiTests.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/UserApiTests.cpp new file mode 100644 index 000000000000..4665a1a4d208 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/UserApiTests.cpp @@ -0,0 +1,199 @@ +#include "UserApiTests.h" + +#include +#include +#include + +PFXUser UserApiTests::createRandomUser() { + PFXUser user; + user.setId(QDateTime::currentMSecsSinceEpoch()); + user.setEmail("Jane.Doe@openapitools.io"); + user.setFirstName("Jane"); + user.setLastName("Doe"); + user.setPhone("123456789"); + user.setUsername("janedoe"); + user.setPassword("secretPassword"); + user.setUserStatus(static_cast(rand())); + return user; +} + +void UserApiTests::createUserTest() { + PFXUserApi api; + QEventLoop loop; + bool userCreated = false; + + connect(&api, &PFXUserApi::createUserSignal, [&]() { + userCreated = true; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXUserApi::createUserSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + + api.createUser(createRandomUser()); + QTimer::singleShot(14000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(userCreated, "didn't finish within timeout"); +} + +void UserApiTests::createUsersWithArrayInputTest() { + PFXUserApi api; + QEventLoop loop; + bool usersCreated = false; + + connect(&api, &PFXUserApi::createUsersWithArrayInputSignal, [&]() { + usersCreated = true; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXUserApi::createUsersWithArrayInputSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + + QList users; + users.append(createRandomUser()); + users.append(createRandomUser()); + users.append(createRandomUser()); + api.createUsersWithArrayInput(users); + QTimer::singleShot(14000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(usersCreated, "didn't finish within timeout"); +} + +void UserApiTests::createUsersWithListInputTest() { + PFXUserApi api; + QEventLoop loop; + bool usersCreated = false; + + connect(&api, &PFXUserApi::createUsersWithListInputSignal, [&]() { + usersCreated = true; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXUserApi::createUsersWithListInputSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + + QList users; + auto johndoe = createRandomUser(); + johndoe.setUsername("johndoe"); + auto rambo = createRandomUser(); + rambo.setUsername("rambo"); + users.append(johndoe); + users.append(rambo); + users.append(createRandomUser()); + api.createUsersWithListInput(users); + QTimer::singleShot(14000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(usersCreated, "didn't finish within timeout"); +} + +void UserApiTests::deleteUserTest() { + PFXUserApi api; + QEventLoop loop; + bool userDeleted = false; + + connect(&api, &PFXUserApi::deleteUserSignal, [&]() { + userDeleted = true; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXUserApi::deleteUserSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { + userDeleted = true; + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + + api.deleteUser("rambo"); + QTimer::singleShot(14000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(userDeleted, "didn't finish within timeout"); +} + +void UserApiTests::getUserByNameTest() { + PFXUserApi api; + QEventLoop loop; + bool userFetched = false; + + connect(&api, &PFXUserApi::getUserByNameSignal, [&](PFXUser summary) { + userFetched = true; + qDebug() << summary.getUsername(); +// QVERIFY(summary.getUsername() == "johndoe"); + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXUserApi::getUserByNameSignalError, [&](PFXUser, QNetworkReply::NetworkError, const QString &error_str) { + userFetched = true; + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + + api.getUserByName("johndoe"); + QTimer::singleShot(14000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(userFetched, "didn't finish within timeout"); +} + +void UserApiTests::loginUserTest() { + PFXUserApi api; + QEventLoop loop; + bool userLogged = false; + + connect(&api, &PFXUserApi::loginUserSignal, [&](QString summary) { + userLogged = true; + qDebug() << summary; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXUserApi::loginUserSignalError, [&](QString, QNetworkReply::NetworkError, const QString &error_str) { + userLogged = true; + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + + api.loginUser("johndoe", "123456789"); + QTimer::singleShot(14000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(userLogged, "didn't finish within timeout"); +} + +void UserApiTests::logoutUserTest() { + PFXUserApi api; + QEventLoop loop; + bool userLoggedOut = false; + + connect(&api, &PFXUserApi::logoutUserSignal, [&]() { + userLoggedOut = true; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXUserApi::logoutUserSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + + api.logoutUser(); + QTimer::singleShot(14000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(userLoggedOut, "didn't finish within timeout"); +} + +void UserApiTests::updateUserTest() { + PFXUserApi api; + QEventLoop loop; + bool userUpdated = false; + + connect(&api, &PFXUserApi::updateUserSignal, [&]() { + userUpdated = true; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + connect(&api, &PFXUserApi::updateUserSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { + qDebug() << "Error happened while issuing request : " << error_str; + QTimer::singleShot(0, &loop, &QEventLoop::quit); + }); + + auto johndoe = createRandomUser(); + johndoe.setUsername("johndoe"); + api.updateUser("johndoe", johndoe); + QTimer::singleShot(14000, &loop, &QEventLoop::quit); + loop.exec(); + QVERIFY2(userUpdated, "didn't finish within timeout"); +} + diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/UserApiTests.h b/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/UserApiTests.h new file mode 100644 index 000000000000..23df1a62ebdd --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/UserApiTests.h @@ -0,0 +1,21 @@ +#pragma once + +#include "../client/PFXUserApi.h" + +using namespace test_namespace; + +class UserApiTests : public QObject { + Q_OBJECT + + PFXUser createRandomUser(); + +private Q_SLOTS: + void createUserTest(); + void createUsersWithArrayInputTest(); + void createUsersWithListInputTest(); + void deleteUserTest(); + void getUserByNameTest(); + void loginUserTest(); + void logoutUserTest(); + void updateUserTest(); +}; diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/main.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/main.cpp new file mode 100644 index 000000000000..79e626c957c0 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/PetStore/main.cpp @@ -0,0 +1,22 @@ +#include +#include + +#include "PFXHelpers.h" +#include "PetApiTests.h" +#include "StoreApiTests.h" +#include "UserApiTests.h" + +int main(int argc, char *argv[]) { + QCoreApplication a(argc, argv); + ::test_namespace::setDateTimeFormat("yyyy-MM-ddTHH:mm:ss.zzzZ"); + PetApiTests petApiTests; + StoreApiTests storeApiTests; + UserApiTests userApiTests; + int failedTests = 0; + + failedTests += QTest::qExec(&petApiTests); + failedTests += QTest::qExec(&storeApiTests); + failedTests += QTest::qExec(&userApiTests); + + return failedTests; +} diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/README.md b/samples/client/petstore/cpp-qt-addDownloadProgress/README.md index 702954814627..906e6e107482 100644 --- a/samples/client/petstore/cpp-qt-addDownloadProgress/README.md +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/README.md @@ -139,6 +139,13 @@ Authentication schemes defined for the API: - write:pets: modify pets in your account - read:pets: read your pets +### api_key + + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ## Author diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/build-and-test.bash b/samples/client/petstore/cpp-qt-addDownloadProgress/build-and-test.bash new file mode 100644 index 000000000000..9602f77ede54 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/build-and-test.bash @@ -0,0 +1,48 @@ +#!/bin/bash + +set -e +# export RUN_VALGRIND_TESTS=TRUE + +mkdir -p build +cd build + +cmake .. + +cmake --build . + +if [[ -z "${RUN_VALGRIND_TESTS}" ]]; then + echo "Running Qt Petstore Tests" + ctest +else + echo "Running Qt Petstore Tests with Valgrind" + valgrind --leak-check=full ./cpp-qt-petstore |& tee result.log || exit 1 + testCount=$(cat result.log | grep 'Finished testing of' | wc -l) + if [ $testCount == 3 ] + then + echo "Ok" + else + echo "The tests were not run!!!" + exit 1 + fi + + echo "Make sure the tests passed:" + successCount=$(cat result.log | grep '0 failed' | wc -l) + if [ $successCount == 3 ] + then + echo "Ok" + else + echo "The tests failed!!!" + exit 1 + fi + + echo "Check if no memory leaks occurred:" + leakCount=$(cat result.log | grep 'lost: 0 bytes in 0 blocks' | wc -l) + if [ $leakCount == 3 ] + then + echo "Ok" + else + echo "There was memory leaks!!!" + exit 1 + fi +fi + diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/CMakeLists.txt b/samples/client/petstore/cpp-qt-addDownloadProgress/client/CMakeLists.txt index b0c5ce51145d..51c19e891bd8 100644 --- a/samples/client/petstore/cpp-qt-addDownloadProgress/client/CMakeLists.txt +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/CMakeLists.txt @@ -11,10 +11,17 @@ include(GNUInstallDirs) include(CMakePackageConfigHelpers) add_library(${PROJECT_NAME} + PFXApiResponse.h PFXCategory.h + PFXOrder.h PFXPet.h PFXTag.h + PFXTestAnyType.h + PFXUser.h PFXPetApi.h + PFXPrimitivesApi.h + PFXStoreApi.h + PFXUserApi.h PFXHelpers.h PFXHttpRequest.h PFXObject.h @@ -23,10 +30,17 @@ add_library(${PROJECT_NAME} PFXServerConfiguration.h PFXServerVariable.h PFXOauth.h + PFXApiResponse.cpp PFXCategory.cpp + PFXOrder.cpp PFXPet.cpp PFXTag.cpp + PFXTestAnyType.cpp + PFXUser.cpp PFXPetApi.cpp + PFXPrimitivesApi.cpp + PFXStoreApi.cpp + PFXUserApi.cpp PFXHelpers.cpp PFXHttpRequest.cpp PFXHttpFileElement.cpp diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXApiResponse.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXApiResponse.cpp new file mode 100644 index 000000000000..8fbef0fb8c5c --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXApiResponse.cpp @@ -0,0 +1,160 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "PFXApiResponse.h" + +#include +#include +#include +#include + +#include "PFXHelpers.h" + +namespace test_namespace { + +PFXApiResponse::PFXApiResponse(QString json) { + this->initializeModel(); + this->fromJson(json); +} + +PFXApiResponse::PFXApiResponse() { + this->initializeModel(); +} + +PFXApiResponse::~PFXApiResponse() {} + +void PFXApiResponse::initializeModel() { + + m_code_isSet = false; + m_code_isValid = false; + + m_type_isSet = false; + m_type_isValid = false; + + m_message_isSet = false; + m_message_isValid = false; +} + +void PFXApiResponse::fromJson(QString jsonString) { + QByteArray array(jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void PFXApiResponse::fromJsonObject(QJsonObject json) { + + m_code_isValid = ::test_namespace::fromJsonValue(m_code, json[QString("code")]); + m_code_isSet = !json[QString("code")].isNull() && m_code_isValid; + + m_type_isValid = ::test_namespace::fromJsonValue(m_type, json[QString("type")]); + m_type_isSet = !json[QString("type")].isNull() && m_type_isValid; + + m_message_isValid = ::test_namespace::fromJsonValue(m_message, json[QString("message")]); + m_message_isSet = !json[QString("message")].isNull() && m_message_isValid; +} + +QString PFXApiResponse::asJson() const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject PFXApiResponse::asJsonObject() const { + QJsonObject obj; + if (m_code_isSet) { + obj.insert(QString("code"), ::test_namespace::toJsonValue(m_code)); + } + if (m_type_isSet) { + obj.insert(QString("type"), ::test_namespace::toJsonValue(m_type)); + } + if (m_message_isSet) { + obj.insert(QString("message"), ::test_namespace::toJsonValue(m_message)); + } + return obj; +} + +qint32 PFXApiResponse::getCode() const { + return m_code; +} +void PFXApiResponse::setCode(const qint32 &code) { + m_code = code; + m_code_isSet = true; +} + +bool PFXApiResponse::is_code_Set() const{ + return m_code_isSet; +} + +bool PFXApiResponse::is_code_Valid() const{ + return m_code_isValid; +} + +QString PFXApiResponse::getType() const { + return m_type; +} +void PFXApiResponse::setType(const QString &type) { + m_type = type; + m_type_isSet = true; +} + +bool PFXApiResponse::is_type_Set() const{ + return m_type_isSet; +} + +bool PFXApiResponse::is_type_Valid() const{ + return m_type_isValid; +} + +QString PFXApiResponse::getMessage() const { + return m_message; +} +void PFXApiResponse::setMessage(const QString &message) { + m_message = message; + m_message_isSet = true; +} + +bool PFXApiResponse::is_message_Set() const{ + return m_message_isSet; +} + +bool PFXApiResponse::is_message_Valid() const{ + return m_message_isValid; +} + +bool PFXApiResponse::isSet() const { + bool isObjectUpdated = false; + do { + if (m_code_isSet) { + isObjectUpdated = true; + break; + } + + if (m_type_isSet) { + isObjectUpdated = true; + break; + } + + if (m_message_isSet) { + isObjectUpdated = true; + break; + } + } while (false); + return isObjectUpdated; +} + +bool PFXApiResponse::isValid() const { + // only required properties are required for the object to be considered valid + return true; +} + +} // namespace test_namespace diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXApiResponse.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXApiResponse.h new file mode 100644 index 000000000000..dc7682206561 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXApiResponse.h @@ -0,0 +1,79 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * PFXApiResponse.h + * + * Describes the result of uploading an image resource + */ + +#ifndef PFXApiResponse_H +#define PFXApiResponse_H + +#include + +#include + +#include "PFXEnum.h" +#include "PFXObject.h" + +namespace test_namespace { + +class PFXApiResponse : public PFXObject { +public: + PFXApiResponse(); + PFXApiResponse(QString json); + ~PFXApiResponse() override; + + QString asJson() const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + qint32 getCode() const; + void setCode(const qint32 &code); + bool is_code_Set() const; + bool is_code_Valid() const; + + QString getType() const; + void setType(const QString &type); + bool is_type_Set() const; + bool is_type_Valid() const; + + QString getMessage() const; + void setMessage(const QString &message); + bool is_message_Set() const; + bool is_message_Valid() const; + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void initializeModel(); + + qint32 m_code; + bool m_code_isSet; + bool m_code_isValid; + + QString m_type; + bool m_type_isSet; + bool m_type_isValid; + + QString m_message; + bool m_message_isSet; + bool m_message_isValid; +}; + +} // namespace test_namespace + +Q_DECLARE_METATYPE(test_namespace::PFXApiResponse) + +#endif // PFXApiResponse_H diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXOrder.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXOrder.cpp new file mode 100644 index 000000000000..15f7e8c36011 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXOrder.cpp @@ -0,0 +1,250 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "PFXOrder.h" + +#include +#include +#include +#include + +#include "PFXHelpers.h" + +namespace test_namespace { + +PFXOrder::PFXOrder(QString json) { + this->initializeModel(); + this->fromJson(json); +} + +PFXOrder::PFXOrder() { + this->initializeModel(); +} + +PFXOrder::~PFXOrder() {} + +void PFXOrder::initializeModel() { + + m_id_isSet = false; + m_id_isValid = false; + + m_pet_id_isSet = false; + m_pet_id_isValid = false; + + m_quantity_isSet = false; + m_quantity_isValid = false; + + m_ship_date_isSet = false; + m_ship_date_isValid = false; + + m_status_isSet = false; + m_status_isValid = false; + + m_complete_isSet = false; + m_complete_isValid = false; +} + +void PFXOrder::fromJson(QString jsonString) { + QByteArray array(jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void PFXOrder::fromJsonObject(QJsonObject json) { + + m_id_isValid = ::test_namespace::fromJsonValue(m_id, json[QString("id")]); + m_id_isSet = !json[QString("id")].isNull() && m_id_isValid; + + m_pet_id_isValid = ::test_namespace::fromJsonValue(m_pet_id, json[QString("petId")]); + m_pet_id_isSet = !json[QString("petId")].isNull() && m_pet_id_isValid; + + m_quantity_isValid = ::test_namespace::fromJsonValue(m_quantity, json[QString("quantity")]); + m_quantity_isSet = !json[QString("quantity")].isNull() && m_quantity_isValid; + + m_ship_date_isValid = ::test_namespace::fromJsonValue(m_ship_date, json[QString("shipDate")]); + m_ship_date_isSet = !json[QString("shipDate")].isNull() && m_ship_date_isValid; + + m_status_isValid = ::test_namespace::fromJsonValue(m_status, json[QString("status")]); + m_status_isSet = !json[QString("status")].isNull() && m_status_isValid; + + m_complete_isValid = ::test_namespace::fromJsonValue(m_complete, json[QString("complete")]); + m_complete_isSet = !json[QString("complete")].isNull() && m_complete_isValid; +} + +QString PFXOrder::asJson() const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject PFXOrder::asJsonObject() const { + QJsonObject obj; + if (m_id_isSet) { + obj.insert(QString("id"), ::test_namespace::toJsonValue(m_id)); + } + if (m_pet_id_isSet) { + obj.insert(QString("petId"), ::test_namespace::toJsonValue(m_pet_id)); + } + if (m_quantity_isSet) { + obj.insert(QString("quantity"), ::test_namespace::toJsonValue(m_quantity)); + } + if (m_ship_date_isSet) { + obj.insert(QString("shipDate"), ::test_namespace::toJsonValue(m_ship_date)); + } + if (m_status_isSet) { + obj.insert(QString("status"), ::test_namespace::toJsonValue(m_status)); + } + if (m_complete_isSet) { + obj.insert(QString("complete"), ::test_namespace::toJsonValue(m_complete)); + } + return obj; +} + +qint64 PFXOrder::getId() const { + return m_id; +} +void PFXOrder::setId(const qint64 &id) { + m_id = id; + m_id_isSet = true; +} + +bool PFXOrder::is_id_Set() const{ + return m_id_isSet; +} + +bool PFXOrder::is_id_Valid() const{ + return m_id_isValid; +} + +qint64 PFXOrder::getPetId() const { + return m_pet_id; +} +void PFXOrder::setPetId(const qint64 &pet_id) { + m_pet_id = pet_id; + m_pet_id_isSet = true; +} + +bool PFXOrder::is_pet_id_Set() const{ + return m_pet_id_isSet; +} + +bool PFXOrder::is_pet_id_Valid() const{ + return m_pet_id_isValid; +} + +qint32 PFXOrder::getQuantity() const { + return m_quantity; +} +void PFXOrder::setQuantity(const qint32 &quantity) { + m_quantity = quantity; + m_quantity_isSet = true; +} + +bool PFXOrder::is_quantity_Set() const{ + return m_quantity_isSet; +} + +bool PFXOrder::is_quantity_Valid() const{ + return m_quantity_isValid; +} + +QDateTime PFXOrder::getShipDate() const { + return m_ship_date; +} +void PFXOrder::setShipDate(const QDateTime &ship_date) { + m_ship_date = ship_date; + m_ship_date_isSet = true; +} + +bool PFXOrder::is_ship_date_Set() const{ + return m_ship_date_isSet; +} + +bool PFXOrder::is_ship_date_Valid() const{ + return m_ship_date_isValid; +} + +QString PFXOrder::getStatus() const { + return m_status; +} +void PFXOrder::setStatus(const QString &status) { + m_status = status; + m_status_isSet = true; +} + +bool PFXOrder::is_status_Set() const{ + return m_status_isSet; +} + +bool PFXOrder::is_status_Valid() const{ + return m_status_isValid; +} + +bool PFXOrder::isComplete() const { + return m_complete; +} +void PFXOrder::setComplete(const bool &complete) { + m_complete = complete; + m_complete_isSet = true; +} + +bool PFXOrder::is_complete_Set() const{ + return m_complete_isSet; +} + +bool PFXOrder::is_complete_Valid() const{ + return m_complete_isValid; +} + +bool PFXOrder::isSet() const { + bool isObjectUpdated = false; + do { + if (m_id_isSet) { + isObjectUpdated = true; + break; + } + + if (m_pet_id_isSet) { + isObjectUpdated = true; + break; + } + + if (m_quantity_isSet) { + isObjectUpdated = true; + break; + } + + if (m_ship_date_isSet) { + isObjectUpdated = true; + break; + } + + if (m_status_isSet) { + isObjectUpdated = true; + break; + } + + if (m_complete_isSet) { + isObjectUpdated = true; + break; + } + } while (false); + return isObjectUpdated; +} + +bool PFXOrder::isValid() const { + // only required properties are required for the object to be considered valid + return true; +} + +} // namespace test_namespace diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXOrder.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXOrder.h new file mode 100644 index 000000000000..3d58afa70e30 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXOrder.h @@ -0,0 +1,107 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * PFXOrder.h + * + * An order for a pets from the pet store + */ + +#ifndef PFXOrder_H +#define PFXOrder_H + +#include + +#include +#include + +#include "PFXEnum.h" +#include "PFXObject.h" + +namespace test_namespace { + +class PFXOrder : public PFXObject { +public: + PFXOrder(); + PFXOrder(QString json); + ~PFXOrder() override; + + QString asJson() const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + qint64 getId() const; + void setId(const qint64 &id); + bool is_id_Set() const; + bool is_id_Valid() const; + + qint64 getPetId() const; + void setPetId(const qint64 &pet_id); + bool is_pet_id_Set() const; + bool is_pet_id_Valid() const; + + qint32 getQuantity() const; + void setQuantity(const qint32 &quantity); + bool is_quantity_Set() const; + bool is_quantity_Valid() const; + + QDateTime getShipDate() const; + void setShipDate(const QDateTime &ship_date); + bool is_ship_date_Set() const; + bool is_ship_date_Valid() const; + + QString getStatus() const; + void setStatus(const QString &status); + bool is_status_Set() const; + bool is_status_Valid() const; + + bool isComplete() const; + void setComplete(const bool &complete); + bool is_complete_Set() const; + bool is_complete_Valid() const; + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void initializeModel(); + + qint64 m_id; + bool m_id_isSet; + bool m_id_isValid; + + qint64 m_pet_id; + bool m_pet_id_isSet; + bool m_pet_id_isValid; + + qint32 m_quantity; + bool m_quantity_isSet; + bool m_quantity_isValid; + + QDateTime m_ship_date; + bool m_ship_date_isSet; + bool m_ship_date_isValid; + + QString m_status; + bool m_status_isSet; + bool m_status_isValid; + + bool m_complete; + bool m_complete_isSet; + bool m_complete_isValid; +}; + +} // namespace test_namespace + +Q_DECLARE_METATYPE(test_namespace::PFXOrder) + +#endif // PFXOrder_H diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPet.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPet.h index 93adfc59e1db..86395d417ac2 100644 --- a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPet.h +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPet.h @@ -68,10 +68,10 @@ class PFXPet : public PFXObject { bool is_tags_Set() const; bool is_tags_Valid() const; - Q_DECL_DEPRECATED QString getStatus() const; - Q_DECL_DEPRECATED void setStatus(const QString &status); - Q_DECL_DEPRECATED bool is_status_Set() const; - Q_DECL_DEPRECATED bool is_status_Valid() const; + QString getStatus() const; + void setStatus(const QString &status); + bool is_status_Set() const; + bool is_status_Valid() const; virtual bool isSet() const override; virtual bool isValid() const override; diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPetApi.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPetApi.cpp index 8d09108a9c61..23d73cd75acf 100644 --- a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPetApi.cpp +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPetApi.cpp @@ -37,6 +37,22 @@ void PFXPetApi::initializeServerConfigs() { QMap())); _serverConfigs.insert("addPet", defaultConf); _serverIndices.insert("addPet", 0); + _serverConfigs.insert("allPets", defaultConf); + _serverIndices.insert("allPets", 0); + _serverConfigs.insert("deletePet", defaultConf); + _serverIndices.insert("deletePet", 0); + _serverConfigs.insert("findPetsByStatus", defaultConf); + _serverIndices.insert("findPetsByStatus", 0); + _serverConfigs.insert("findPetsByTags", defaultConf); + _serverIndices.insert("findPetsByTags", 0); + _serverConfigs.insert("getPetById", defaultConf); + _serverIndices.insert("getPetById", 0); + _serverConfigs.insert("updatePet", defaultConf); + _serverIndices.insert("updatePet", 0); + _serverConfigs.insert("updatePetWithForm", defaultConf); + _serverIndices.insert("updatePetWithForm", 0); + _serverConfigs.insert("uploadFile", defaultConf); + _serverIndices.insert("uploadFile", 0); } /** @@ -271,12 +287,11 @@ void PFXPetApi::addPetCallback(PFXHttpRequestWorker *worker) { if (worker->error_type != QNetworkReply::NoError) { error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); } - PFXPet output(QString(worker->response)); worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - Q_EMIT addPetSignal(output); - Q_EMIT addPetSignalFull(worker, output); + Q_EMIT addPetSignal(); + Q_EMIT addPetSignalFull(worker); } else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){ connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable())); QStringList scope; @@ -305,7 +320,7 @@ void PFXPetApi::addPetCallback(PFXHttpRequestWorker *worker) { #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif - Q_EMIT addPetSignalE(output, error_type, error_str); + Q_EMIT addPetSignalE(error_type, error_str); Q_EMIT addPetSignalEFull(worker, error_type, error_str); #if defined(_MSC_VER) @@ -316,11 +331,1094 @@ void PFXPetApi::addPetCallback(PFXHttpRequestWorker *worker) { #pragma GCC diagnostic pop #endif - Q_EMIT addPetSignalError(output, error_type, error_str); + Q_EMIT addPetSignalError(error_type, error_str); Q_EMIT addPetSignalErrorFull(worker, error_type, error_str); } } +void PFXPetApi::allPets() { + QString fullPath = QString(_serverConfigs["allPets"][_serverIndices.value("allPets")].URL()+"/pet/all"); + + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "GET"); + + + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXPetApi::allPetsProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::allPetsCallback); + connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + + worker->execute(&input); +} + +void PFXPetApi::allPetsCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + QSet output; + QString json(worker->response); + QByteArray array(json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonArray jsonArray = doc.array(); + for (QJsonValue obj : jsonArray) { + PFXPet val; + ::test_namespace::fromJsonValue(val, obj); + output.insert(val); + } + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT allPetsSignal(output); + Q_EMIT allPetsSignalFull(worker, output); + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT allPetsSignalE(output, error_type, error_str); + Q_EMIT allPetsSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT allPetsSignalError(output, error_type, error_str); + Q_EMIT allPetsSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXPetApi::deletePet(const qint64 &pet_id, const ::test_namespace::OptionalParam &api_key) { + QString fullPath = QString(_serverConfigs["deletePet"][_serverIndices.value("deletePet")].URL()+"/pet/{petId}"); + + + { + QString pet_idPathParam("{"); + pet_idPathParam.append("petId").append("}"); + QString pathPrefix, pathSuffix, pathDelimiter; + QString pathStyle = "simple"; + if (pathStyle == "") + pathStyle = "simple"; + pathPrefix = getParamStylePrefix(pathStyle); + pathSuffix = getParamStyleSuffix(pathStyle); + pathDelimiter = getParamStyleDelimiter(pathStyle, "petId", false); + QString paramString = (pathStyle == "matrix") ? pathPrefix+"petId"+pathSuffix : pathPrefix; + fullPath.replace(pet_idPathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(pet_id))); + } + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "DELETE"); + + + if (api_key.hasValue()) + { + if (!::test_namespace::toStringValue(api_key.value()).isEmpty()) { + input.headers.insert("api_key", ::test_namespace::toStringValue(api_key.value())); + } + } + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXPetApi::deletePetProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::deletePetCallback); + connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + _OauthMethod = 1; + _implicitFlow.link(); + _passwordFlow.unlink(); + _authFlow.unlink(); + _credentialFlow.unlink(); + QStringList scope; + scope.append("write:pets"); + scope.append("read:pets"); + auto token = _implicitFlow.getToken(scope.join(" ")); + if(token.isValid()) + input.headers.insert("Authorization", "Bearer " + token.getToken()); + + _latestWorker = new PFXHttpRequestWorker(this, _manager); + _latestWorker->setTimeOut(_timeOut); + _latestWorker->setWorkingDirectory(_workingDirectory); + + connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::deletePetCallback); + connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); + connect(_latestWorker, &QObject::destroyed, [this](){ + if(findChildren().count() == 0){ + Q_EMIT allPendingRequestsCompleted(); + } + }); + + _latestInput = input; + _latestScope = scope; + + + + worker->execute(&input); +} + +void PFXPetApi::deletePetCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT deletePetSignal(); + Q_EMIT deletePetSignalFull(worker); + } else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){ + connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable())); + QStringList scope; + scope.append("write:pets"); + scope.append("read:pets"); + QString scopeStr = scope.join(" "); + QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog"); + //TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like + _implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId"); + Q_EMIT _implicitFlow.authenticationNeeded(); + + + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT deletePetSignalE(error_type, error_str); + Q_EMIT deletePetSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT deletePetSignalError(error_type, error_str); + Q_EMIT deletePetSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXPetApi::findPetsByStatus(const QList &status) { + QString fullPath = QString(_serverConfigs["findPetsByStatus"][_serverIndices.value("findPetsByStatus")].URL()+"/pet/findByStatus"); + + QString queryPrefix, querySuffix, queryDelimiter, queryStyle; + + { + queryStyle = "form"; + if (queryStyle == "") + queryStyle = "form"; + queryPrefix = getParamStylePrefix(queryStyle); + querySuffix = getParamStyleSuffix(queryStyle); + queryDelimiter = getParamStyleDelimiter(queryStyle, "status", false); + if (status.size() > 0) { + if (QString("csv").indexOf("multi") == 0) { + for (QString t : status) { + if (fullPath.indexOf("?") > 0) + fullPath.append(queryPrefix); + else + fullPath.append("?"); + fullPath.append("status=").append(::test_namespace::toStringValue(t)); + } + } else if (QString("csv").indexOf("ssv") == 0) { + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?").append(queryPrefix).append("status").append(querySuffix); + qint32 count = 0; + for (QString t : status) { + if (count > 0) { + fullPath.append((false)? queryDelimiter : QUrl::toPercentEncoding(queryDelimiter)); + } + fullPath.append(::test_namespace::toStringValue(t)); + count++; + } + } else if (QString("csv").indexOf("tsv") == 0) { + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?").append(queryPrefix).append("status").append(querySuffix); + qint32 count = 0; + for (QString t : status) { + if (count > 0) { + fullPath.append("\t"); + } + fullPath.append(::test_namespace::toStringValue(t)); + count++; + } + } else if (QString("csv").indexOf("csv") == 0) { + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?").append(queryPrefix).append("status").append(querySuffix); + qint32 count = 0; + for (QString t : status) { + if (count > 0) { + fullPath.append(queryDelimiter); + } + fullPath.append(::test_namespace::toStringValue(t)); + count++; + } + } else if (QString("csv").indexOf("pipes") == 0) { + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?").append(queryPrefix).append("status").append(querySuffix); + qint32 count = 0; + for (QString t : status) { + if (count > 0) { + fullPath.append(queryDelimiter); + } + fullPath.append(::test_namespace::toStringValue(t)); + count++; + } + } else if (QString("csv").indexOf("deepObject") == 0) { + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?").append(queryPrefix).append("status").append(querySuffix); + qint32 count = 0; + for (QString t : status) { + if (count > 0) { + fullPath.append(queryDelimiter); + } + fullPath.append(::test_namespace::toStringValue(t)); + count++; + } + } + } + } + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "GET"); + + + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXPetApi::findPetsByStatusProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::findPetsByStatusCallback); + connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + _OauthMethod = 1; + _implicitFlow.link(); + _passwordFlow.unlink(); + _authFlow.unlink(); + _credentialFlow.unlink(); + QStringList scope; + scope.append("write:pets"); + scope.append("read:pets"); + auto token = _implicitFlow.getToken(scope.join(" ")); + if(token.isValid()) + input.headers.insert("Authorization", "Bearer " + token.getToken()); + + _latestWorker = new PFXHttpRequestWorker(this, _manager); + _latestWorker->setTimeOut(_timeOut); + _latestWorker->setWorkingDirectory(_workingDirectory); + + connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::findPetsByStatusCallback); + connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); + connect(_latestWorker, &QObject::destroyed, [this](){ + if(findChildren().count() == 0){ + Q_EMIT allPendingRequestsCompleted(); + } + }); + + _latestInput = input; + _latestScope = scope; + + + + worker->execute(&input); +} + +void PFXPetApi::findPetsByStatusCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + QList output; + QString json(worker->response); + QByteArray array(json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonArray jsonArray = doc.array(); + for (QJsonValue obj : jsonArray) { + PFXPet val; + ::test_namespace::fromJsonValue(val, obj); + output.append(val); + } + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT findPetsByStatusSignal(output); + Q_EMIT findPetsByStatusSignalFull(worker, output); + } else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){ + connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable())); + QStringList scope; + scope.append("write:pets"); + scope.append("read:pets"); + QString scopeStr = scope.join(" "); + QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog"); + //TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like + _implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId"); + Q_EMIT _implicitFlow.authenticationNeeded(); + + + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT findPetsByStatusSignalE(output, error_type, error_str); + Q_EMIT findPetsByStatusSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT findPetsByStatusSignalError(output, error_type, error_str); + Q_EMIT findPetsByStatusSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXPetApi::findPetsByTags(const QList &tags) { + QString fullPath = QString(_serverConfigs["findPetsByTags"][_serverIndices.value("findPetsByTags")].URL()+"/pet/findByTags"); + + QString queryPrefix, querySuffix, queryDelimiter, queryStyle; + + { + queryStyle = "form"; + if (queryStyle == "") + queryStyle = "form"; + queryPrefix = getParamStylePrefix(queryStyle); + querySuffix = getParamStyleSuffix(queryStyle); + queryDelimiter = getParamStyleDelimiter(queryStyle, "tags", false); + if (tags.size() > 0) { + if (QString("csv").indexOf("multi") == 0) { + for (QString t : tags) { + if (fullPath.indexOf("?") > 0) + fullPath.append(queryPrefix); + else + fullPath.append("?"); + fullPath.append("tags=").append(::test_namespace::toStringValue(t)); + } + } else if (QString("csv").indexOf("ssv") == 0) { + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?").append(queryPrefix).append("tags").append(querySuffix); + qint32 count = 0; + for (QString t : tags) { + if (count > 0) { + fullPath.append((false)? queryDelimiter : QUrl::toPercentEncoding(queryDelimiter)); + } + fullPath.append(::test_namespace::toStringValue(t)); + count++; + } + } else if (QString("csv").indexOf("tsv") == 0) { + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?").append(queryPrefix).append("tags").append(querySuffix); + qint32 count = 0; + for (QString t : tags) { + if (count > 0) { + fullPath.append("\t"); + } + fullPath.append(::test_namespace::toStringValue(t)); + count++; + } + } else if (QString("csv").indexOf("csv") == 0) { + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?").append(queryPrefix).append("tags").append(querySuffix); + qint32 count = 0; + for (QString t : tags) { + if (count > 0) { + fullPath.append(queryDelimiter); + } + fullPath.append(::test_namespace::toStringValue(t)); + count++; + } + } else if (QString("csv").indexOf("pipes") == 0) { + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?").append(queryPrefix).append("tags").append(querySuffix); + qint32 count = 0; + for (QString t : tags) { + if (count > 0) { + fullPath.append(queryDelimiter); + } + fullPath.append(::test_namespace::toStringValue(t)); + count++; + } + } else if (QString("csv").indexOf("deepObject") == 0) { + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?").append(queryPrefix).append("tags").append(querySuffix); + qint32 count = 0; + for (QString t : tags) { + if (count > 0) { + fullPath.append(queryDelimiter); + } + fullPath.append(::test_namespace::toStringValue(t)); + count++; + } + } + } + } + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "GET"); + + + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXPetApi::findPetsByTagsProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::findPetsByTagsCallback); + connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + _OauthMethod = 1; + _implicitFlow.link(); + _passwordFlow.unlink(); + _authFlow.unlink(); + _credentialFlow.unlink(); + QStringList scope; + scope.append("write:pets"); + scope.append("read:pets"); + auto token = _implicitFlow.getToken(scope.join(" ")); + if(token.isValid()) + input.headers.insert("Authorization", "Bearer " + token.getToken()); + + _latestWorker = new PFXHttpRequestWorker(this, _manager); + _latestWorker->setTimeOut(_timeOut); + _latestWorker->setWorkingDirectory(_workingDirectory); + + connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::findPetsByTagsCallback); + connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); + connect(_latestWorker, &QObject::destroyed, [this](){ + if(findChildren().count() == 0){ + Q_EMIT allPendingRequestsCompleted(); + } + }); + + _latestInput = input; + _latestScope = scope; + + + + worker->execute(&input); +} + +void PFXPetApi::findPetsByTagsCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + QList output; + QString json(worker->response); + QByteArray array(json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonArray jsonArray = doc.array(); + for (QJsonValue obj : jsonArray) { + PFXPet val; + ::test_namespace::fromJsonValue(val, obj); + output.append(val); + } + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT findPetsByTagsSignal(output); + Q_EMIT findPetsByTagsSignalFull(worker, output); + } else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){ + connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable())); + QStringList scope; + scope.append("write:pets"); + scope.append("read:pets"); + QString scopeStr = scope.join(" "); + QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog"); + //TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like + _implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId"); + Q_EMIT _implicitFlow.authenticationNeeded(); + + + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT findPetsByTagsSignalE(output, error_type, error_str); + Q_EMIT findPetsByTagsSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT findPetsByTagsSignalError(output, error_type, error_str); + Q_EMIT findPetsByTagsSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXPetApi::getPetById(const qint64 &pet_id) { + QString fullPath = QString(_serverConfigs["getPetById"][_serverIndices.value("getPetById")].URL()+"/pet/{petId}"); + + if (_apiKeys.contains("api_key")) { + addHeaders("api_key",_apiKeys.find("api_key").value()); + } + + + { + QString pet_idPathParam("{"); + pet_idPathParam.append("petId").append("}"); + QString pathPrefix, pathSuffix, pathDelimiter; + QString pathStyle = "simple"; + if (pathStyle == "") + pathStyle = "simple"; + pathPrefix = getParamStylePrefix(pathStyle); + pathSuffix = getParamStyleSuffix(pathStyle); + pathDelimiter = getParamStyleDelimiter(pathStyle, "petId", false); + QString paramString = (pathStyle == "matrix") ? pathPrefix+"petId"+pathSuffix : pathPrefix; + fullPath.replace(pet_idPathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(pet_id))); + } + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "GET"); + + + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXPetApi::getPetByIdProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::getPetByIdCallback); + connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + + worker->execute(&input); +} + +void PFXPetApi::getPetByIdCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + PFXPet output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT getPetByIdSignal(output); + Q_EMIT getPetByIdSignalFull(worker, output); + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT getPetByIdSignalE(output, error_type, error_str); + Q_EMIT getPetByIdSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT getPetByIdSignalError(output, error_type, error_str); + Q_EMIT getPetByIdSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXPetApi::updatePet(const PFXPet &pfx_pet) { + QString fullPath = QString(_serverConfigs["updatePet"][_serverIndices.value("updatePet")].URL()+"/pet"); + + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "PUT"); + + { + + + QByteArray output = pfx_pet.asJson().toUtf8(); + input.request_body.append(output); + } + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXPetApi::updatePetProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::updatePetCallback); + connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + _OauthMethod = 1; + _implicitFlow.link(); + _passwordFlow.unlink(); + _authFlow.unlink(); + _credentialFlow.unlink(); + QStringList scope; + scope.append("write:pets"); + scope.append("read:pets"); + auto token = _implicitFlow.getToken(scope.join(" ")); + if(token.isValid()) + input.headers.insert("Authorization", "Bearer " + token.getToken()); + + _latestWorker = new PFXHttpRequestWorker(this, _manager); + _latestWorker->setTimeOut(_timeOut); + _latestWorker->setWorkingDirectory(_workingDirectory); + + connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::updatePetCallback); + connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); + connect(_latestWorker, &QObject::destroyed, [this](){ + if(findChildren().count() == 0){ + Q_EMIT allPendingRequestsCompleted(); + } + }); + + _latestInput = input; + _latestScope = scope; + + + + worker->execute(&input); +} + +void PFXPetApi::updatePetCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT updatePetSignal(); + Q_EMIT updatePetSignalFull(worker); + } else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){ + connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable())); + QStringList scope; + scope.append("write:pets"); + scope.append("read:pets"); + QString scopeStr = scope.join(" "); + QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog"); + //TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like + _implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId"); + Q_EMIT _implicitFlow.authenticationNeeded(); + + + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT updatePetSignalE(error_type, error_str); + Q_EMIT updatePetSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT updatePetSignalError(error_type, error_str); + Q_EMIT updatePetSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXPetApi::updatePetWithForm(const qint64 &pet_id, const ::test_namespace::OptionalParam &name, const ::test_namespace::OptionalParam &status) { + QString fullPath = QString(_serverConfigs["updatePetWithForm"][_serverIndices.value("updatePetWithForm")].URL()+"/pet/{petId}"); + + + { + QString pet_idPathParam("{"); + pet_idPathParam.append("petId").append("}"); + QString pathPrefix, pathSuffix, pathDelimiter; + QString pathStyle = "simple"; + if (pathStyle == "") + pathStyle = "simple"; + pathPrefix = getParamStylePrefix(pathStyle); + pathSuffix = getParamStyleSuffix(pathStyle); + pathDelimiter = getParamStyleDelimiter(pathStyle, "petId", false); + QString paramString = (pathStyle == "matrix") ? pathPrefix+"petId"+pathSuffix : pathPrefix; + fullPath.replace(pet_idPathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(pet_id))); + } + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "POST"); + + if (name.hasValue()) + { + input.add_var("name", ::test_namespace::toStringValue(name.value())); + } + if (status.hasValue()) + { + input.add_var("status", ::test_namespace::toStringValue(status.value())); + } + + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXPetApi::updatePetWithFormProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::updatePetWithFormCallback); + connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + _OauthMethod = 1; + _implicitFlow.link(); + _passwordFlow.unlink(); + _authFlow.unlink(); + _credentialFlow.unlink(); + QStringList scope; + scope.append("write:pets"); + scope.append("read:pets"); + auto token = _implicitFlow.getToken(scope.join(" ")); + if(token.isValid()) + input.headers.insert("Authorization", "Bearer " + token.getToken()); + + _latestWorker = new PFXHttpRequestWorker(this, _manager); + _latestWorker->setTimeOut(_timeOut); + _latestWorker->setWorkingDirectory(_workingDirectory); + + connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::updatePetWithFormCallback); + connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); + connect(_latestWorker, &QObject::destroyed, [this](){ + if(findChildren().count() == 0){ + Q_EMIT allPendingRequestsCompleted(); + } + }); + + _latestInput = input; + _latestScope = scope; + + + + worker->execute(&input); +} + +void PFXPetApi::updatePetWithFormCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT updatePetWithFormSignal(); + Q_EMIT updatePetWithFormSignalFull(worker); + } else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){ + connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable())); + QStringList scope; + scope.append("write:pets"); + scope.append("read:pets"); + QString scopeStr = scope.join(" "); + QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog"); + //TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like + _implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId"); + Q_EMIT _implicitFlow.authenticationNeeded(); + + + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT updatePetWithFormSignalE(error_type, error_str); + Q_EMIT updatePetWithFormSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT updatePetWithFormSignalError(error_type, error_str); + Q_EMIT updatePetWithFormSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXPetApi::uploadFile(const qint64 &pet_id, const ::test_namespace::OptionalParam &additional_metadata, const ::test_namespace::OptionalParam &file) { + QString fullPath = QString(_serverConfigs["uploadFile"][_serverIndices.value("uploadFile")].URL()+"/pet/{petId}/uploadImage"); + + + { + QString pet_idPathParam("{"); + pet_idPathParam.append("petId").append("}"); + QString pathPrefix, pathSuffix, pathDelimiter; + QString pathStyle = "simple"; + if (pathStyle == "") + pathStyle = "simple"; + pathPrefix = getParamStylePrefix(pathStyle); + pathSuffix = getParamStyleSuffix(pathStyle); + pathDelimiter = getParamStyleDelimiter(pathStyle, "petId", false); + QString paramString = (pathStyle == "matrix") ? pathPrefix+"petId"+pathSuffix : pathPrefix; + fullPath.replace(pet_idPathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(pet_id))); + } + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "POST"); + + if (additional_metadata.hasValue()) + { + input.add_var("additionalMetadata", ::test_namespace::toStringValue(additional_metadata.value())); + } + if (file.hasValue()) + { + input.add_file("file", file.value().local_filename, file.value().request_filename, file.value().mime_type); + } + + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXPetApi::uploadFileProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::uploadFileCallback); + connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + _OauthMethod = 1; + _implicitFlow.link(); + _passwordFlow.unlink(); + _authFlow.unlink(); + _credentialFlow.unlink(); + QStringList scope; + scope.append("write:pets"); + scope.append("read:pets"); + auto token = _implicitFlow.getToken(scope.join(" ")); + if(token.isValid()) + input.headers.insert("Authorization", "Bearer " + token.getToken()); + + _latestWorker = new PFXHttpRequestWorker(this, _manager); + _latestWorker->setTimeOut(_timeOut); + _latestWorker->setWorkingDirectory(_workingDirectory); + + connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::uploadFileCallback); + connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); + connect(_latestWorker, &QObject::destroyed, [this](){ + if(findChildren().count() == 0){ + Q_EMIT allPendingRequestsCompleted(); + } + }); + + _latestInput = input; + _latestScope = scope; + + + + worker->execute(&input); +} + +void PFXPetApi::uploadFileCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + PFXApiResponse output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT uploadFileSignal(output); + Q_EMIT uploadFileSignalFull(worker, output); + } else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){ + connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable())); + QStringList scope; + scope.append("write:pets"); + scope.append("read:pets"); + QString scopeStr = scope.join(" "); + QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog"); + //TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like + _implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId"); + Q_EMIT _implicitFlow.authenticationNeeded(); + + + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT uploadFileSignalE(output, error_type, error_str); + Q_EMIT uploadFileSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT uploadFileSignalError(output, error_type, error_str); + Q_EMIT uploadFileSignalErrorFull(worker, error_type, error_str); + } +} + void PFXPetApi::tokenAvailable(){ oauthToken token; diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPetApi.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPetApi.h index f096872e95b8..e2688c5b9d30 100644 --- a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPetApi.h +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPetApi.h @@ -17,7 +17,10 @@ #include "PFXServerConfiguration.h" #include "PFXOauth.h" +#include "PFXApiResponse.h" +#include "PFXHttpFileElement.h" #include "PFXPet.h" +#include #include #include @@ -62,6 +65,49 @@ class PFXPetApi : public QObject { void addPet(const PFXPet &pfx_pet); + void allPets(); + + /** + * @param[in] pet_id qint64 [required] + * @param[in] api_key QString [optional] + */ + void deletePet(const qint64 &pet_id, const ::test_namespace::OptionalParam &api_key = ::test_namespace::OptionalParam()); + + /** + * @param[in] status QList [required] + */ + void findPetsByStatus(const QList &status); + + /** + * @param[in] tags QList [required] + */ + Q_DECL_DEPRECATED void findPetsByTags(const QList &tags); + + /** + * @param[in] pet_id qint64 [required] + */ + void getPetById(const qint64 &pet_id); + + /** + * @param[in] pfx_pet PFXPet [required] + */ + void updatePet(const PFXPet &pfx_pet); + + /** + * @param[in] pet_id qint64 [required] + * @param[in] name QString [optional] + * @param[in] status QString [optional] + */ + void updatePetWithForm(const qint64 &pet_id, const ::test_namespace::OptionalParam &name = ::test_namespace::OptionalParam(), const ::test_namespace::OptionalParam &status = ::test_namespace::OptionalParam()); + + /** + * @param[in] pet_id qint64 [required] + * @param[in] additional_metadata QString [optional] + * @param[in] file PFXHttpFileElement [optional] + */ + void uploadFile(const qint64 &pet_id, const ::test_namespace::OptionalParam &additional_metadata = ::test_namespace::OptionalParam(), const ::test_namespace::OptionalParam &file = ::test_namespace::OptionalParam()); + + private: QMap _serverIndices; QMap> _serverConfigs; @@ -85,22 +131,102 @@ class PFXPetApi : public QObject { int _OauthMethod = 0; void addPetCallback(PFXHttpRequestWorker *worker); + void allPetsCallback(PFXHttpRequestWorker *worker); + void deletePetCallback(PFXHttpRequestWorker *worker); + void findPetsByStatusCallback(PFXHttpRequestWorker *worker); + void findPetsByTagsCallback(PFXHttpRequestWorker *worker); + void getPetByIdCallback(PFXHttpRequestWorker *worker); + void updatePetCallback(PFXHttpRequestWorker *worker); + void updatePetWithFormCallback(PFXHttpRequestWorker *worker); + void uploadFileCallback(PFXHttpRequestWorker *worker); Q_SIGNALS: - void addPetSignal(PFXPet summary); + void addPetSignal(); + void allPetsSignal(QSet summary); + void deletePetSignal(); + void findPetsByStatusSignal(QList summary); + void findPetsByTagsSignal(QList summary); + void getPetByIdSignal(PFXPet summary); + void updatePetSignal(); + void updatePetWithFormSignal(); + void uploadFileSignal(PFXApiResponse summary); void addPetProgress(qint64 bytesReceived, qint64 bytesTotal); - - void addPetSignalFull(PFXHttpRequestWorker *worker, PFXPet summary); + void allPetsProgress(qint64 bytesReceived, qint64 bytesTotal); + void deletePetProgress(qint64 bytesReceived, qint64 bytesTotal); + void findPetsByStatusProgress(qint64 bytesReceived, qint64 bytesTotal); + void findPetsByTagsProgress(qint64 bytesReceived, qint64 bytesTotal); + void getPetByIdProgress(qint64 bytesReceived, qint64 bytesTotal); + void updatePetProgress(qint64 bytesReceived, qint64 bytesTotal); + void updatePetWithFormProgress(qint64 bytesReceived, qint64 bytesTotal); + void uploadFileProgress(qint64 bytesReceived, qint64 bytesTotal); + + void addPetSignalFull(PFXHttpRequestWorker *worker); + void allPetsSignalFull(PFXHttpRequestWorker *worker, QSet summary); + void deletePetSignalFull(PFXHttpRequestWorker *worker); + void findPetsByStatusSignalFull(PFXHttpRequestWorker *worker, QList summary); + void findPetsByTagsSignalFull(PFXHttpRequestWorker *worker, QList summary); + void getPetByIdSignalFull(PFXHttpRequestWorker *worker, PFXPet summary); + void updatePetSignalFull(PFXHttpRequestWorker *worker); + void updatePetWithFormSignalFull(PFXHttpRequestWorker *worker); + void uploadFileSignalFull(PFXHttpRequestWorker *worker, PFXApiResponse summary); Q_DECL_DEPRECATED_X("Use addPetSignalError() instead") - void addPetSignalE(PFXPet summary, QNetworkReply::NetworkError error_type, QString error_str); - void addPetSignalError(PFXPet summary, QNetworkReply::NetworkError error_type, const QString &error_str); + void addPetSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void addPetSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use allPetsSignalError() instead") + void allPetsSignalE(QSet summary, QNetworkReply::NetworkError error_type, QString error_str); + void allPetsSignalError(QSet summary, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use deletePetSignalError() instead") + void deletePetSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void deletePetSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use findPetsByStatusSignalError() instead") + void findPetsByStatusSignalE(QList summary, QNetworkReply::NetworkError error_type, QString error_str); + void findPetsByStatusSignalError(QList summary, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use findPetsByTagsSignalError() instead") + void findPetsByTagsSignalE(QList summary, QNetworkReply::NetworkError error_type, QString error_str); + void findPetsByTagsSignalError(QList summary, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use getPetByIdSignalError() instead") + void getPetByIdSignalE(PFXPet summary, QNetworkReply::NetworkError error_type, QString error_str); + void getPetByIdSignalError(PFXPet summary, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use updatePetSignalError() instead") + void updatePetSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void updatePetSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use updatePetWithFormSignalError() instead") + void updatePetWithFormSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void updatePetWithFormSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use uploadFileSignalError() instead") + void uploadFileSignalE(PFXApiResponse summary, QNetworkReply::NetworkError error_type, QString error_str); + void uploadFileSignalError(PFXApiResponse summary, QNetworkReply::NetworkError error_type, const QString &error_str); Q_DECL_DEPRECATED_X("Use addPetSignalErrorFull() instead") void addPetSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); void addPetSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use allPetsSignalErrorFull() instead") + void allPetsSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void allPetsSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use deletePetSignalErrorFull() instead") + void deletePetSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void deletePetSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use findPetsByStatusSignalErrorFull() instead") + void findPetsByStatusSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void findPetsByStatusSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use findPetsByTagsSignalErrorFull() instead") + void findPetsByTagsSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void findPetsByTagsSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use getPetByIdSignalErrorFull() instead") + void getPetByIdSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void getPetByIdSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use updatePetSignalErrorFull() instead") + void updatePetSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void updatePetSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use updatePetWithFormSignalErrorFull() instead") + void updatePetWithFormSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void updatePetWithFormSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use uploadFileSignalErrorFull() instead") + void uploadFileSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void uploadFileSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); void abortRequestsSignal(); void allPendingRequestsCompleted(); diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPrimitivesApi.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPrimitivesApi.cpp new file mode 100644 index 000000000000..5bf3ba3b3eb7 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPrimitivesApi.cpp @@ -0,0 +1,406 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "PFXPrimitivesApi.h" +#include "PFXServerConfiguration.h" +#include +#include + +namespace test_namespace { + +PFXPrimitivesApi::PFXPrimitivesApi(const int timeOut) + : _timeOut(timeOut), + _manager(nullptr), + _isResponseCompressionEnabled(false), + _isRequestCompressionEnabled(false) { + initializeServerConfigs(); +} + +PFXPrimitivesApi::~PFXPrimitivesApi() { +} + +void PFXPrimitivesApi::initializeServerConfigs() { + //Default server + QList defaultConf = QList(); + //varying endpoint server + defaultConf.append(PFXServerConfiguration( + QUrl("http://petstore.swagger.io/v2"), + "No description provided", + QMap())); + _serverConfigs.insert("primitivesIntegerPost", defaultConf); + _serverIndices.insert("primitivesIntegerPost", 0); + _serverConfigs.insert("primitivesNumberPut", defaultConf); + _serverIndices.insert("primitivesNumberPut", 0); +} + +/** +* returns 0 on success and -1, -2 or -3 on failure. +* -1 when the variable does not exist and -2 if the value is not defined in the enum and -3 if the operation or server index is not found +*/ +int PFXPrimitivesApi::setDefaultServerValue(int serverIndex, const QString &operation, const QString &variable, const QString &value) { + auto it = _serverConfigs.find(operation); + if (it != _serverConfigs.end() && serverIndex < it.value().size()) { + return _serverConfigs[operation][serverIndex].setDefaultValue(variable,value); + } + return -3; +} +void PFXPrimitivesApi::setServerIndex(const QString &operation, int serverIndex) { + if (_serverIndices.contains(operation) && serverIndex < _serverConfigs.find(operation).value().size()) { + _serverIndices[operation] = serverIndex; + } +} + +void PFXPrimitivesApi::setApiKey(const QString &apiKeyName, const QString &apiKey) { + _apiKeys.insert(apiKeyName, apiKey); +} + +void PFXPrimitivesApi::setBearerToken(const QString &token) { + _bearerToken = token; +} + +void PFXPrimitivesApi::setUsername(const QString &username) { + _username = username; +} + +void PFXPrimitivesApi::setPassword(const QString &password) { + _password = password; +} + + +void PFXPrimitivesApi::setTimeOut(const int timeOut) { + _timeOut = timeOut; +} + +void PFXPrimitivesApi::setWorkingDirectory(const QString &path) { + _workingDirectory = path; +} + +void PFXPrimitivesApi::setNetworkAccessManager(QNetworkAccessManager* manager) { + _manager = manager; +} + +/** + * Appends a new ServerConfiguration to the config map for a specific operation. + * @param operation The id to the target operation. + * @param url A string that contains the URL of the server + * @param description A String that describes the server + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + * returns the index of the new server config on success and -1 if the operation is not found + */ +int PFXPrimitivesApi::addServerConfiguration(const QString &operation, const QUrl &url, const QString &description, const QMap &variables) { + if (_serverConfigs.contains(operation)) { + _serverConfigs[operation].append(PFXServerConfiguration( + url, + description, + variables)); + return _serverConfigs[operation].size()-1; + } else { + return -1; + } +} + +/** + * Appends a new ServerConfiguration to the config map for a all operations and sets the index to that server. + * @param url A string that contains the URL of the server + * @param description A String that describes the server + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ +void PFXPrimitivesApi::setNewServerForAllOperations(const QUrl &url, const QString &description, const QMap &variables) { + for (auto keyIt = _serverIndices.keyBegin(); keyIt != _serverIndices.keyEnd(); keyIt++) { + setServerIndex(*keyIt, addServerConfiguration(*keyIt, url, description, variables)); + } +} + +/** + * Appends a new ServerConfiguration to the config map for an operations and sets the index to that server. + * @param URL A string that contains the URL of the server + * @param description A String that describes the server + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ +void PFXPrimitivesApi::setNewServer(const QString &operation, const QUrl &url, const QString &description, const QMap &variables) { + setServerIndex(operation, addServerConfiguration(operation, url, description, variables)); +} + +void PFXPrimitivesApi::addHeaders(const QString &key, const QString &value) { + _defaultHeaders.insert(key, value); +} + +void PFXPrimitivesApi::enableRequestCompression() { + _isRequestCompressionEnabled = true; +} + +void PFXPrimitivesApi::enableResponseCompression() { + _isResponseCompressionEnabled = true; +} + +void PFXPrimitivesApi::abortRequests() { + Q_EMIT abortRequestsSignal(); +} + +QString PFXPrimitivesApi::getParamStylePrefix(const QString &style) { + if (style == "matrix") { + return ";"; + } else if (style == "label") { + return "."; + } else if (style == "form") { + return "&"; + } else if (style == "simple") { + return ""; + } else if (style == "spaceDelimited") { + return "&"; + } else if (style == "pipeDelimited") { + return "&"; + } else { + return "none"; + } +} + +QString PFXPrimitivesApi::getParamStyleSuffix(const QString &style) { + if (style == "matrix") { + return "="; + } else if (style == "label") { + return ""; + } else if (style == "form") { + return "="; + } else if (style == "simple") { + return ""; + } else if (style == "spaceDelimited") { + return "="; + } else if (style == "pipeDelimited") { + return "="; + } else { + return "none"; + } +} + +QString PFXPrimitivesApi::getParamStyleDelimiter(const QString &style, const QString &name, bool isExplode) { + + if (style == "matrix") { + return (isExplode) ? ";" + name + "=" : ","; + + } else if (style == "label") { + return (isExplode) ? "." : ","; + + } else if (style == "form") { + return (isExplode) ? "&" + name + "=" : ","; + + } else if (style == "simple") { + return ","; + } else if (style == "spaceDelimited") { + return (isExplode) ? "&" + name + "=" : " "; + + } else if (style == "pipeDelimited") { + return (isExplode) ? "&" + name + "=" : "|"; + + } else if (style == "deepObject") { + return (isExplode) ? "&" : "none"; + + } else { + return "none"; + } +} + +void PFXPrimitivesApi::primitivesIntegerPost(const ::test_namespace::OptionalParam &body) { + QString fullPath = QString(_serverConfigs["primitivesIntegerPost"][_serverIndices.value("primitivesIntegerPost")].URL()+"/primitives/integer"); + + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "POST"); + + if (body.hasValue()){ + + QByteArray output = QByteArray::number(body.value()); + input.request_body.append(output); + } + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXPrimitivesApi::primitivesIntegerPostProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPrimitivesApi::primitivesIntegerPostCallback); + connect(this, &PFXPrimitivesApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + + worker->execute(&input); +} + +void PFXPrimitivesApi::primitivesIntegerPostCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT primitivesIntegerPostSignal(); + Q_EMIT primitivesIntegerPostSignalFull(worker); + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT primitivesIntegerPostSignalE(error_type, error_str); + Q_EMIT primitivesIntegerPostSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT primitivesIntegerPostSignalError(error_type, error_str); + Q_EMIT primitivesIntegerPostSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXPrimitivesApi::primitivesNumberPut(const ::test_namespace::OptionalParam &body) { + QString fullPath = QString(_serverConfigs["primitivesNumberPut"][_serverIndices.value("primitivesNumberPut")].URL()+"/primitives/number"); + + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "PUT"); + + if (body.hasValue()){ + + QByteArray output = QByteArray::number(body.value()); + input.request_body.append(output); + } + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXPrimitivesApi::primitivesNumberPutProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPrimitivesApi::primitivesNumberPutCallback); + connect(this, &PFXPrimitivesApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + + worker->execute(&input); +} + +void PFXPrimitivesApi::primitivesNumberPutCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT primitivesNumberPutSignal(); + Q_EMIT primitivesNumberPutSignalFull(worker); + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT primitivesNumberPutSignalE(error_type, error_str); + Q_EMIT primitivesNumberPutSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT primitivesNumberPutSignalError(error_type, error_str); + Q_EMIT primitivesNumberPutSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXPrimitivesApi::tokenAvailable(){ + + oauthToken token; + switch (_OauthMethod) { + case 1: //implicit flow + token = _implicitFlow.getToken(_latestScope.join(" ")); + if(token.isValid()){ + _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); + _latestWorker->execute(&_latestInput); + }else{ + _implicitFlow.removeToken(_latestScope.join(" ")); + qDebug() << "Could not retrieve a valid token"; + } + break; + case 2: //authorization flow + token = _authFlow.getToken(_latestScope.join(" ")); + if(token.isValid()){ + _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); + _latestWorker->execute(&_latestInput); + }else{ + _authFlow.removeToken(_latestScope.join(" ")); + qDebug() << "Could not retrieve a valid token"; + } + break; + case 3: //client credentials flow + token = _credentialFlow.getToken(_latestScope.join(" ")); + if(token.isValid()){ + _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); + _latestWorker->execute(&_latestInput); + }else{ + _credentialFlow.removeToken(_latestScope.join(" ")); + qDebug() << "Could not retrieve a valid token"; + } + break; + case 4: //resource owner password flow + token = _passwordFlow.getToken(_latestScope.join(" ")); + if(token.isValid()){ + _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); + _latestWorker->execute(&_latestInput); + }else{ + _credentialFlow.removeToken(_latestScope.join(" ")); + qDebug() << "Could not retrieve a valid token"; + } + break; + default: + qDebug() << "No Oauth method set!"; + break; + } +} +} // namespace test_namespace diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPrimitivesApi.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPrimitivesApi.h new file mode 100644 index 000000000000..722ef1746b55 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXPrimitivesApi.h @@ -0,0 +1,127 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#ifndef PFX_PFXPrimitivesApi_H +#define PFX_PFXPrimitivesApi_H + +#include "PFXHelpers.h" +#include "PFXHttpRequest.h" +#include "PFXServerConfiguration.h" +#include "PFXOauth.h" + +#include + +#include +#include +#include +#include +#include + +namespace test_namespace { + +class PFXPrimitivesApi : public QObject { + Q_OBJECT + +public: + PFXPrimitivesApi(const int timeOut = 0); + ~PFXPrimitivesApi(); + + void initializeServerConfigs(); + int setDefaultServerValue(int serverIndex,const QString &operation, const QString &variable,const QString &val); + void setServerIndex(const QString &operation, int serverIndex); + void setApiKey(const QString &apiKeyName, const QString &apiKey); + void setBearerToken(const QString &token); + void setUsername(const QString &username); + void setPassword(const QString &password); + void setTimeOut(const int timeOut); + void setWorkingDirectory(const QString &path); + void setNetworkAccessManager(QNetworkAccessManager* manager); + int addServerConfiguration(const QString &operation, const QUrl &url, const QString &description = "", const QMap &variables = QMap()); + void setNewServerForAllOperations(const QUrl &url, const QString &description = "", const QMap &variables = QMap()); + void setNewServer(const QString &operation, const QUrl &url, const QString &description = "", const QMap &variables = QMap()); + void addHeaders(const QString &key, const QString &value); + void enableRequestCompression(); + void enableResponseCompression(); + void abortRequests(); + QString getParamStylePrefix(const QString &style); + QString getParamStyleSuffix(const QString &style); + QString getParamStyleDelimiter(const QString &style, const QString &name, bool isExplode); + + /** + * @param[in] body qint32 [optional] + */ + void primitivesIntegerPost(const ::test_namespace::OptionalParam &body = ::test_namespace::OptionalParam()); + + /** + * @param[in] body double [optional] + */ + void primitivesNumberPut(const ::test_namespace::OptionalParam &body = ::test_namespace::OptionalParam()); + + +private: + QMap _serverIndices; + QMap> _serverConfigs; + QMap _apiKeys; + QString _bearerToken; + QString _username; + QString _password; + int _timeOut; + QString _workingDirectory; + QNetworkAccessManager* _manager; + QMap _defaultHeaders; + bool _isResponseCompressionEnabled; + bool _isRequestCompressionEnabled; + PFXHttpRequestInput _latestInput; + PFXHttpRequestWorker *_latestWorker; + QStringList _latestScope; + OauthCode _authFlow; + OauthImplicit _implicitFlow; + OauthCredentials _credentialFlow; + OauthPassword _passwordFlow; + int _OauthMethod = 0; + + void primitivesIntegerPostCallback(PFXHttpRequestWorker *worker); + void primitivesNumberPutCallback(PFXHttpRequestWorker *worker); + +Q_SIGNALS: + + void primitivesIntegerPostSignal(); + void primitivesNumberPutSignal(); + + void primitivesIntegerPostProgress(qint64 bytesReceived, qint64 bytesTotal); + void primitivesNumberPutProgress(qint64 bytesReceived, qint64 bytesTotal); + + void primitivesIntegerPostSignalFull(PFXHttpRequestWorker *worker); + void primitivesNumberPutSignalFull(PFXHttpRequestWorker *worker); + + Q_DECL_DEPRECATED_X("Use primitivesIntegerPostSignalError() instead") + void primitivesIntegerPostSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void primitivesIntegerPostSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use primitivesNumberPutSignalError() instead") + void primitivesNumberPutSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void primitivesNumberPutSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + + Q_DECL_DEPRECATED_X("Use primitivesIntegerPostSignalErrorFull() instead") + void primitivesIntegerPostSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void primitivesIntegerPostSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use primitivesNumberPutSignalErrorFull() instead") + void primitivesNumberPutSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void primitivesNumberPutSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + + void abortRequestsSignal(); + void allPendingRequestsCompleted(); + +public Q_SLOTS: + void tokenAvailable(); +}; + +} // namespace test_namespace +#endif diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXStoreApi.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXStoreApi.cpp new file mode 100644 index 000000000000..54825bab3679 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXStoreApi.cpp @@ -0,0 +1,589 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "PFXStoreApi.h" +#include "PFXServerConfiguration.h" +#include +#include + +namespace test_namespace { + +PFXStoreApi::PFXStoreApi(const int timeOut) + : _timeOut(timeOut), + _manager(nullptr), + _isResponseCompressionEnabled(false), + _isRequestCompressionEnabled(false) { + initializeServerConfigs(); +} + +PFXStoreApi::~PFXStoreApi() { +} + +void PFXStoreApi::initializeServerConfigs() { + //Default server + QList defaultConf = QList(); + //varying endpoint server + defaultConf.append(PFXServerConfiguration( + QUrl("http://petstore.swagger.io/v2"), + "No description provided", + QMap())); + _serverConfigs.insert("deleteOrder", defaultConf); + _serverIndices.insert("deleteOrder", 0); + _serverConfigs.insert("getInventory", defaultConf); + _serverIndices.insert("getInventory", 0); + _serverConfigs.insert("getOrderById", defaultConf); + _serverIndices.insert("getOrderById", 0); + _serverConfigs.insert("placeOrder", defaultConf); + _serverIndices.insert("placeOrder", 0); +} + +/** +* returns 0 on success and -1, -2 or -3 on failure. +* -1 when the variable does not exist and -2 if the value is not defined in the enum and -3 if the operation or server index is not found +*/ +int PFXStoreApi::setDefaultServerValue(int serverIndex, const QString &operation, const QString &variable, const QString &value) { + auto it = _serverConfigs.find(operation); + if (it != _serverConfigs.end() && serverIndex < it.value().size()) { + return _serverConfigs[operation][serverIndex].setDefaultValue(variable,value); + } + return -3; +} +void PFXStoreApi::setServerIndex(const QString &operation, int serverIndex) { + if (_serverIndices.contains(operation) && serverIndex < _serverConfigs.find(operation).value().size()) { + _serverIndices[operation] = serverIndex; + } +} + +void PFXStoreApi::setApiKey(const QString &apiKeyName, const QString &apiKey) { + _apiKeys.insert(apiKeyName, apiKey); +} + +void PFXStoreApi::setBearerToken(const QString &token) { + _bearerToken = token; +} + +void PFXStoreApi::setUsername(const QString &username) { + _username = username; +} + +void PFXStoreApi::setPassword(const QString &password) { + _password = password; +} + + +void PFXStoreApi::setTimeOut(const int timeOut) { + _timeOut = timeOut; +} + +void PFXStoreApi::setWorkingDirectory(const QString &path) { + _workingDirectory = path; +} + +void PFXStoreApi::setNetworkAccessManager(QNetworkAccessManager* manager) { + _manager = manager; +} + +/** + * Appends a new ServerConfiguration to the config map for a specific operation. + * @param operation The id to the target operation. + * @param url A string that contains the URL of the server + * @param description A String that describes the server + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + * returns the index of the new server config on success and -1 if the operation is not found + */ +int PFXStoreApi::addServerConfiguration(const QString &operation, const QUrl &url, const QString &description, const QMap &variables) { + if (_serverConfigs.contains(operation)) { + _serverConfigs[operation].append(PFXServerConfiguration( + url, + description, + variables)); + return _serverConfigs[operation].size()-1; + } else { + return -1; + } +} + +/** + * Appends a new ServerConfiguration to the config map for a all operations and sets the index to that server. + * @param url A string that contains the URL of the server + * @param description A String that describes the server + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ +void PFXStoreApi::setNewServerForAllOperations(const QUrl &url, const QString &description, const QMap &variables) { + for (auto keyIt = _serverIndices.keyBegin(); keyIt != _serverIndices.keyEnd(); keyIt++) { + setServerIndex(*keyIt, addServerConfiguration(*keyIt, url, description, variables)); + } +} + +/** + * Appends a new ServerConfiguration to the config map for an operations and sets the index to that server. + * @param URL A string that contains the URL of the server + * @param description A String that describes the server + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ +void PFXStoreApi::setNewServer(const QString &operation, const QUrl &url, const QString &description, const QMap &variables) { + setServerIndex(operation, addServerConfiguration(operation, url, description, variables)); +} + +void PFXStoreApi::addHeaders(const QString &key, const QString &value) { + _defaultHeaders.insert(key, value); +} + +void PFXStoreApi::enableRequestCompression() { + _isRequestCompressionEnabled = true; +} + +void PFXStoreApi::enableResponseCompression() { + _isResponseCompressionEnabled = true; +} + +void PFXStoreApi::abortRequests() { + Q_EMIT abortRequestsSignal(); +} + +QString PFXStoreApi::getParamStylePrefix(const QString &style) { + if (style == "matrix") { + return ";"; + } else if (style == "label") { + return "."; + } else if (style == "form") { + return "&"; + } else if (style == "simple") { + return ""; + } else if (style == "spaceDelimited") { + return "&"; + } else if (style == "pipeDelimited") { + return "&"; + } else { + return "none"; + } +} + +QString PFXStoreApi::getParamStyleSuffix(const QString &style) { + if (style == "matrix") { + return "="; + } else if (style == "label") { + return ""; + } else if (style == "form") { + return "="; + } else if (style == "simple") { + return ""; + } else if (style == "spaceDelimited") { + return "="; + } else if (style == "pipeDelimited") { + return "="; + } else { + return "none"; + } +} + +QString PFXStoreApi::getParamStyleDelimiter(const QString &style, const QString &name, bool isExplode) { + + if (style == "matrix") { + return (isExplode) ? ";" + name + "=" : ","; + + } else if (style == "label") { + return (isExplode) ? "." : ","; + + } else if (style == "form") { + return (isExplode) ? "&" + name + "=" : ","; + + } else if (style == "simple") { + return ","; + } else if (style == "spaceDelimited") { + return (isExplode) ? "&" + name + "=" : " "; + + } else if (style == "pipeDelimited") { + return (isExplode) ? "&" + name + "=" : "|"; + + } else if (style == "deepObject") { + return (isExplode) ? "&" : "none"; + + } else { + return "none"; + } +} + +void PFXStoreApi::deleteOrder(const QString &order_id) { + QString fullPath = QString(_serverConfigs["deleteOrder"][_serverIndices.value("deleteOrder")].URL()+"/store/order/{orderId}"); + + + { + QString order_idPathParam("{"); + order_idPathParam.append("orderId").append("}"); + QString pathPrefix, pathSuffix, pathDelimiter; + QString pathStyle = "simple"; + if (pathStyle == "") + pathStyle = "simple"; + pathPrefix = getParamStylePrefix(pathStyle); + pathSuffix = getParamStyleSuffix(pathStyle); + pathDelimiter = getParamStyleDelimiter(pathStyle, "orderId", false); + QString paramString = (pathStyle == "matrix") ? pathPrefix+"orderId"+pathSuffix : pathPrefix; + fullPath.replace(order_idPathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(order_id))); + } + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "DELETE"); + + + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXStoreApi::deleteOrderProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXStoreApi::deleteOrderCallback); + connect(this, &PFXStoreApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + + worker->execute(&input); +} + +void PFXStoreApi::deleteOrderCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT deleteOrderSignal(); + Q_EMIT deleteOrderSignalFull(worker); + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT deleteOrderSignalE(error_type, error_str); + Q_EMIT deleteOrderSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT deleteOrderSignalError(error_type, error_str); + Q_EMIT deleteOrderSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXStoreApi::getInventory() { + QString fullPath = QString(_serverConfigs["getInventory"][_serverIndices.value("getInventory")].URL()+"/store/inventory"); + + if (_apiKeys.contains("api_key")) { + addHeaders("api_key",_apiKeys.find("api_key").value()); + } + + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "GET"); + + + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXStoreApi::getInventoryProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXStoreApi::getInventoryCallback); + connect(this, &PFXStoreApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + + worker->execute(&input); +} + +void PFXStoreApi::getInventoryCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + QMap output; + QString json(worker->response); + QByteArray array(json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject obj = doc.object(); + for (QString key : obj.keys()) { + qint32 val; + ::test_namespace::fromJsonValue(val, obj[key]); + output.insert(key, val); + } + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT getInventorySignal(output); + Q_EMIT getInventorySignalFull(worker, output); + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT getInventorySignalE(output, error_type, error_str); + Q_EMIT getInventorySignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT getInventorySignalError(output, error_type, error_str); + Q_EMIT getInventorySignalErrorFull(worker, error_type, error_str); + } +} + +void PFXStoreApi::getOrderById(const qint64 &order_id) { + QString fullPath = QString(_serverConfigs["getOrderById"][_serverIndices.value("getOrderById")].URL()+"/store/order/{orderId}"); + + + { + QString order_idPathParam("{"); + order_idPathParam.append("orderId").append("}"); + QString pathPrefix, pathSuffix, pathDelimiter; + QString pathStyle = "simple"; + if (pathStyle == "") + pathStyle = "simple"; + pathPrefix = getParamStylePrefix(pathStyle); + pathSuffix = getParamStyleSuffix(pathStyle); + pathDelimiter = getParamStyleDelimiter(pathStyle, "orderId", false); + QString paramString = (pathStyle == "matrix") ? pathPrefix+"orderId"+pathSuffix : pathPrefix; + fullPath.replace(order_idPathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(order_id))); + } + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "GET"); + + + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXStoreApi::getOrderByIdProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXStoreApi::getOrderByIdCallback); + connect(this, &PFXStoreApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + + worker->execute(&input); +} + +void PFXStoreApi::getOrderByIdCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + PFXOrder output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT getOrderByIdSignal(output); + Q_EMIT getOrderByIdSignalFull(worker, output); + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT getOrderByIdSignalE(output, error_type, error_str); + Q_EMIT getOrderByIdSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT getOrderByIdSignalError(output, error_type, error_str); + Q_EMIT getOrderByIdSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXStoreApi::placeOrder(const PFXOrder &pfx_order) { + QString fullPath = QString(_serverConfigs["placeOrder"][_serverIndices.value("placeOrder")].URL()+"/store/order"); + + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "POST"); + + { + + + QByteArray output = pfx_order.asJson().toUtf8(); + input.request_body.append(output); + } + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXStoreApi::placeOrderProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXStoreApi::placeOrderCallback); + connect(this, &PFXStoreApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + + worker->execute(&input); +} + +void PFXStoreApi::placeOrderCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + PFXOrder output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT placeOrderSignal(output); + Q_EMIT placeOrderSignalFull(worker, output); + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT placeOrderSignalE(output, error_type, error_str); + Q_EMIT placeOrderSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT placeOrderSignalError(output, error_type, error_str); + Q_EMIT placeOrderSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXStoreApi::tokenAvailable(){ + + oauthToken token; + switch (_OauthMethod) { + case 1: //implicit flow + token = _implicitFlow.getToken(_latestScope.join(" ")); + if(token.isValid()){ + _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); + _latestWorker->execute(&_latestInput); + }else{ + _implicitFlow.removeToken(_latestScope.join(" ")); + qDebug() << "Could not retrieve a valid token"; + } + break; + case 2: //authorization flow + token = _authFlow.getToken(_latestScope.join(" ")); + if(token.isValid()){ + _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); + _latestWorker->execute(&_latestInput); + }else{ + _authFlow.removeToken(_latestScope.join(" ")); + qDebug() << "Could not retrieve a valid token"; + } + break; + case 3: //client credentials flow + token = _credentialFlow.getToken(_latestScope.join(" ")); + if(token.isValid()){ + _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); + _latestWorker->execute(&_latestInput); + }else{ + _credentialFlow.removeToken(_latestScope.join(" ")); + qDebug() << "Could not retrieve a valid token"; + } + break; + case 4: //resource owner password flow + token = _passwordFlow.getToken(_latestScope.join(" ")); + if(token.isValid()){ + _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); + _latestWorker->execute(&_latestInput); + }else{ + _credentialFlow.removeToken(_latestScope.join(" ")); + qDebug() << "Could not retrieve a valid token"; + } + break; + default: + qDebug() << "No Oauth method set!"; + break; + } +} +} // namespace test_namespace diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXStoreApi.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXStoreApi.h new file mode 100644 index 000000000000..e5ff6fd32b7a --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXStoreApi.h @@ -0,0 +1,157 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#ifndef PFX_PFXStoreApi_H +#define PFX_PFXStoreApi_H + +#include "PFXHelpers.h" +#include "PFXHttpRequest.h" +#include "PFXServerConfiguration.h" +#include "PFXOauth.h" + +#include "PFXOrder.h" +#include +#include + +#include +#include +#include +#include +#include + +namespace test_namespace { + +class PFXStoreApi : public QObject { + Q_OBJECT + +public: + PFXStoreApi(const int timeOut = 0); + ~PFXStoreApi(); + + void initializeServerConfigs(); + int setDefaultServerValue(int serverIndex,const QString &operation, const QString &variable,const QString &val); + void setServerIndex(const QString &operation, int serverIndex); + void setApiKey(const QString &apiKeyName, const QString &apiKey); + void setBearerToken(const QString &token); + void setUsername(const QString &username); + void setPassword(const QString &password); + void setTimeOut(const int timeOut); + void setWorkingDirectory(const QString &path); + void setNetworkAccessManager(QNetworkAccessManager* manager); + int addServerConfiguration(const QString &operation, const QUrl &url, const QString &description = "", const QMap &variables = QMap()); + void setNewServerForAllOperations(const QUrl &url, const QString &description = "", const QMap &variables = QMap()); + void setNewServer(const QString &operation, const QUrl &url, const QString &description = "", const QMap &variables = QMap()); + void addHeaders(const QString &key, const QString &value); + void enableRequestCompression(); + void enableResponseCompression(); + void abortRequests(); + QString getParamStylePrefix(const QString &style); + QString getParamStyleSuffix(const QString &style); + QString getParamStyleDelimiter(const QString &style, const QString &name, bool isExplode); + + /** + * @param[in] order_id QString [required] + */ + void deleteOrder(const QString &order_id); + + + void getInventory(); + + /** + * @param[in] order_id qint64 [required] + */ + void getOrderById(const qint64 &order_id); + + /** + * @param[in] pfx_order PFXOrder [required] + */ + void placeOrder(const PFXOrder &pfx_order); + + +private: + QMap _serverIndices; + QMap> _serverConfigs; + QMap _apiKeys; + QString _bearerToken; + QString _username; + QString _password; + int _timeOut; + QString _workingDirectory; + QNetworkAccessManager* _manager; + QMap _defaultHeaders; + bool _isResponseCompressionEnabled; + bool _isRequestCompressionEnabled; + PFXHttpRequestInput _latestInput; + PFXHttpRequestWorker *_latestWorker; + QStringList _latestScope; + OauthCode _authFlow; + OauthImplicit _implicitFlow; + OauthCredentials _credentialFlow; + OauthPassword _passwordFlow; + int _OauthMethod = 0; + + void deleteOrderCallback(PFXHttpRequestWorker *worker); + void getInventoryCallback(PFXHttpRequestWorker *worker); + void getOrderByIdCallback(PFXHttpRequestWorker *worker); + void placeOrderCallback(PFXHttpRequestWorker *worker); + +Q_SIGNALS: + + void deleteOrderSignal(); + void getInventorySignal(QMap summary); + void getOrderByIdSignal(PFXOrder summary); + void placeOrderSignal(PFXOrder summary); + + void deleteOrderProgress(qint64 bytesReceived, qint64 bytesTotal); + void getInventoryProgress(qint64 bytesReceived, qint64 bytesTotal); + void getOrderByIdProgress(qint64 bytesReceived, qint64 bytesTotal); + void placeOrderProgress(qint64 bytesReceived, qint64 bytesTotal); + + void deleteOrderSignalFull(PFXHttpRequestWorker *worker); + void getInventorySignalFull(PFXHttpRequestWorker *worker, QMap summary); + void getOrderByIdSignalFull(PFXHttpRequestWorker *worker, PFXOrder summary); + void placeOrderSignalFull(PFXHttpRequestWorker *worker, PFXOrder summary); + + Q_DECL_DEPRECATED_X("Use deleteOrderSignalError() instead") + void deleteOrderSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void deleteOrderSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use getInventorySignalError() instead") + void getInventorySignalE(QMap summary, QNetworkReply::NetworkError error_type, QString error_str); + void getInventorySignalError(QMap summary, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use getOrderByIdSignalError() instead") + void getOrderByIdSignalE(PFXOrder summary, QNetworkReply::NetworkError error_type, QString error_str); + void getOrderByIdSignalError(PFXOrder summary, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use placeOrderSignalError() instead") + void placeOrderSignalE(PFXOrder summary, QNetworkReply::NetworkError error_type, QString error_str); + void placeOrderSignalError(PFXOrder summary, QNetworkReply::NetworkError error_type, const QString &error_str); + + Q_DECL_DEPRECATED_X("Use deleteOrderSignalErrorFull() instead") + void deleteOrderSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void deleteOrderSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use getInventorySignalErrorFull() instead") + void getInventorySignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void getInventorySignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use getOrderByIdSignalErrorFull() instead") + void getOrderByIdSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void getOrderByIdSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use placeOrderSignalErrorFull() instead") + void placeOrderSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void placeOrderSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + + void abortRequestsSignal(); + void allPendingRequestsCompleted(); + +public Q_SLOTS: + void tokenAvailable(); +}; + +} // namespace test_namespace +#endif diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXTestAnyType.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXTestAnyType.cpp new file mode 100644 index 000000000000..f0baa2c149e5 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXTestAnyType.cpp @@ -0,0 +1,130 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "PFXTestAnyType.h" + +#include +#include +#include +#include + +#include "PFXHelpers.h" + +namespace test_namespace { + +PFXTestAnyType::PFXTestAnyType(QString json) { + this->initializeModel(); + this->fromJson(json); +} + +PFXTestAnyType::PFXTestAnyType() { + this->initializeModel(); +} + +PFXTestAnyType::~PFXTestAnyType() {} + +void PFXTestAnyType::initializeModel() { + + m_code_isSet = false; + m_code_isValid = false; + + m_message_isSet = false; + m_message_isValid = false; +} + +void PFXTestAnyType::fromJson(QString jsonString) { + QByteArray array(jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void PFXTestAnyType::fromJsonObject(QJsonObject json) { + + m_code_isValid = ::test_namespace::fromJsonValue(m_code, json[QString("code")]); + m_code_isSet = !json[QString("code")].isNull() && m_code_isValid; + + m_message_isValid = ::test_namespace::fromJsonValue(m_message, json[QString("message")]); + m_message_isSet = !json[QString("message")].isNull() && m_message_isValid; +} + +QString PFXTestAnyType::asJson() const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject PFXTestAnyType::asJsonObject() const { + QJsonObject obj; + if (m_code_isSet) { + obj.insert(QString("code"), ::test_namespace::toJsonValue(m_code)); + } + if (m_message_isSet) { + obj.insert(QString("message"), ::test_namespace::toJsonValue(m_message)); + } + return obj; +} + +QJsonValue PFXTestAnyType::getCode() const { + return m_code; +} +void PFXTestAnyType::setCode(const QJsonValue &code) { + m_code = code; + m_code_isSet = true; +} + +bool PFXTestAnyType::is_code_Set() const{ + return m_code_isSet; +} + +bool PFXTestAnyType::is_code_Valid() const{ + return m_code_isValid; +} + +QString PFXTestAnyType::getMessage() const { + return m_message; +} +void PFXTestAnyType::setMessage(const QString &message) { + m_message = message; + m_message_isSet = true; +} + +bool PFXTestAnyType::is_message_Set() const{ + return m_message_isSet; +} + +bool PFXTestAnyType::is_message_Valid() const{ + return m_message_isValid; +} + +bool PFXTestAnyType::isSet() const { + bool isObjectUpdated = false; + do { + if (m_code_isSet) { + isObjectUpdated = true; + break; + } + + if (m_message_isSet) { + isObjectUpdated = true; + break; + } + } while (false); + return isObjectUpdated; +} + +bool PFXTestAnyType::isValid() const { + // only required properties are required for the object to be considered valid + return true; +} + +} // namespace test_namespace diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXTestAnyType.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXTestAnyType.h new file mode 100644 index 000000000000..b8a76d1fc964 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXTestAnyType.h @@ -0,0 +1,71 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * PFXTestAnyType.h + * + * test any type + */ + +#ifndef PFXTestAnyType_H +#define PFXTestAnyType_H + +#include + +#include +#include + +#include "PFXEnum.h" +#include "PFXObject.h" + +namespace test_namespace { + +class PFXTestAnyType : public PFXObject { +public: + PFXTestAnyType(); + PFXTestAnyType(QString json); + ~PFXTestAnyType() override; + + QString asJson() const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + QJsonValue getCode() const; + void setCode(const QJsonValue &code); + bool is_code_Set() const; + bool is_code_Valid() const; + + QString getMessage() const; + void setMessage(const QString &message); + bool is_message_Set() const; + bool is_message_Valid() const; + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void initializeModel(); + + QJsonValue m_code; + bool m_code_isSet; + bool m_code_isValid; + + QString m_message; + bool m_message_isSet; + bool m_message_isValid; +}; + +} // namespace test_namespace + +Q_DECLARE_METATYPE(test_namespace::PFXTestAnyType) + +#endif // PFXTestAnyType_H diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXUser.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXUser.cpp new file mode 100644 index 000000000000..e466a42424cc --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXUser.cpp @@ -0,0 +1,310 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "PFXUser.h" + +#include +#include +#include +#include + +#include "PFXHelpers.h" + +namespace test_namespace { + +PFXUser::PFXUser(QString json) { + this->initializeModel(); + this->fromJson(json); +} + +PFXUser::PFXUser() { + this->initializeModel(); +} + +PFXUser::~PFXUser() {} + +void PFXUser::initializeModel() { + + m_id_isSet = false; + m_id_isValid = false; + + m_username_isSet = false; + m_username_isValid = false; + + m_first_name_isSet = false; + m_first_name_isValid = false; + + m_last_name_isSet = false; + m_last_name_isValid = false; + + m_email_isSet = false; + m_email_isValid = false; + + m_password_isSet = false; + m_password_isValid = false; + + m_phone_isSet = false; + m_phone_isValid = false; + + m_user_status_isSet = false; + m_user_status_isValid = false; +} + +void PFXUser::fromJson(QString jsonString) { + QByteArray array(jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void PFXUser::fromJsonObject(QJsonObject json) { + + m_id_isValid = ::test_namespace::fromJsonValue(m_id, json[QString("id")]); + m_id_isSet = !json[QString("id")].isNull() && m_id_isValid; + + m_username_isValid = ::test_namespace::fromJsonValue(m_username, json[QString("username")]); + m_username_isSet = !json[QString("username")].isNull() && m_username_isValid; + + m_first_name_isValid = ::test_namespace::fromJsonValue(m_first_name, json[QString("firstName")]); + m_first_name_isSet = !json[QString("firstName")].isNull() && m_first_name_isValid; + + m_last_name_isValid = ::test_namespace::fromJsonValue(m_last_name, json[QString("lastName")]); + m_last_name_isSet = !json[QString("lastName")].isNull() && m_last_name_isValid; + + m_email_isValid = ::test_namespace::fromJsonValue(m_email, json[QString("email")]); + m_email_isSet = !json[QString("email")].isNull() && m_email_isValid; + + m_password_isValid = ::test_namespace::fromJsonValue(m_password, json[QString("password")]); + m_password_isSet = !json[QString("password")].isNull() && m_password_isValid; + + m_phone_isValid = ::test_namespace::fromJsonValue(m_phone, json[QString("phone")]); + m_phone_isSet = !json[QString("phone")].isNull() && m_phone_isValid; + + m_user_status_isValid = ::test_namespace::fromJsonValue(m_user_status, json[QString("userStatus")]); + m_user_status_isSet = !json[QString("userStatus")].isNull() && m_user_status_isValid; +} + +QString PFXUser::asJson() const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject PFXUser::asJsonObject() const { + QJsonObject obj; + if (m_id_isSet) { + obj.insert(QString("id"), ::test_namespace::toJsonValue(m_id)); + } + if (m_username_isSet) { + obj.insert(QString("username"), ::test_namespace::toJsonValue(m_username)); + } + if (m_first_name_isSet) { + obj.insert(QString("firstName"), ::test_namespace::toJsonValue(m_first_name)); + } + if (m_last_name_isSet) { + obj.insert(QString("lastName"), ::test_namespace::toJsonValue(m_last_name)); + } + if (m_email_isSet) { + obj.insert(QString("email"), ::test_namespace::toJsonValue(m_email)); + } + if (m_password_isSet) { + obj.insert(QString("password"), ::test_namespace::toJsonValue(m_password)); + } + if (m_phone_isSet) { + obj.insert(QString("phone"), ::test_namespace::toJsonValue(m_phone)); + } + if (m_user_status_isSet) { + obj.insert(QString("userStatus"), ::test_namespace::toJsonValue(m_user_status)); + } + return obj; +} + +qint64 PFXUser::getId() const { + return m_id; +} +void PFXUser::setId(const qint64 &id) { + m_id = id; + m_id_isSet = true; +} + +bool PFXUser::is_id_Set() const{ + return m_id_isSet; +} + +bool PFXUser::is_id_Valid() const{ + return m_id_isValid; +} + +QString PFXUser::getUsername() const { + return m_username; +} +void PFXUser::setUsername(const QString &username) { + m_username = username; + m_username_isSet = true; +} + +bool PFXUser::is_username_Set() const{ + return m_username_isSet; +} + +bool PFXUser::is_username_Valid() const{ + return m_username_isValid; +} + +QString PFXUser::getFirstName() const { + return m_first_name; +} +void PFXUser::setFirstName(const QString &first_name) { + m_first_name = first_name; + m_first_name_isSet = true; +} + +bool PFXUser::is_first_name_Set() const{ + return m_first_name_isSet; +} + +bool PFXUser::is_first_name_Valid() const{ + return m_first_name_isValid; +} + +QString PFXUser::getLastName() const { + return m_last_name; +} +void PFXUser::setLastName(const QString &last_name) { + m_last_name = last_name; + m_last_name_isSet = true; +} + +bool PFXUser::is_last_name_Set() const{ + return m_last_name_isSet; +} + +bool PFXUser::is_last_name_Valid() const{ + return m_last_name_isValid; +} + +QString PFXUser::getEmail() const { + return m_email; +} +void PFXUser::setEmail(const QString &email) { + m_email = email; + m_email_isSet = true; +} + +bool PFXUser::is_email_Set() const{ + return m_email_isSet; +} + +bool PFXUser::is_email_Valid() const{ + return m_email_isValid; +} + +QString PFXUser::getPassword() const { + return m_password; +} +void PFXUser::setPassword(const QString &password) { + m_password = password; + m_password_isSet = true; +} + +bool PFXUser::is_password_Set() const{ + return m_password_isSet; +} + +bool PFXUser::is_password_Valid() const{ + return m_password_isValid; +} + +QString PFXUser::getPhone() const { + return m_phone; +} +void PFXUser::setPhone(const QString &phone) { + m_phone = phone; + m_phone_isSet = true; +} + +bool PFXUser::is_phone_Set() const{ + return m_phone_isSet; +} + +bool PFXUser::is_phone_Valid() const{ + return m_phone_isValid; +} + +qint32 PFXUser::getUserStatus() const { + return m_user_status; +} +void PFXUser::setUserStatus(const qint32 &user_status) { + m_user_status = user_status; + m_user_status_isSet = true; +} + +bool PFXUser::is_user_status_Set() const{ + return m_user_status_isSet; +} + +bool PFXUser::is_user_status_Valid() const{ + return m_user_status_isValid; +} + +bool PFXUser::isSet() const { + bool isObjectUpdated = false; + do { + if (m_id_isSet) { + isObjectUpdated = true; + break; + } + + if (m_username_isSet) { + isObjectUpdated = true; + break; + } + + if (m_first_name_isSet) { + isObjectUpdated = true; + break; + } + + if (m_last_name_isSet) { + isObjectUpdated = true; + break; + } + + if (m_email_isSet) { + isObjectUpdated = true; + break; + } + + if (m_password_isSet) { + isObjectUpdated = true; + break; + } + + if (m_phone_isSet) { + isObjectUpdated = true; + break; + } + + if (m_user_status_isSet) { + isObjectUpdated = true; + break; + } + } while (false); + return isObjectUpdated; +} + +bool PFXUser::isValid() const { + // only required properties are required for the object to be considered valid + return true; +} + +} // namespace test_namespace diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXUser.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXUser.h new file mode 100644 index 000000000000..5a3def81b532 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXUser.h @@ -0,0 +1,124 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * PFXUser.h + * + * A User who is purchasing from the pet store + */ + +#ifndef PFXUser_H +#define PFXUser_H + +#include + +#include + +#include "PFXEnum.h" +#include "PFXObject.h" + +namespace test_namespace { + +class PFXUser : public PFXObject { +public: + PFXUser(); + PFXUser(QString json); + ~PFXUser() override; + + QString asJson() const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + qint64 getId() const; + void setId(const qint64 &id); + bool is_id_Set() const; + bool is_id_Valid() const; + + QString getUsername() const; + void setUsername(const QString &username); + bool is_username_Set() const; + bool is_username_Valid() const; + + QString getFirstName() const; + void setFirstName(const QString &first_name); + bool is_first_name_Set() const; + bool is_first_name_Valid() const; + + QString getLastName() const; + void setLastName(const QString &last_name); + bool is_last_name_Set() const; + bool is_last_name_Valid() const; + + QString getEmail() const; + void setEmail(const QString &email); + bool is_email_Set() const; + bool is_email_Valid() const; + + QString getPassword() const; + void setPassword(const QString &password); + bool is_password_Set() const; + bool is_password_Valid() const; + + QString getPhone() const; + void setPhone(const QString &phone); + bool is_phone_Set() const; + bool is_phone_Valid() const; + + qint32 getUserStatus() const; + void setUserStatus(const qint32 &user_status); + bool is_user_status_Set() const; + bool is_user_status_Valid() const; + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void initializeModel(); + + qint64 m_id; + bool m_id_isSet; + bool m_id_isValid; + + QString m_username; + bool m_username_isSet; + bool m_username_isValid; + + QString m_first_name; + bool m_first_name_isSet; + bool m_first_name_isValid; + + QString m_last_name; + bool m_last_name_isSet; + bool m_last_name_isValid; + + QString m_email; + bool m_email_isSet; + bool m_email_isValid; + + QString m_password; + bool m_password_isSet; + bool m_password_isValid; + + QString m_phone; + bool m_phone_isSet; + bool m_phone_isValid; + + qint32 m_user_status; + bool m_user_status_isSet; + bool m_user_status_isValid; +}; + +} // namespace test_namespace + +Q_DECLARE_METATYPE(test_namespace::PFXUser) + +#endif // PFXUser_H diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXUserApi.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXUserApi.cpp new file mode 100644 index 000000000000..1dde54421429 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXUserApi.cpp @@ -0,0 +1,918 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "PFXUserApi.h" +#include "PFXServerConfiguration.h" +#include +#include + +namespace test_namespace { + +PFXUserApi::PFXUserApi(const int timeOut) + : _timeOut(timeOut), + _manager(nullptr), + _isResponseCompressionEnabled(false), + _isRequestCompressionEnabled(false) { + initializeServerConfigs(); +} + +PFXUserApi::~PFXUserApi() { +} + +void PFXUserApi::initializeServerConfigs() { + //Default server + QList defaultConf = QList(); + //varying endpoint server + defaultConf.append(PFXServerConfiguration( + QUrl("http://petstore.swagger.io/v2"), + "No description provided", + QMap())); + _serverConfigs.insert("createUser", defaultConf); + _serverIndices.insert("createUser", 0); + _serverConfigs.insert("createUsersWithArrayInput", defaultConf); + _serverIndices.insert("createUsersWithArrayInput", 0); + _serverConfigs.insert("createUsersWithListInput", defaultConf); + _serverIndices.insert("createUsersWithListInput", 0); + _serverConfigs.insert("deleteUser", defaultConf); + _serverIndices.insert("deleteUser", 0); + _serverConfigs.insert("getUserByName", defaultConf); + _serverIndices.insert("getUserByName", 0); + _serverConfigs.insert("loginUser", defaultConf); + _serverIndices.insert("loginUser", 0); + _serverConfigs.insert("logoutUser", defaultConf); + _serverIndices.insert("logoutUser", 0); + _serverConfigs.insert("updateUser", defaultConf); + _serverIndices.insert("updateUser", 0); +} + +/** +* returns 0 on success and -1, -2 or -3 on failure. +* -1 when the variable does not exist and -2 if the value is not defined in the enum and -3 if the operation or server index is not found +*/ +int PFXUserApi::setDefaultServerValue(int serverIndex, const QString &operation, const QString &variable, const QString &value) { + auto it = _serverConfigs.find(operation); + if (it != _serverConfigs.end() && serverIndex < it.value().size()) { + return _serverConfigs[operation][serverIndex].setDefaultValue(variable,value); + } + return -3; +} +void PFXUserApi::setServerIndex(const QString &operation, int serverIndex) { + if (_serverIndices.contains(operation) && serverIndex < _serverConfigs.find(operation).value().size()) { + _serverIndices[operation] = serverIndex; + } +} + +void PFXUserApi::setApiKey(const QString &apiKeyName, const QString &apiKey) { + _apiKeys.insert(apiKeyName, apiKey); +} + +void PFXUserApi::setBearerToken(const QString &token) { + _bearerToken = token; +} + +void PFXUserApi::setUsername(const QString &username) { + _username = username; +} + +void PFXUserApi::setPassword(const QString &password) { + _password = password; +} + + +void PFXUserApi::setTimeOut(const int timeOut) { + _timeOut = timeOut; +} + +void PFXUserApi::setWorkingDirectory(const QString &path) { + _workingDirectory = path; +} + +void PFXUserApi::setNetworkAccessManager(QNetworkAccessManager* manager) { + _manager = manager; +} + +/** + * Appends a new ServerConfiguration to the config map for a specific operation. + * @param operation The id to the target operation. + * @param url A string that contains the URL of the server + * @param description A String that describes the server + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + * returns the index of the new server config on success and -1 if the operation is not found + */ +int PFXUserApi::addServerConfiguration(const QString &operation, const QUrl &url, const QString &description, const QMap &variables) { + if (_serverConfigs.contains(operation)) { + _serverConfigs[operation].append(PFXServerConfiguration( + url, + description, + variables)); + return _serverConfigs[operation].size()-1; + } else { + return -1; + } +} + +/** + * Appends a new ServerConfiguration to the config map for a all operations and sets the index to that server. + * @param url A string that contains the URL of the server + * @param description A String that describes the server + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ +void PFXUserApi::setNewServerForAllOperations(const QUrl &url, const QString &description, const QMap &variables) { + for (auto keyIt = _serverIndices.keyBegin(); keyIt != _serverIndices.keyEnd(); keyIt++) { + setServerIndex(*keyIt, addServerConfiguration(*keyIt, url, description, variables)); + } +} + +/** + * Appends a new ServerConfiguration to the config map for an operations and sets the index to that server. + * @param URL A string that contains the URL of the server + * @param description A String that describes the server + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ +void PFXUserApi::setNewServer(const QString &operation, const QUrl &url, const QString &description, const QMap &variables) { + setServerIndex(operation, addServerConfiguration(operation, url, description, variables)); +} + +void PFXUserApi::addHeaders(const QString &key, const QString &value) { + _defaultHeaders.insert(key, value); +} + +void PFXUserApi::enableRequestCompression() { + _isRequestCompressionEnabled = true; +} + +void PFXUserApi::enableResponseCompression() { + _isResponseCompressionEnabled = true; +} + +void PFXUserApi::abortRequests() { + Q_EMIT abortRequestsSignal(); +} + +QString PFXUserApi::getParamStylePrefix(const QString &style) { + if (style == "matrix") { + return ";"; + } else if (style == "label") { + return "."; + } else if (style == "form") { + return "&"; + } else if (style == "simple") { + return ""; + } else if (style == "spaceDelimited") { + return "&"; + } else if (style == "pipeDelimited") { + return "&"; + } else { + return "none"; + } +} + +QString PFXUserApi::getParamStyleSuffix(const QString &style) { + if (style == "matrix") { + return "="; + } else if (style == "label") { + return ""; + } else if (style == "form") { + return "="; + } else if (style == "simple") { + return ""; + } else if (style == "spaceDelimited") { + return "="; + } else if (style == "pipeDelimited") { + return "="; + } else { + return "none"; + } +} + +QString PFXUserApi::getParamStyleDelimiter(const QString &style, const QString &name, bool isExplode) { + + if (style == "matrix") { + return (isExplode) ? ";" + name + "=" : ","; + + } else if (style == "label") { + return (isExplode) ? "." : ","; + + } else if (style == "form") { + return (isExplode) ? "&" + name + "=" : ","; + + } else if (style == "simple") { + return ","; + } else if (style == "spaceDelimited") { + return (isExplode) ? "&" + name + "=" : " "; + + } else if (style == "pipeDelimited") { + return (isExplode) ? "&" + name + "=" : "|"; + + } else if (style == "deepObject") { + return (isExplode) ? "&" : "none"; + + } else { + return "none"; + } +} + +void PFXUserApi::createUser(const PFXUser &pfx_user) { + QString fullPath = QString(_serverConfigs["createUser"][_serverIndices.value("createUser")].URL()+"/user"); + + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "POST"); + + { + + + QByteArray output = pfx_user.asJson().toUtf8(); + input.request_body.append(output); + } + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXUserApi::createUserProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXUserApi::createUserCallback); + connect(this, &PFXUserApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + + worker->execute(&input); +} + +void PFXUserApi::createUserCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT createUserSignal(); + Q_EMIT createUserSignalFull(worker); + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT createUserSignalE(error_type, error_str); + Q_EMIT createUserSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT createUserSignalError(error_type, error_str); + Q_EMIT createUserSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXUserApi::createUsersWithArrayInput(const QList &pfx_user) { + QString fullPath = QString(_serverConfigs["createUsersWithArrayInput"][_serverIndices.value("createUsersWithArrayInput")].URL()+"/user/createWithArray"); + + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "POST"); + + { + QJsonDocument doc(::test_namespace::toJsonValue(pfx_user).toArray()); + QByteArray bytes = doc.toJson(); + input.request_body.append(bytes); + } + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXUserApi::createUsersWithArrayInputProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXUserApi::createUsersWithArrayInputCallback); + connect(this, &PFXUserApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + + worker->execute(&input); +} + +void PFXUserApi::createUsersWithArrayInputCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT createUsersWithArrayInputSignal(); + Q_EMIT createUsersWithArrayInputSignalFull(worker); + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT createUsersWithArrayInputSignalE(error_type, error_str); + Q_EMIT createUsersWithArrayInputSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT createUsersWithArrayInputSignalError(error_type, error_str); + Q_EMIT createUsersWithArrayInputSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXUserApi::createUsersWithListInput(const QList &pfx_user) { + QString fullPath = QString(_serverConfigs["createUsersWithListInput"][_serverIndices.value("createUsersWithListInput")].URL()+"/user/createWithList"); + + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "POST"); + + { + QJsonDocument doc(::test_namespace::toJsonValue(pfx_user).toArray()); + QByteArray bytes = doc.toJson(); + input.request_body.append(bytes); + } + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXUserApi::createUsersWithListInputProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXUserApi::createUsersWithListInputCallback); + connect(this, &PFXUserApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + + worker->execute(&input); +} + +void PFXUserApi::createUsersWithListInputCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT createUsersWithListInputSignal(); + Q_EMIT createUsersWithListInputSignalFull(worker); + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT createUsersWithListInputSignalE(error_type, error_str); + Q_EMIT createUsersWithListInputSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT createUsersWithListInputSignalError(error_type, error_str); + Q_EMIT createUsersWithListInputSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXUserApi::deleteUser(const QString &username) { + QString fullPath = QString(_serverConfigs["deleteUser"][_serverIndices.value("deleteUser")].URL()+"/user/{username}"); + + + { + QString usernamePathParam("{"); + usernamePathParam.append("username").append("}"); + QString pathPrefix, pathSuffix, pathDelimiter; + QString pathStyle = "simple"; + if (pathStyle == "") + pathStyle = "simple"; + pathPrefix = getParamStylePrefix(pathStyle); + pathSuffix = getParamStyleSuffix(pathStyle); + pathDelimiter = getParamStyleDelimiter(pathStyle, "username", false); + QString paramString = (pathStyle == "matrix") ? pathPrefix+"username"+pathSuffix : pathPrefix; + fullPath.replace(usernamePathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(username))); + } + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "DELETE"); + + + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXUserApi::deleteUserProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXUserApi::deleteUserCallback); + connect(this, &PFXUserApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + + worker->execute(&input); +} + +void PFXUserApi::deleteUserCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT deleteUserSignal(); + Q_EMIT deleteUserSignalFull(worker); + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT deleteUserSignalE(error_type, error_str); + Q_EMIT deleteUserSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT deleteUserSignalError(error_type, error_str); + Q_EMIT deleteUserSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXUserApi::getUserByName(const QString &username) { + QString fullPath = QString(_serverConfigs["getUserByName"][_serverIndices.value("getUserByName")].URL()+"/user/{username}"); + + + { + QString usernamePathParam("{"); + usernamePathParam.append("username").append("}"); + QString pathPrefix, pathSuffix, pathDelimiter; + QString pathStyle = "simple"; + if (pathStyle == "") + pathStyle = "simple"; + pathPrefix = getParamStylePrefix(pathStyle); + pathSuffix = getParamStyleSuffix(pathStyle); + pathDelimiter = getParamStyleDelimiter(pathStyle, "username", false); + QString paramString = (pathStyle == "matrix") ? pathPrefix+"username"+pathSuffix : pathPrefix; + fullPath.replace(usernamePathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(username))); + } + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "GET"); + + + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXUserApi::getUserByNameProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXUserApi::getUserByNameCallback); + connect(this, &PFXUserApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + + worker->execute(&input); +} + +void PFXUserApi::getUserByNameCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + PFXUser output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT getUserByNameSignal(output); + Q_EMIT getUserByNameSignalFull(worker, output); + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT getUserByNameSignalE(output, error_type, error_str); + Q_EMIT getUserByNameSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT getUserByNameSignalError(output, error_type, error_str); + Q_EMIT getUserByNameSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXUserApi::loginUser(const QString &username, const QString &password) { + QString fullPath = QString(_serverConfigs["loginUser"][_serverIndices.value("loginUser")].URL()+"/user/login"); + + QString queryPrefix, querySuffix, queryDelimiter, queryStyle; + + { + queryStyle = "form"; + if (queryStyle == "") + queryStyle = "form"; + queryPrefix = getParamStylePrefix(queryStyle); + querySuffix = getParamStyleSuffix(queryStyle); + queryDelimiter = getParamStyleDelimiter(queryStyle, "username", true); + if (fullPath.indexOf("?") > 0) + fullPath.append(queryPrefix); + else + fullPath.append("?"); + + fullPath.append(QUrl::toPercentEncoding("username")).append(querySuffix).append(QUrl::toPercentEncoding(username)); + } + + { + queryStyle = "form"; + if (queryStyle == "") + queryStyle = "form"; + queryPrefix = getParamStylePrefix(queryStyle); + querySuffix = getParamStyleSuffix(queryStyle); + queryDelimiter = getParamStyleDelimiter(queryStyle, "password", true); + if (fullPath.indexOf("?") > 0) + fullPath.append(queryPrefix); + else + fullPath.append("?"); + + fullPath.append(QUrl::toPercentEncoding("password")).append(querySuffix).append(QUrl::toPercentEncoding(password)); + } + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "GET"); + + + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXUserApi::loginUserProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXUserApi::loginUserCallback); + connect(this, &PFXUserApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + + worker->execute(&input); +} + +void PFXUserApi::loginUserCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + QString output; + ::test_namespace::fromStringValue(QString(worker->response), output); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT loginUserSignal(output); + Q_EMIT loginUserSignalFull(worker, output); + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT loginUserSignalE(output, error_type, error_str); + Q_EMIT loginUserSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT loginUserSignalError(output, error_type, error_str); + Q_EMIT loginUserSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXUserApi::logoutUser() { + QString fullPath = QString(_serverConfigs["logoutUser"][_serverIndices.value("logoutUser")].URL()+"/user/logout"); + + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "GET"); + + + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXUserApi::logoutUserProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXUserApi::logoutUserCallback); + connect(this, &PFXUserApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + + worker->execute(&input); +} + +void PFXUserApi::logoutUserCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT logoutUserSignal(); + Q_EMIT logoutUserSignalFull(worker); + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT logoutUserSignalE(error_type, error_str); + Q_EMIT logoutUserSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT logoutUserSignalError(error_type, error_str); + Q_EMIT logoutUserSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXUserApi::updateUser(const QString &username, const PFXUser &pfx_user) { + QString fullPath = QString(_serverConfigs["updateUser"][_serverIndices.value("updateUser")].URL()+"/user/{username}"); + + + { + QString usernamePathParam("{"); + usernamePathParam.append("username").append("}"); + QString pathPrefix, pathSuffix, pathDelimiter; + QString pathStyle = "simple"; + if (pathStyle == "") + pathStyle = "simple"; + pathPrefix = getParamStylePrefix(pathStyle); + pathSuffix = getParamStyleSuffix(pathStyle); + pathDelimiter = getParamStyleDelimiter(pathStyle, "username", false); + QString paramString = (pathStyle == "matrix") ? pathPrefix+"username"+pathSuffix : pathPrefix; + fullPath.replace(usernamePathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(username))); + } + PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager); + worker->setTimeOut(_timeOut); + worker->setWorkingDirectory(_workingDirectory); + PFXHttpRequestInput input(fullPath, "PUT"); + + { + + + QByteArray output = pfx_user.asJson().toUtf8(); + input.request_body.append(output); + } + for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) { + input.headers.insert(keyValueIt->first, keyValueIt->second); + } + + connect(worker, &PFXHttpRequestWorker::downloadProgress, this, &PFXUserApi::updateUserProgress); + connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXUserApi::updateUserCallback); + connect(this, &PFXUserApi::abortRequestsSignal, worker, &QObject::deleteLater); + connect(worker, &QObject::destroyed, this, [this]() { + if (findChildren().count() == 0) { + Q_EMIT allPendingRequestsCompleted(); + } + }); + + worker->execute(&input); +} + +void PFXUserApi::updateUserCallback(PFXHttpRequestWorker *worker) { + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type != QNetworkReply::NoError) { + error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response)); + } + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + Q_EMIT updateUserSignal(); + Q_EMIT updateUserSignalFull(worker); + } else { + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT updateUserSignalE(error_type, error_str); + Q_EMIT updateUserSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT updateUserSignalError(error_type, error_str); + Q_EMIT updateUserSignalErrorFull(worker, error_type, error_str); + } +} + +void PFXUserApi::tokenAvailable(){ + + oauthToken token; + switch (_OauthMethod) { + case 1: //implicit flow + token = _implicitFlow.getToken(_latestScope.join(" ")); + if(token.isValid()){ + _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); + _latestWorker->execute(&_latestInput); + }else{ + _implicitFlow.removeToken(_latestScope.join(" ")); + qDebug() << "Could not retrieve a valid token"; + } + break; + case 2: //authorization flow + token = _authFlow.getToken(_latestScope.join(" ")); + if(token.isValid()){ + _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); + _latestWorker->execute(&_latestInput); + }else{ + _authFlow.removeToken(_latestScope.join(" ")); + qDebug() << "Could not retrieve a valid token"; + } + break; + case 3: //client credentials flow + token = _credentialFlow.getToken(_latestScope.join(" ")); + if(token.isValid()){ + _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); + _latestWorker->execute(&_latestInput); + }else{ + _credentialFlow.removeToken(_latestScope.join(" ")); + qDebug() << "Could not retrieve a valid token"; + } + break; + case 4: //resource owner password flow + token = _passwordFlow.getToken(_latestScope.join(" ")); + if(token.isValid()){ + _latestInput.headers.insert("Authorization", "Bearer " + token.getToken()); + _latestWorker->execute(&_latestInput); + }else{ + _credentialFlow.removeToken(_latestScope.join(" ")); + qDebug() << "Could not retrieve a valid token"; + } + break; + default: + qDebug() << "No Oauth method set!"; + break; + } +} +} // namespace test_namespace diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXUserApi.h b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXUserApi.h new file mode 100644 index 000000000000..8356df7c53e0 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXUserApi.h @@ -0,0 +1,218 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#ifndef PFX_PFXUserApi_H +#define PFX_PFXUserApi_H + +#include "PFXHelpers.h" +#include "PFXHttpRequest.h" +#include "PFXServerConfiguration.h" +#include "PFXOauth.h" + +#include "PFXUser.h" +#include + +#include +#include +#include +#include +#include + +namespace test_namespace { + +class PFXUserApi : public QObject { + Q_OBJECT + +public: + PFXUserApi(const int timeOut = 0); + ~PFXUserApi(); + + void initializeServerConfigs(); + int setDefaultServerValue(int serverIndex,const QString &operation, const QString &variable,const QString &val); + void setServerIndex(const QString &operation, int serverIndex); + void setApiKey(const QString &apiKeyName, const QString &apiKey); + void setBearerToken(const QString &token); + void setUsername(const QString &username); + void setPassword(const QString &password); + void setTimeOut(const int timeOut); + void setWorkingDirectory(const QString &path); + void setNetworkAccessManager(QNetworkAccessManager* manager); + int addServerConfiguration(const QString &operation, const QUrl &url, const QString &description = "", const QMap &variables = QMap()); + void setNewServerForAllOperations(const QUrl &url, const QString &description = "", const QMap &variables = QMap()); + void setNewServer(const QString &operation, const QUrl &url, const QString &description = "", const QMap &variables = QMap()); + void addHeaders(const QString &key, const QString &value); + void enableRequestCompression(); + void enableResponseCompression(); + void abortRequests(); + QString getParamStylePrefix(const QString &style); + QString getParamStyleSuffix(const QString &style); + QString getParamStyleDelimiter(const QString &style, const QString &name, bool isExplode); + + /** + * @param[in] pfx_user PFXUser [required] + */ + void createUser(const PFXUser &pfx_user); + + /** + * @param[in] pfx_user QList [required] + */ + void createUsersWithArrayInput(const QList &pfx_user); + + /** + * @param[in] pfx_user QList [required] + */ + void createUsersWithListInput(const QList &pfx_user); + + /** + * @param[in] username QString [required] + */ + void deleteUser(const QString &username); + + /** + * @param[in] username QString [required] + */ + void getUserByName(const QString &username); + + /** + * @param[in] username QString [required] + * @param[in] password QString [required] + */ + void loginUser(const QString &username, const QString &password); + + + void logoutUser(); + + /** + * @param[in] username QString [required] + * @param[in] pfx_user PFXUser [required] + */ + void updateUser(const QString &username, const PFXUser &pfx_user); + + +private: + QMap _serverIndices; + QMap> _serverConfigs; + QMap _apiKeys; + QString _bearerToken; + QString _username; + QString _password; + int _timeOut; + QString _workingDirectory; + QNetworkAccessManager* _manager; + QMap _defaultHeaders; + bool _isResponseCompressionEnabled; + bool _isRequestCompressionEnabled; + PFXHttpRequestInput _latestInput; + PFXHttpRequestWorker *_latestWorker; + QStringList _latestScope; + OauthCode _authFlow; + OauthImplicit _implicitFlow; + OauthCredentials _credentialFlow; + OauthPassword _passwordFlow; + int _OauthMethod = 0; + + void createUserCallback(PFXHttpRequestWorker *worker); + void createUsersWithArrayInputCallback(PFXHttpRequestWorker *worker); + void createUsersWithListInputCallback(PFXHttpRequestWorker *worker); + void deleteUserCallback(PFXHttpRequestWorker *worker); + void getUserByNameCallback(PFXHttpRequestWorker *worker); + void loginUserCallback(PFXHttpRequestWorker *worker); + void logoutUserCallback(PFXHttpRequestWorker *worker); + void updateUserCallback(PFXHttpRequestWorker *worker); + +Q_SIGNALS: + + void createUserSignal(); + void createUsersWithArrayInputSignal(); + void createUsersWithListInputSignal(); + void deleteUserSignal(); + void getUserByNameSignal(PFXUser summary); + void loginUserSignal(QString summary); + void logoutUserSignal(); + void updateUserSignal(); + + void createUserProgress(qint64 bytesReceived, qint64 bytesTotal); + void createUsersWithArrayInputProgress(qint64 bytesReceived, qint64 bytesTotal); + void createUsersWithListInputProgress(qint64 bytesReceived, qint64 bytesTotal); + void deleteUserProgress(qint64 bytesReceived, qint64 bytesTotal); + void getUserByNameProgress(qint64 bytesReceived, qint64 bytesTotal); + void loginUserProgress(qint64 bytesReceived, qint64 bytesTotal); + void logoutUserProgress(qint64 bytesReceived, qint64 bytesTotal); + void updateUserProgress(qint64 bytesReceived, qint64 bytesTotal); + + void createUserSignalFull(PFXHttpRequestWorker *worker); + void createUsersWithArrayInputSignalFull(PFXHttpRequestWorker *worker); + void createUsersWithListInputSignalFull(PFXHttpRequestWorker *worker); + void deleteUserSignalFull(PFXHttpRequestWorker *worker); + void getUserByNameSignalFull(PFXHttpRequestWorker *worker, PFXUser summary); + void loginUserSignalFull(PFXHttpRequestWorker *worker, QString summary); + void logoutUserSignalFull(PFXHttpRequestWorker *worker); + void updateUserSignalFull(PFXHttpRequestWorker *worker); + + Q_DECL_DEPRECATED_X("Use createUserSignalError() instead") + void createUserSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void createUserSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use createUsersWithArrayInputSignalError() instead") + void createUsersWithArrayInputSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void createUsersWithArrayInputSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use createUsersWithListInputSignalError() instead") + void createUsersWithListInputSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void createUsersWithListInputSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use deleteUserSignalError() instead") + void deleteUserSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void deleteUserSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use getUserByNameSignalError() instead") + void getUserByNameSignalE(PFXUser summary, QNetworkReply::NetworkError error_type, QString error_str); + void getUserByNameSignalError(PFXUser summary, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use loginUserSignalError() instead") + void loginUserSignalE(QString summary, QNetworkReply::NetworkError error_type, QString error_str); + void loginUserSignalError(QString summary, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use logoutUserSignalError() instead") + void logoutUserSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void logoutUserSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use updateUserSignalError() instead") + void updateUserSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void updateUserSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + + Q_DECL_DEPRECATED_X("Use createUserSignalErrorFull() instead") + void createUserSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void createUserSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use createUsersWithArrayInputSignalErrorFull() instead") + void createUsersWithArrayInputSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void createUsersWithArrayInputSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use createUsersWithListInputSignalErrorFull() instead") + void createUsersWithListInputSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void createUsersWithListInputSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use deleteUserSignalErrorFull() instead") + void deleteUserSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void deleteUserSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use getUserByNameSignalErrorFull() instead") + void getUserByNameSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void getUserByNameSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use loginUserSignalErrorFull() instead") + void loginUserSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void loginUserSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use logoutUserSignalErrorFull() instead") + void logoutUserSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void logoutUserSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use updateUserSignalErrorFull() instead") + void updateUserSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void updateUserSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + + void abortRequestsSignal(); + void allPendingRequestsCompleted(); + +public Q_SLOTS: + void tokenAvailable(); +}; + +} // namespace test_namespace +#endif diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXclient.pri b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXclient.pri index 3e4cdfe7449d..dc65e65de723 100644 --- a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXclient.pri +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXclient.pri @@ -2,11 +2,18 @@ QT += network HEADERS += \ # Models + $${PWD}/PFXApiResponse.h \ $${PWD}/PFXCategory.h \ + $${PWD}/PFXOrder.h \ $${PWD}/PFXPet.h \ $${PWD}/PFXTag.h \ + $${PWD}/PFXTestAnyType.h \ + $${PWD}/PFXUser.h \ # APIs $${PWD}/PFXPetApi.h \ + $${PWD}/PFXPrimitivesApi.h \ + $${PWD}/PFXStoreApi.h \ + $${PWD}/PFXUserApi.h \ # Others $${PWD}/PFXHelpers.h \ $${PWD}/PFXHttpRequest.h \ @@ -19,11 +26,18 @@ HEADERS += \ SOURCES += \ # Models + $${PWD}/PFXApiResponse.cpp \ $${PWD}/PFXCategory.cpp \ + $${PWD}/PFXOrder.cpp \ $${PWD}/PFXPet.cpp \ $${PWD}/PFXTag.cpp \ + $${PWD}/PFXTestAnyType.cpp \ + $${PWD}/PFXUser.cpp \ # APIs $${PWD}/PFXPetApi.cpp \ + $${PWD}/PFXPrimitivesApi.cpp \ + $${PWD}/PFXStoreApi.cpp \ + $${PWD}/PFXUserApi.cpp \ # Others $${PWD}/PFXHelpers.cpp \ $${PWD}/PFXHttpRequest.cpp \ diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/pom.xml b/samples/client/petstore/cpp-qt-addDownloadProgress/pom.xml new file mode 100644 index 000000000000..70cf260fde76 --- /dev/null +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + org.openapitools + CppQt5PetstoreClientTests + pom + 1.0-SNAPSHOT + Qt5 OpenAPI Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + pet-test + integration-test + + exec + + + ./build-and-test.bash + + + + + + +