From 66864f366025a54944bd91529304bd8ee5072f72 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Mon, 5 Aug 2024 15:38:57 +0800 Subject: [PATCH] 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