From 5c27abb277f0bd9904b663284d77b1cff1312d65 Mon Sep 17 00:00:00 2001 From: Anders Aaen Springborg Date: Mon, 24 May 2021 05:11:44 +0200 Subject: [PATCH] New generator | Arduino cpp (#9489) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * initil tiny client generator * Helper string * WIP: added helper file with json helper functions * WIP: model implementation.. Working on JSON * Added codegen files for model and helper * WIP: toJson() * Added mapping configurations * Upadet string compare * Removed redundant namespaces * Added files for example * fixed syntax errors * fixed syntax errors * header generation * unittest example for pet class * Refactored mustache & fixed logical errors * WIP: unit test mustache format * Removed legacy file * mustache service * Declare service in Java file * Removed legacy file * removed legacy code * Documentation * Added folder structure + new supporting files * Added file to run all unittests * Refactored unit tests * typemappings and new paths * First service impl * Added esp32 and esp8266 env * Added default values * Added cli option to specify controller * added type decl method * Added stringify methods * service get requests * Fix helper header * post merge fix * fix long test * Tiny namespace * remove shared pointer * include petapi * stringify * return problems * Canged logic for response-body handling * Implemented last logic for reponse handeling * Implemented constructor logic * first tiny sample * update basepath to petstore v3 * standard main example * root certificate example * root folder * TODO cleanup * exclude features * supports delete again!πŸ‘· * remove todo ❌ * new main example ❣️ * new main example ❣️ * Make our feature set realistic * fix indentation * HTTP / HTTPS Connection * Root certificate sample * https vs http πŸ‘¨πŸ»β€πŸ”¬ * fix lint in template * default value for controller in config * new readme πŸ“œ * remove old comments * removed unused testfile * no default root certificate * new main * remove test * Update platformio.ini.mustache πŸ€·β€β™‚οΈ * Update platformio.ini.mustache remove native * added support info * Add namespace to Pet πŸ… * bourne compatibility fix * spelling error in python file * bourne python script 🐍 * Version bump * Add bourne script to readme * update main sample, from template * pre_compiling_bourne.py.mustache to samples folder πŸ“ƒ * set header Content'type to json * map todoπŸ—ΊοΈ * remove unused debug flagβš’οΈ * added support for ESP8266 ΰΌΌ ぀ β—•_β—• ༽぀ * added new sample for ESP32 πŸ“€ * 🎯 * removed use of namespace std ❌ * removed use of "__" in variables * removed unused code in destructor * fixed type comparison * move default ctor to header * added zero initialized primitive variables * moved variable to TypeMappings * updated ifndefines * Extra comment for build error in standard example πŸ¦ΈπŸ½β€ * afer cpp-ish cast from std::string to uint8* cast🏰 * excluded maps type * Documentation og generator Co-authored-by: kaareHH Co-authored-by: mkakbas <45030188+mkakbas@users.noreply.github.com> Co-authored-by: mkakbas --- bin/configs/tiny-cpp-client-petstore-new.yaml | 7 + docs/generators/tiny-cpp.md | 243 ++++++++++ .../languages/TinyCppClientCodegen.java | 338 ++++++++++++++ .../org.openapitools.codegen.CodegenConfig | 1 + .../resources/tiny-cpp-client/README.mustache | 43 ++ .../tiny-cpp-client/helpers-body.mustache | 102 +++++ .../tiny-cpp-client/helpers-header.mustache | 22 + .../resources/tiny-cpp-client/main.mustache | 40 ++ .../tiny-cpp-client/model-body.mustache | 160 +++++++ .../tiny-cpp-client/model-header.mustache | 81 ++++ .../tiny-cpp-client/platformio.ini.mustache | 19 + .../pre_compiling_bourne.py.mustache | 25 ++ .../tiny-cpp-client/root.cert.mustache | 53 +++ .../tiny-cpp-client/run-tests.mustache | 44 ++ .../service/AbstractService.cpp.mustache | 15 + .../service/AbstractService.h.mustache | 39 ++ .../service/Response.h.mustache | 25 ++ .../tiny-cpp-client/service/api-body.mustache | 219 +++++++++ .../service/api-header.mustache | 74 ++++ .../tiny-cpp-client/unit-test-model.mustache | 161 +++++++ .../tiny-cpp-client/unittest.mustache | 132 ++++++ samples/client/petstore/tiny/cpp/.gitignore | 5 + .../tiny/cpp/.openapi-generator-ignore | 23 + .../tiny/cpp/.openapi-generator/FILES | 30 ++ .../tiny/cpp/.openapi-generator/VERSION | 1 + samples/client/petstore/tiny/cpp/README.md | 73 +++ .../tiny/cpp/lib/Models/ApiResponse.cpp | 139 ++++++ .../tiny/cpp/lib/Models/ApiResponse.h | 78 ++++ .../petstore/tiny/cpp/lib/Models/Category.cpp | 106 +++++ .../petstore/tiny/cpp/lib/Models/Category.h | 70 +++ .../petstore/tiny/cpp/lib/Models/Helpers.cpp | 102 +++++ .../petstore/tiny/cpp/lib/Models/Helpers.h | 22 + .../petstore/tiny/cpp/lib/Models/Order.cpp | 238 ++++++++++ .../petstore/tiny/cpp/lib/Models/Order.h | 102 +++++ .../petstore/tiny/cpp/lib/Models/Pet.cpp | 274 ++++++++++++ .../client/petstore/tiny/cpp/lib/Models/Pet.h | 105 +++++ .../petstore/tiny/cpp/lib/Models/Tag.cpp | 106 +++++ .../client/petstore/tiny/cpp/lib/Models/Tag.h | 70 +++ .../petstore/tiny/cpp/lib/Models/User.cpp | 304 +++++++++++++ .../petstore/tiny/cpp/lib/Models/User.h | 118 +++++ .../cpp/lib/TestFiles/ApiResponseTest.cpp | 139 ++++++ .../tiny/cpp/lib/TestFiles/CategoryTest.cpp | 97 ++++ .../tiny/cpp/lib/TestFiles/OrderTest.cpp | 245 ++++++++++ .../tiny/cpp/lib/TestFiles/PetTest.cpp | 145 ++++++ .../tiny/cpp/lib/TestFiles/TagTest.cpp | 97 ++++ .../tiny/cpp/lib/TestFiles/UserTest.cpp | 349 +++++++++++++++ .../tiny/cpp/lib/service/AbstractService.cpp | 8 + .../tiny/cpp/lib/service/AbstractService.h | 28 ++ .../petstore/tiny/cpp/lib/service/PetApi.cpp | 418 ++++++++++++++++++ .../petstore/tiny/cpp/lib/service/PetApi.h | 163 +++++++ .../petstore/tiny/cpp/lib/service/Response.h | 25 ++ .../tiny/cpp/lib/service/StoreApi.cpp | 185 ++++++++ .../petstore/tiny/cpp/lib/service/StoreApi.h | 83 ++++ .../petstore/tiny/cpp/lib/service/UserApi.cpp | 366 +++++++++++++++ .../petstore/tiny/cpp/lib/service/UserApi.h | 147 ++++++ .../client/petstore/tiny/cpp/platformio.ini | 7 + .../petstore/tiny/cpp/pre_compiling_bourne.py | 25 ++ samples/client/petstore/tiny/cpp/root.cert | 53 +++ samples/client/petstore/tiny/cpp/src/main.cpp | 37 ++ .../petstore/tiny/cpp/test/RunTests.cpp | 204 +++++++++ 60 files changed, 6630 insertions(+) create mode 100644 bin/configs/tiny-cpp-client-petstore-new.yaml create mode 100644 docs/generators/tiny-cpp.md create mode 100644 modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TinyCppClientCodegen.java create mode 100644 modules/openapi-generator/src/main/resources/tiny-cpp-client/README.mustache create mode 100644 modules/openapi-generator/src/main/resources/tiny-cpp-client/helpers-body.mustache create mode 100644 modules/openapi-generator/src/main/resources/tiny-cpp-client/helpers-header.mustache create mode 100644 modules/openapi-generator/src/main/resources/tiny-cpp-client/main.mustache create mode 100644 modules/openapi-generator/src/main/resources/tiny-cpp-client/model-body.mustache create mode 100644 modules/openapi-generator/src/main/resources/tiny-cpp-client/model-header.mustache create mode 100644 modules/openapi-generator/src/main/resources/tiny-cpp-client/platformio.ini.mustache create mode 100644 modules/openapi-generator/src/main/resources/tiny-cpp-client/pre_compiling_bourne.py.mustache create mode 100644 modules/openapi-generator/src/main/resources/tiny-cpp-client/root.cert.mustache create mode 100644 modules/openapi-generator/src/main/resources/tiny-cpp-client/run-tests.mustache create mode 100644 modules/openapi-generator/src/main/resources/tiny-cpp-client/service/AbstractService.cpp.mustache create mode 100644 modules/openapi-generator/src/main/resources/tiny-cpp-client/service/AbstractService.h.mustache create mode 100644 modules/openapi-generator/src/main/resources/tiny-cpp-client/service/Response.h.mustache create mode 100644 modules/openapi-generator/src/main/resources/tiny-cpp-client/service/api-body.mustache create mode 100644 modules/openapi-generator/src/main/resources/tiny-cpp-client/service/api-header.mustache create mode 100644 modules/openapi-generator/src/main/resources/tiny-cpp-client/unit-test-model.mustache create mode 100644 modules/openapi-generator/src/main/resources/tiny-cpp-client/unittest.mustache create mode 100644 samples/client/petstore/tiny/cpp/.gitignore create mode 100644 samples/client/petstore/tiny/cpp/.openapi-generator-ignore create mode 100644 samples/client/petstore/tiny/cpp/.openapi-generator/FILES create mode 100644 samples/client/petstore/tiny/cpp/.openapi-generator/VERSION create mode 100644 samples/client/petstore/tiny/cpp/README.md create mode 100644 samples/client/petstore/tiny/cpp/lib/Models/ApiResponse.cpp create mode 100644 samples/client/petstore/tiny/cpp/lib/Models/ApiResponse.h create mode 100644 samples/client/petstore/tiny/cpp/lib/Models/Category.cpp create mode 100644 samples/client/petstore/tiny/cpp/lib/Models/Category.h create mode 100644 samples/client/petstore/tiny/cpp/lib/Models/Helpers.cpp create mode 100644 samples/client/petstore/tiny/cpp/lib/Models/Helpers.h create mode 100644 samples/client/petstore/tiny/cpp/lib/Models/Order.cpp create mode 100644 samples/client/petstore/tiny/cpp/lib/Models/Order.h create mode 100644 samples/client/petstore/tiny/cpp/lib/Models/Pet.cpp create mode 100644 samples/client/petstore/tiny/cpp/lib/Models/Pet.h create mode 100644 samples/client/petstore/tiny/cpp/lib/Models/Tag.cpp create mode 100644 samples/client/petstore/tiny/cpp/lib/Models/Tag.h create mode 100644 samples/client/petstore/tiny/cpp/lib/Models/User.cpp create mode 100644 samples/client/petstore/tiny/cpp/lib/Models/User.h create mode 100644 samples/client/petstore/tiny/cpp/lib/TestFiles/ApiResponseTest.cpp create mode 100644 samples/client/petstore/tiny/cpp/lib/TestFiles/CategoryTest.cpp create mode 100644 samples/client/petstore/tiny/cpp/lib/TestFiles/OrderTest.cpp create mode 100644 samples/client/petstore/tiny/cpp/lib/TestFiles/PetTest.cpp create mode 100644 samples/client/petstore/tiny/cpp/lib/TestFiles/TagTest.cpp create mode 100644 samples/client/petstore/tiny/cpp/lib/TestFiles/UserTest.cpp create mode 100644 samples/client/petstore/tiny/cpp/lib/service/AbstractService.cpp create mode 100644 samples/client/petstore/tiny/cpp/lib/service/AbstractService.h create mode 100644 samples/client/petstore/tiny/cpp/lib/service/PetApi.cpp create mode 100644 samples/client/petstore/tiny/cpp/lib/service/PetApi.h create mode 100644 samples/client/petstore/tiny/cpp/lib/service/Response.h create mode 100644 samples/client/petstore/tiny/cpp/lib/service/StoreApi.cpp create mode 100644 samples/client/petstore/tiny/cpp/lib/service/StoreApi.h create mode 100644 samples/client/petstore/tiny/cpp/lib/service/UserApi.cpp create mode 100644 samples/client/petstore/tiny/cpp/lib/service/UserApi.h create mode 100644 samples/client/petstore/tiny/cpp/platformio.ini create mode 100644 samples/client/petstore/tiny/cpp/pre_compiling_bourne.py create mode 100644 samples/client/petstore/tiny/cpp/root.cert create mode 100644 samples/client/petstore/tiny/cpp/src/main.cpp create mode 100644 samples/client/petstore/tiny/cpp/test/RunTests.cpp diff --git a/bin/configs/tiny-cpp-client-petstore-new.yaml b/bin/configs/tiny-cpp-client-petstore-new.yaml new file mode 100644 index 000000000000..e80824e989a6 --- /dev/null +++ b/bin/configs/tiny-cpp-client-petstore-new.yaml @@ -0,0 +1,7 @@ +generatorName: tiny-cpp +outputDir: samples/client/petstore/tiny/cpp +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/tiny-cpp-client +additionalProperties: + hideGenerationTimestamp: "true" + controller: "esp32" diff --git a/docs/generators/tiny-cpp.md b/docs/generators/tiny-cpp.md new file mode 100644 index 000000000000..cd3877236ec7 --- /dev/null +++ b/docs/generators/tiny-cpp.md @@ -0,0 +1,243 @@ +--- +title: Config Options for tiny-cpp +sidebar_label: tiny-cpp +--- + +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|controller|name of microcontroller (e.g esp32 or esp8266)| |esp32| +|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
|true| +|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| +|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|reservedWordPrefix|Prefix to prepend to reserved words in order to avoid conflicts| |r_| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|variableNameFirstCharacterUppercase|Make first character of variable name uppercase (eg. value -> Value)| |true| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | + + +## LANGUAGE PRIMITIVES + +
    +
  • bool
  • +
  • double
  • +
  • float
  • +
  • int
  • +
  • long
  • +
  • std::string
  • +
+ +## RESERVED WORDS + +
    +
  • alignas
  • +
  • alignof
  • +
  • and
  • +
  • and_eq
  • +
  • asm
  • +
  • auto
  • +
  • bitand
  • +
  • bitor
  • +
  • bool
  • +
  • break
  • +
  • case
  • +
  • catch
  • +
  • char
  • +
  • char16_t
  • +
  • char32_t
  • +
  • class
  • +
  • compl
  • +
  • concept
  • +
  • const
  • +
  • const_cast
  • +
  • constexpr
  • +
  • continue
  • +
  • decltype
  • +
  • default
  • +
  • delete
  • +
  • do
  • +
  • double
  • +
  • dynamic_cast
  • +
  • else
  • +
  • enum
  • +
  • explicit
  • +
  • export
  • +
  • extern
  • +
  • false
  • +
  • float
  • +
  • for
  • +
  • friend
  • +
  • goto
  • +
  • if
  • +
  • inline
  • +
  • int
  • +
  • linux
  • +
  • long
  • +
  • mutable
  • +
  • namespace
  • +
  • new
  • +
  • noexcept
  • +
  • not
  • +
  • not_eq
  • +
  • nullptr
  • +
  • operator
  • +
  • or
  • +
  • or_eq
  • +
  • private
  • +
  • protected
  • +
  • public
  • +
  • register
  • +
  • reinterpret_cast
  • +
  • requires
  • +
  • return
  • +
  • short
  • +
  • signed
  • +
  • sizeof
  • +
  • static
  • +
  • static_assert
  • +
  • static_cast
  • +
  • struct
  • +
  • switch
  • +
  • template
  • +
  • this
  • +
  • thread_local
  • +
  • throw
  • +
  • true
  • +
  • try
  • +
  • typedef
  • +
  • typeid
  • +
  • typename
  • +
  • union
  • +
  • unsigned
  • +
  • using
  • +
  • virtual
  • +
  • void
  • +
  • volatile
  • +
  • wchar_t
  • +
  • while
  • +
  • xor
  • +
  • xor_eq
  • +
+ +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|βœ—|ToolingExtension +|Authorizations|βœ—|ToolingExtension +|UserAgent|βœ—|ToolingExtension +|MockServer|βœ—|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|βœ—|OAS2,OAS3 +|Int32|βœ“|OAS2,OAS3 +|Int64|βœ“|OAS2,OAS3 +|Float|βœ“|OAS2,OAS3 +|Double|βœ“|OAS2,OAS3 +|Decimal|βœ“|ToolingExtension +|String|βœ“|OAS2,OAS3 +|Byte|βœ“|OAS2,OAS3 +|Binary|βœ“|OAS2,OAS3 +|Boolean|βœ“|OAS2,OAS3 +|Date|βœ“|OAS2,OAS3 +|DateTime|βœ“|OAS2,OAS3 +|Password|βœ“|OAS2,OAS3 +|File|βœ“|OAS2 +|Array|βœ“|OAS2,OAS3 +|Maps|βœ—|ToolingExtension +|CollectionFormat|βœ“|OAS2 +|CollectionFormatMulti|βœ“|OAS2 +|Enum|βœ“|OAS2,OAS3 +|ArrayOfEnum|βœ“|ToolingExtension +|ArrayOfModel|βœ“|ToolingExtension +|ArrayOfCollectionOfPrimitives|βœ“|ToolingExtension +|ArrayOfCollectionOfModel|βœ“|ToolingExtension +|ArrayOfCollectionOfEnum|βœ“|ToolingExtension +|MapOfEnum|βœ—|ToolingExtension +|MapOfModel|βœ—|ToolingExtension +|MapOfCollectionOfPrimitives|βœ—|ToolingExtension +|MapOfCollectionOfModel|βœ—|ToolingExtension +|MapOfCollectionOfEnum|βœ—|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|βœ“|ToolingExtension +|Model|βœ“|ToolingExtension +|Api|βœ“|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|βœ“|OAS2,OAS3 +|BasePath|βœ“|OAS2,OAS3 +|Info|βœ“|OAS2,OAS3 +|Schemes|βœ—|OAS2,OAS3 +|PartialSchemes|βœ“|OAS2,OAS3 +|Consumes|βœ“|OAS2 +|Produces|βœ“|OAS2 +|ExternalDocumentation|βœ“|OAS2,OAS3 +|Examples|βœ“|OAS2,OAS3 +|XMLStructureDefinitions|βœ—|OAS2,OAS3 +|MultiServer|βœ—|OAS3 +|ParameterizedServer|βœ—|OAS3 +|ParameterStyling|βœ—|OAS3 +|Callbacks|βœ—|OAS3 +|LinkObjects|βœ—|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|βœ“|OAS2,OAS3 +|Query|βœ—|OAS2,OAS3 +|Header|βœ—|OAS2,OAS3 +|Body|βœ“|OAS2 +|FormUnencoded|βœ—|OAS2 +|FormMultipart|βœ—|OAS2 +|Cookie|βœ—|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|βœ“|OAS2,OAS3 +|Composite|βœ“|OAS2,OAS3 +|Polymorphism|βœ—|OAS2,OAS3 +|Union|βœ—|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|βœ“|OAS2,OAS3 +|ApiKey|βœ“|OAS2,OAS3 +|OpenIDConnect|βœ—|OAS3 +|BearerToken|βœ“|OAS3 +|OAuth2_Implicit|βœ“|OAS2,OAS3 +|OAuth2_Password|βœ“|OAS2,OAS3 +|OAuth2_ClientCredentials|βœ“|OAS2,OAS3 +|OAuth2_AuthorizationCode|βœ“|OAS2,OAS3 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|βœ“|OAS2,OAS3 +|XML|βœ—|OAS2,OAS3 +|PROTOBUF|βœ—|ToolingExtension +|Custom|βœ—|OAS2,OAS3 diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TinyCppClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TinyCppClientCodegen.java new file mode 100644 index 000000000000..91a9a95b5e41 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TinyCppClientCodegen.java @@ -0,0 +1,338 @@ +package org.openapitools.codegen.languages; + +import org.openapitools.codegen.*; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.parser.util.SchemaTypeUtil; +import org.openapitools.codegen.meta.features.*; +import org.openapitools.codegen.utils.ModelUtils; + +import java.io.File; +import java.util.*; + +import org.apache.commons.lang3.StringUtils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TinyCppClientCodegen extends AbstractCppCodegen implements CodegenConfig { + public static final String PROJECT_NAME = "TinyClient"; + + static final Logger LOGGER = LoggerFactory.getLogger(TinyCppClientCodegen.class); + + public static final String MICROCONTROLLER = "controller"; + public static final String rootFolder = ""; + protected String controller = "esp32"; + + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + /** + * Configures a friendly name for the generator. This will be used by the + * generator to select the library with the -g flag. + * + * @return the friendly name for the generator + */ + public String getName() { + return "tiny-cpp"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with + * help tips, parameters here + * + * @return A string value for the help message + */ + public String getHelp() { + return "Generates a Arduino rest client."; + } + + public void addControllerToAdditionalProperties(){ + Map supportedControllers = new HashMap(){{ + put("esp32", "isESP32"); + put("esp8266", "isESP8266"); + }}; + if (supportedControllers.containsKey(controller)) { + additionalProperties.put(supportedControllers.get(controller), true); + } + else { + //String msg = String.format("The specified controller: %s is not supported.\nSupported controllers are: %s", + // controller, + // supportedControllers.keySet()); + throw new UnsupportedOperationException("Supported controllers are: ESP32, ESP8266"); + } + } + + public TinyCppClientCodegen() { + super(); + + modifyFeatureSet(feature -> feature + .excludeGlobalFeatures( + GlobalFeature.XMLStructureDefinitions, + GlobalFeature.Callbacks, + GlobalFeature.LinkObjects, + GlobalFeature.ParameterStyling, + GlobalFeature.MultiServer) + .excludeSchemaSupportFeatures( + SchemaSupportFeature.Polymorphism + ) + .excludeParameterFeatures( + ParameterFeature.Cookie, + ParameterFeature.Header, + ParameterFeature.FormUnencoded, + ParameterFeature.FormMultipart, + ParameterFeature.Query + ) + .excludeDataTypeFeatures( + DataTypeFeature.Enum, + DataTypeFeature.Maps, + DataTypeFeature.MapOfCollectionOfEnum, + DataTypeFeature.MapOfCollectionOfModel, + DataTypeFeature.MapOfCollectionOfPrimitives, + DataTypeFeature.MapOfEnum, + DataTypeFeature.MapOfModel + + ) + .excludeWireFormatFeatures( + WireFormatFeature.XML, + WireFormatFeature.PROTOBUF, + WireFormatFeature.Custom + ) + .includeDocumentationFeatures( + DocumentationFeature.Readme + )); + + outputFolder = "generated-code" + File.separator + "tiny-cpp"; + embeddedTemplateDir = templateDir = "tiny-cpp-client"; + + String libFolder = "lib"; + // MODELS + modelPackage = libFolder + File.separator + "Models"; + modelTemplateFiles.put("model-header.mustache", ".h"); + modelTemplateFiles.put("model-body.mustache", ".cpp"); + + // MODELS: Helpers + supportingFiles.add(new SupportingFile("helpers-header.mustache", modelPackage, "Helpers.h")); + supportingFiles.add(new SupportingFile("helpers-body.mustache", modelPackage, "Helpers.cpp")); + + // MODELS: TESTS + testPackage = libFolder + File.separator + "TestFiles"; + modelTestTemplateFiles.put("unit-test-model.mustache", ".cpp"); + supportingFiles.add(new SupportingFile("run-tests.mustache", "test", "RunTests.cpp")); + + // SERVICES + apiPackage = TinyCppClientCodegen.libFolder + File.separator + "service"; + apiTemplateFiles.put("service/api-header.mustache".replace('/', File.separatorChar), ".h"); + apiTemplateFiles.put("service/api-body.mustache".replace('/', File.separatorChar), ".cpp"); + + // SERVICES: Helpers + supportingFiles.add(new SupportingFile("service/Response.h.mustache", serviceFolder, "Response.h")); + supportingFiles.add(new SupportingFile("service/AbstractService.h.mustache", serviceFolder, "AbstractService.h")); + supportingFiles.add(new SupportingFile("service/AbstractService.cpp.mustache", serviceFolder, "AbstractService.cpp")); + + + // Main + supportingFiles.add(new SupportingFile("main.mustache", TinyCppClientCodegen.sourceFolder, "main.cpp")); + + // Config files + supportingFiles.add(new SupportingFile("README.mustache", rootFolder, "README.md")); + supportingFiles.add(new SupportingFile("platformio.ini.mustache", rootFolder, "platformio.ini")); + supportingFiles.add(new SupportingFile("root.cert.mustache", rootFolder, "root.cert")); + supportingFiles.add(new SupportingFile("README.mustache", rootFolder, "README.md")); + supportingFiles.add(new SupportingFile("pre_compiling_bourne.py.mustache", rootFolder, "pre_compiling_bourne.py")); + + + + defaultIncludes = new HashSet( + Arrays.asList( + "bool", + "int", + "long", + "double", + "float") + ); + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "bool", + "int", + "long", + "double", + "float", + "std::string") + ); + + + + + + super.typeMapping = new HashMap(); + typeMapping.put("string", "std::string"); + typeMapping.put("integer", "int"); + typeMapping.put("boolean", "bool"); + typeMapping.put("array", "std::list"); + typeMapping.put("DateTime", "std::string"); + + cliOptions.add(new CliOption(MICROCONTROLLER, "name of microcontroller (e.g esp32 or esp8266)"). + defaultValue("esp32")); + + makeTypeMappings(); + + } + + + // FilePaths + private static final String sourceFolder = "src"; + private static final String libFolder = "lib"; + private static final String serviceFolder = libFolder + File.separator + "service"; + + @Override + public String getTypeDeclaration(String str) { + return str; + } + + private void makeTypeMappings() { + // Types + String cpp_array_type = "std::list"; + typeMapping = new HashMap<>(); + + typeMapping.put("string", "std::string"); + typeMapping.put("integer", "int"); + typeMapping.put("float", "float"); + typeMapping.put("long", "long"); + typeMapping.put("boolean", "bool"); + typeMapping.put("double", "double"); + typeMapping.put("array", cpp_array_type); + typeMapping.put("number", "long"); + typeMapping.put("binary", "std::string"); + typeMapping.put("password", "std::string"); + typeMapping.put("file", "std::string"); + typeMapping.put("DateTime", "std::string"); + typeMapping.put("Date", "std::string"); + typeMapping.put("UUID", "std::string"); + typeMapping.put("URI", "std::string"); + } + + + + @Override + public void processOpts() { + super.processOpts(); + // Throw exception if http and esp8266 + + // -- --additional-properties=controller= + if (additionalProperties.containsKey(MICROCONTROLLER)) { + controller = additionalProperties.get(MICROCONTROLLER).toString(); + } + + addControllerToAdditionalProperties(); + + LOGGER.info("Generator targeting the following microcontroller: {}", controller); + } + + + @Override + public String toInstantiationType(Schema p) { + if (ModelUtils.isArraySchema(p)) { + return instantiationTypes.get("array"); + } else { + return null; + } + } + + + @Override + public String getTypeDeclaration(Schema p) { + String openAPIType = getSchemaType(p); + if (languageSpecificPrimitives.contains(openAPIType)) { + return toModelName(openAPIType); + } else { + return openAPIType + ""; + } + } + + + @Override + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); + String type = null; + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); + if (languageSpecificPrimitives.contains(type)) { + return toModelName(type); + } + } else { + type = openAPIType; + } + return toModelName(type); + } + + @Override + public String toModelName(String type) { + if (typeMapping.keySet().contains(type) || + typeMapping.values().contains(type) || + defaultIncludes.contains(type) || + languageSpecificPrimitives.contains(type)) { + return type; + } else { + return Character.toUpperCase(type.charAt(0)) + type.substring(1); + } + } + + @Override + public String toModelImport(String name) { + if (name.equals("std::string")) { + return "#include "; + } else if (name.equals("std::list")) { + return "#include "; + } else if (name.equals("Map")) { + return "#include "; + } + return "#include \"" + name + ".h\""; + } + + + + @Override + public String toApiImport(String name) { + return super.toApiImport(name); + } + + @Override + public String toVarName(String name) { + String paramName = name.replaceAll("[^a-zA-Z0-9_]", ""); + if (name.length() > 0 ) { + paramName = Character.toLowerCase(paramName.charAt(0)) + paramName.substring(1); + } + if (isReservedWord(paramName)) { + return escapeReservedWord(paramName); + } + return "" + paramName; + } + + public String toDefaultValue(Schema p) { + if (ModelUtils.isBooleanSchema(p)) { + return "bool(false)"; + } else if (ModelUtils.isNumberSchema(p)) { + return "float(0)"; + } else if (ModelUtils.isIntegerSchema(p)) { + if (SchemaTypeUtil.INTEGER64_FORMAT.equals(p.getFormat())) { + return "long(0)"; + } + return "int(0)"; + } else if (ModelUtils.isArraySchema(p)) { + return "std::list"; + } else if (!StringUtils.isEmpty(p.get$ref())) { + return toModelName(ModelUtils.getSimpleRef(p.get$ref())) + "()"; + } else if (ModelUtils.isDateSchema(p) || ModelUtils.isDateTimeSchema(p)) { + return "std::string()"; + } else if (ModelUtils.isStringSchema(p)) { + return "std::string()"; + } + return "null"; + } + + + + +} diff --git a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig index eacec0f51278..1d4ef4f2568a 100644 --- a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig +++ b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig @@ -132,4 +132,5 @@ org.openapitools.codegen.languages.TypeScriptNestjsClientCodegen org.openapitools.codegen.languages.TypeScriptNodeClientCodegen org.openapitools.codegen.languages.TypeScriptReduxQueryClientCodegen org.openapitools.codegen.languages.TypeScriptRxjsClientCodegen +org.openapitools.codegen.languages.TinyCppClientCodegen org.openapitools.codegen.languages.GoEchoServerCodegen diff --git a/modules/openapi-generator/src/main/resources/tiny-cpp-client/README.mustache b/modules/openapi-generator/src/main/resources/tiny-cpp-client/README.mustache new file mode 100644 index 000000000000..e749562a0aa3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/tiny-cpp-client/README.mustache @@ -0,0 +1,43 @@ +# Documentation for OpenAPI Petstore +This is a client generator for microcontrollers on the Espressif32 platform and the Arduino framework +After the client have been generated, you have to change these following variablies: +- root.cert | Provide your service root certificate. +- src/main.cpp | Change wifi name +- src/main.cpp | Change wifi password +- lib/service/AbstractService.h | Change to your url + +# Documentation for {{#openAPI}}{{#info}}{{title}} {{version}} Tiny client cpp (Arduino) {{/info}}{{/openAPI}} + +The project is structured like this: +``` +samples/client/petstore/tiny/cpp/ +β”œβ”€β”€ lib +β”‚ β”œβ”€β”€ Models +β”‚ β”œβ”€β”€ service +β”‚ └── TestFiles +β”œβ”€β”€ platformio.ini +β”œβ”€β”€ pre_compiling_bourne.py +β”œβ”€β”€ README.md +β”œβ”€β”€ root.cert +β”œβ”€β”€ src +β”‚ └── main.cpp +└── test + └── RunTests.cpp +``` + +All URIs are relative to {{{scheme}}}://{{{host}}}{{{basePath}}} +{{#apiInfo}}{{#apis}}{{#operations}} +### {{classname}} +|Method | HTTP request | Description| +|------------- | ------------- | -------------| + {{#operation}} +|*{{operationId}}* | *{{httpMethod}}* {{{path}}} | {{{summary}}}.| + {{/operation}} +{{/operations}}{{/apis}}{{/apiInfo}} + +## What are the Model files for the data structures/objects? +|Class | Description| +|------------- | -------------| +{{#models}}{{#model}}|*{{classname}}* | {{{description}}}| +{{/model}}{{/models}} + diff --git a/modules/openapi-generator/src/main/resources/tiny-cpp-client/helpers-body.mustache b/modules/openapi-generator/src/main/resources/tiny-cpp-client/helpers-body.mustache new file mode 100644 index 000000000000..c3935b37cde9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/tiny-cpp-client/helpers-body.mustache @@ -0,0 +1,102 @@ +#include "Helpers.h" +#include +#include + +bool isprimitive(std::string type){ + if(type == "std::string" || + type == "int" || + type == "float" || + type == "long" || + type == "double" || + type == "bool" || + type == "std::map" || + type == "std::list") + { + return true; + } + return false; +} + + +void +jsonToValue(void* target, bourne::json value, std::string type) +{ + if (target == NULL || value.is_null()) { + return; + } + + else if (type.compare("bool") == 0) + { + bool* val = static_cast (target); + *val = value.to_bool(); + } + + else if (type.compare("int") == 0) + { + int* val = static_cast (target); + *val = value.to_int(); + } + + else if (type.compare("float") == 0) + { + float* val = static_cast (target); + *val = (float)(value.to_float()); + } + + else if (type.compare("long") == 0) + { + long* val = static_cast (target); + *val = (long)(value.to_int()); + } + + else if (type.compare("double") == 0) + { + double* val = static_cast (target); + *val = value.to_float(); + } + + else if (type.compare("std::string") == 0) + { + std::string* val = static_cast (target); + *val = value.to_string(); + } + else { + return; + } +} + +std::string +stringify(long input){ + std::stringstream stream; + stream << input; + return stream.str(); + +}; + +std::string +stringify(int input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(double input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(float input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(std::string input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; diff --git a/modules/openapi-generator/src/main/resources/tiny-cpp-client/helpers-header.mustache b/modules/openapi-generator/src/main/resources/tiny-cpp-client/helpers-header.mustache new file mode 100644 index 000000000000..5ef7d9afdf77 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/tiny-cpp-client/helpers-header.mustache @@ -0,0 +1,22 @@ +#ifndef TINY_CPP_CLIENT_HELPERS_H_ +#define TINY_CPP_CLIENT_HELPERS_H_ + +#include +#include "bourne/json.hpp" + +bool isprimitive(std::string type); + +void jsonToValue(void* target, bourne::json value, std::string type); + +std::string stringify(long input); + +std::string stringify(int input); + +std::string stringify(double input); + +std::string stringify(float input); + +std::string stringify(std::string input); + +#endif /* TINY_CPP_CLIENT_HELPERS_H_ */ + diff --git a/modules/openapi-generator/src/main/resources/tiny-cpp-client/main.mustache b/modules/openapi-generator/src/main/resources/tiny-cpp-client/main.mustache new file mode 100644 index 000000000000..56170a91e0fc --- /dev/null +++ b/modules/openapi-generator/src/main/resources/tiny-cpp-client/main.mustache @@ -0,0 +1,40 @@ +#include "PetApi.h" +{{#isESP8266}} +#include "ESP8266WiFi.h" +{{/isESP8266}} + +const char* ssid = "your wifi name"; // TODO Change wifi name +const char* password = "Your wifi password"; //TODO Change wifi password + + +void setup(){ + //Initialize serial and wait for port to open: + Serial.begin(9600); + delay(100); + + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + WiFi.begin(ssid, password); + + // attempt to connect to Wifi network: + while (WiFi.status() != WL_CONNECTED) { + Serial.print("."); + // wait 1 second for re-trying + delay(1000); + } + + Serial.print("Connected to "); + Serial.println(ssid); + + //Print LAN IP. + Serial.print("IP address set: "); + Serial.println(WiFi.localIP()); + + Tiny::PetApi petapi; + auto resp = petapi.getPetById(10); + Serial.println(resp.code); + Tiny::Pet pet = resp.obj; + Serial.println(pet.toJson().dump().c_str()); +} + +void loop(){} diff --git a/modules/openapi-generator/src/main/resources/tiny-cpp-client/model-body.mustache b/modules/openapi-generator/src/main/resources/tiny-cpp-client/model-body.mustache new file mode 100644 index 000000000000..b2f2ee66fd9d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/tiny-cpp-client/model-body.mustache @@ -0,0 +1,160 @@ + +{{#models}}{{#model}} +#include "{{classname}}.h" + +using namespace Tiny; + +{{classname}}::{{classname}}() +{ + {{#vars}} + {{#isContainer}} + {{name}} = {{defaultValue}}<{{#items}}{{baseType}}{{/items}}>(); + {{/isContainer}} + {{^isContainer}} + {{name}} = {{defaultValue}}; + {{/isContainer}} + {{/vars}} +} + +{{classname}}::{{classname}}(std::string jsonString) +{ + this->fromJson(jsonString); +} + +{{classname}}::~{{classname}}() +{ + +} + +void +{{classname}}::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + {{#vars}} + const char *{{name}}Key = "{{baseName}}"; + + if(object.has_key({{name}}Key)) + { + bourne::json value = object[{{name}}Key]; + + {{#isContainer}} + {{#isArray}} + + std::list<{{#items}}{{dataType}}{{/items}}> {{name}}_list; + {{#items}}{{dataType}}{{/items}} element; + for(auto& var : value.array_range()) + { + {{#items}} + + {{#isPrimitiveType}} + jsonToValue(&element, var, "{{dataType}}"); + {{/isPrimitiveType}} + + {{^isPrimitiveType}} + element.fromJson(var.dump()); + {{/isPrimitiveType}} + + {{/items}} + {{name}}_list.push_back(element); + } + {{name}} = {{name}}_list; + + {{/isArray}} + {{/isContainer}} + + {{^isContainer}} + + {{#isPrimitiveType}} + jsonToValue(&{{name}}, value, "{{baseType}}"); + {{/isPrimitiveType}} + + {{^isPrimitiveType}} + {{baseType}}* obj = &{{name}}; + obj->fromJson(value.dump()); + {{/isPrimitiveType}} + + {{/isContainer}} + } + + {{/vars}} + +} + +bourne::json +{{classname}}::toJson() +{ + bourne::json object = bourne::json::object(); + + {{#vars}} + + {{#isContainer}} + {{#isArray}} + + {{#items}} + {{#isPrimitiveType}} + + std::list<{{dataType}}> {{name}}_list = {{getter}}(); + bourne::json {{name}}_arr = bourne::json::array(); + + for(auto& var : {{name}}_list) + { + {{name}}_arr.append(var); + } + object["{{name}}"] = {{name}}_arr; + + + {{/isPrimitiveType}} + + {{^isPrimitiveType}} + std::list<{{dataType}}> {{name}}_list = {{getter}}(); + bourne::json {{name}}_arr = bourne::json::array(); + + for(auto& var : {{name}}_list) + { + {{dataType}} obj = var; + {{name}}_arr.append(obj.toJson()); + } + object["{{name}}"] = {{name}}_arr; + + {{/isPrimitiveType}} + {{/items}} + {{/isArray}} + {{/isContainer}} + + + {{^isContainer}} + + {{#isPrimitiveType}} + object["{{name}}"] = {{getter}}(); + {{/isPrimitiveType}} + + {{^isPrimitiveType}} + object["{{name}}"] = {{getter}}().toJson(); + {{/isPrimitiveType}} + + {{/isContainer}} + {{/vars}} + + return object; + +} + +{{#vars}} +{{dataType}}{{#isContainer}}{{#isMap}}{{/isMap}}{{^isMap}}<{{#items}}{{dataType}}{{/items}}>{{/isMap}}{{/isContainer}} +{{classname}}::{{getter}}() +{ + return {{name}}; +} + +void +{{classname}}::{{setter}}({{dataType}} {{#isContainer}}{{#isMap}}{{/isMap}}{{^isMap}}<{{#items}}{{dataType}}{{/items}}>{{/isMap}}{{/isContainer}} {{name}}) +{ + this->{{name}} = {{name}}; +} + +{{/vars}} + + +{{/model}} +{{/models}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/tiny-cpp-client/model-header.mustache b/modules/openapi-generator/src/main/resources/tiny-cpp-client/model-header.mustache new file mode 100644 index 000000000000..a71ba0677c12 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/tiny-cpp-client/model-header.mustache @@ -0,0 +1,81 @@ + +{{#models}}{{#model}}/* + * {{classname}}.h + * + * {{description}} + */ + +#ifndef TINY_CPP_CLIENT_{{classname}}_H_ +#define TINY_CPP_CLIENT_{{classname}}_H_ + +{{/model}}{{/models}} +#include +#include "bourne/json.hpp" +#include "Helpers.h" +{{#imports}} +{{{import}}} +{{/imports}} + +namespace Tiny { +{{#models}}{{#model}} + +/*! \brief {{{description}}} + * + * \ingroup Models + * + */ + +class {{classname}}{ +public: + + /*! \brief Constructor. + */ + {{classname}}(); + {{classname}}(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~{{classname}}(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + {{#vars}} + /*! \brief Get {{{description}}} + */ + {{dataType}}{{#isContainer}}{{#isMap}}{{/isMap}}{{^isMap}}<{{#items}}{{dataType}}{{/items}}>{{/isMap}}{{/isContainer}} {{getter}}(); + + /*! \brief Set {{{description}}} + */ + void {{setter}}({{dataType}} {{#isContainer}}{{#isMap}}{{/isMap}}{{^isMap}}<{{#items}}{{dataType}}{{/items}}>{{/isMap}}{{/isContainer}} {{name}}); + {{/vars}} + + + private: + {{#vars}} + {{^isContainer}} + {{#isPrimitiveType}} + {{dataType}} {{name}}{}; + {{/isPrimitiveType}} + {{^isPrimitiveType}} + {{dataType}} {{name}}; + {{/isPrimitiveType}} + {{/isContainer}} + {{#isContainer}} + {{dataType}}{{#isMap}}{{/isMap}}{{^isMap}}<{{#items}}{{dataType}}{{/items}}>{{/isMap}} {{name}}; + {{/isContainer}} + {{/vars}} +}; +{{/model}} +{{/models}} +} + +#endif /* TINY_CPP_CLIENT_{{classname}}_H_ */ diff --git a/modules/openapi-generator/src/main/resources/tiny-cpp-client/platformio.ini.mustache b/modules/openapi-generator/src/main/resources/tiny-cpp-client/platformio.ini.mustache new file mode 100644 index 000000000000..1e364ee0ab20 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/tiny-cpp-client/platformio.ini.mustache @@ -0,0 +1,19 @@ +{{#isESP32}} +[env:esp32] +platform = espressif32 +board = nodemcu-32s +framework = arduino +lib_deps = https://github.com/steinwurf/bourne.git +extra_scripts = pre_compiling_bourne.py +{{/isESP32}} + +{{#isESP8266}} +[env:esp8266] +platform = espressif8266 +board = d1_mini +framework = arduino +lib_deps = https://github.com/steinwurf/bourne.git +build_flags = -fexceptions +build_unflags = -fno-exceptions +extra_scripts = pre_compiling_bourne.py +{{/isESP8266}} diff --git a/modules/openapi-generator/src/main/resources/tiny-cpp-client/pre_compiling_bourne.py.mustache b/modules/openapi-generator/src/main/resources/tiny-cpp-client/pre_compiling_bourne.py.mustache new file mode 100644 index 000000000000..96356dcdf158 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/tiny-cpp-client/pre_compiling_bourne.py.mustache @@ -0,0 +1,25 @@ +Import("env") + +## Compatibility for bourne to work on microcontrollers +# We insert '#define _GLIBCXX_USE_C99' in files that use std::stoll or std::to_string +def insert_c99_into(file): + import fileinput + + path = env['PROJECT_LIBDEPS_DIR'] + "/" + env['PIOENV'] + "/bourne/src/bourne/" + file + value = '#define _GLIBCXX_USE_C99 1\n' + + for line in fileinput.FileInput(path,inplace=1): + if line.startswith('#define _GLIBCXX_USE_C99'): + continue + elif line.startswith('// D'): + line=line.replace(line,line+value) + print(line, end='') + +def fix_parser(): + insert_c99_into('detail/parser.cpp') + +def fix_json(): + insert_c99_into('json.cpp') + +fix_parser() +fix_json() \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/tiny-cpp-client/root.cert.mustache b/modules/openapi-generator/src/main/resources/tiny-cpp-client/root.cert.mustache new file mode 100644 index 000000000000..bad9c08efad1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/tiny-cpp-client/root.cert.mustache @@ -0,0 +1,53 @@ +// TODO: Provide your service root certificate. +// Below is two examples of root certificates. + +// Let's encrypt root certificate +/** +"-----BEGIN CERTIFICATE-----\n" \ +"MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n" \ +"MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" \ +"d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n" \ +"QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n" \ +"MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n" \ +"b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n" \ +"9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n" \ +"CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n" \ +"nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n" \ +"43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n" \ +"T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n" \ +"gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n" \ +"BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n" \ +"TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n" \ +"DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n" \ +"hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n" \ +"06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n" \ +"PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n" \ +"YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n" \ +"CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n" \ +"-----END CERTIFICATE-----\n" +*/ + +// Amazon_Root_CA_1.pem +/** +"-----BEGIN CERTIFICATE-----\n" \ +"MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF\n" \ +"ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\n" \ +"b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL\n" \ +"MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv\n" \ +"b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj\n" \ +"ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM\n" \ +"9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw\n" \ +"IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6\n" \ +"VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L\n" \ +"93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm\n" \ +"jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\n" \ +"AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA\n" \ +"A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI\n" \ +"U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs\n" \ +"N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv\n" \ +"o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU\n" \ +"5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy\n" \ +"rqXRfboQnoZsG4q5WTP468SQvvG5\n" \ +"-----END CERTIFICATE-----\n" \ +*/ + diff --git a/modules/openapi-generator/src/main/resources/tiny-cpp-client/run-tests.mustache b/modules/openapi-generator/src/main/resources/tiny-cpp-client/run-tests.mustache new file mode 100644 index 000000000000..54bf326c43a3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/tiny-cpp-client/run-tests.mustache @@ -0,0 +1,44 @@ +{{#models}}{{#model}} +#include "{{classname}}Test.cpp" +{{/model}}{{/models}} + + +void setUp(){} + +void tearDown(){} + +void runTests(){ + {{#models}}{{#model}} + {{#vars}} + {{#isPrimitiveType}}{{^isArray}} + RUN_TEST(test_{{classname}}_{{name}}_is_assigned_from_json); + {{/isArray}}{{/isPrimitiveType}} + {{/vars}} + {{/model}}{{/models}} + + {{#models}}{{#model}} + {{#vars}} + {{#isPrimitiveType}}{{^isArray}} + RUN_TEST(test_{{classname}}_{{name}}_is_converted_to_json); + {{/isArray}}{{/isPrimitiveType}} + {{/vars}} + {{/model}}{{/models}} + + +} + +int main(void) { + UNITY_BEGIN(); + runTests(); + return UNITY_END(); +} + +void setup() { + UNITY_BEGIN(); + runTests(); + UNITY_END(); +} + +void loop() { + +} diff --git a/modules/openapi-generator/src/main/resources/tiny-cpp-client/service/AbstractService.cpp.mustache b/modules/openapi-generator/src/main/resources/tiny-cpp-client/service/AbstractService.cpp.mustache new file mode 100644 index 000000000000..0c056c85ae35 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/tiny-cpp-client/service/AbstractService.cpp.mustache @@ -0,0 +1,15 @@ +#include "AbstractService.h" +#include "Arduino.h" + +{{#isESP8266}} +void Tiny::AbstractService::begin(std::string url){ + http.begin(client, String(url.c_str())); +} +{{/isESP8266}} + + +{{#isESP32}} +void Tiny::AbstractService::begin(std::string url){ + http.begin(String(url.c_str()), test_root_ca); //HTTPS connection +} +{{/isESP32}} diff --git a/modules/openapi-generator/src/main/resources/tiny-cpp-client/service/AbstractService.h.mustache b/modules/openapi-generator/src/main/resources/tiny-cpp-client/service/AbstractService.h.mustache new file mode 100644 index 000000000000..7dc46b5b20f0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/tiny-cpp-client/service/AbstractService.h.mustache @@ -0,0 +1,39 @@ +#ifndef TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ +#define TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ +{{#isESP8266}} +#include +#include +{{/isESP8266}} + +{{#isESP32}} +#include "HTTPClient.h" +{{/isESP32}} +#include "Response.h" +namespace Tiny { + +/** +* Class +* Generated with openapi::tiny-cpp-client +*/ +class AbstractService { +public: +HTTPClient http; +{{#isESP8266}} +WiFiClient client; +{{/isESP8266}} +std::string basepath = "https://petstore3.swagger.io/api/v3"; // TODO: change to your url + +void begin(std::string url); + +{{#isESP32}} +// Go and comment out a certificate in root.cert, if you get an error here +// Certificate from file +const char* test_root_ca = +#include "../../root.cert" +; +{{/isESP32}} + +}; // end class +}// namespace Tinyclient + +#endif /* TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ */ diff --git a/modules/openapi-generator/src/main/resources/tiny-cpp-client/service/Response.h.mustache b/modules/openapi-generator/src/main/resources/tiny-cpp-client/service/Response.h.mustache new file mode 100644 index 000000000000..9b7b616b8f1b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/tiny-cpp-client/service/Response.h.mustache @@ -0,0 +1,25 @@ +#ifndef TINY_CPP_CLIENT_RESPONSE_H_ +#define TINY_CPP_CLIENT_RESPONSE_H_ +#include + +namespace Tiny { + +/** +* Class +* Generated with openapi::tiny-cpp-client +*/ +template + class Response { + public: + + Response(T _obj, int _code){ + obj = _obj; + code = _code; + } + + int code; + T obj; + }; + } // namespace Tinyclient + +#endif /* TINY_CPP_CLIENT_RESPONSE_H_ */ diff --git a/modules/openapi-generator/src/main/resources/tiny-cpp-client/service/api-body.mustache b/modules/openapi-generator/src/main/resources/tiny-cpp-client/service/api-body.mustache new file mode 100644 index 000000000000..dc1298688372 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/tiny-cpp-client/service/api-body.mustache @@ -0,0 +1,219 @@ +#include "{{classname}}.h" + +using namespace Tiny; + +{{#operations}} + + {{! Method }} + {{#operation}} + + Response< + {{#returnType}} + {{#returnContainer}} + {{#isArray}} + {{returnType}}<{{returnBaseType}}> + {{/isArray}} + {{#isMap}} + String + {{/isMap}} + {{/returnContainer}} + {{^returnContainer}} + {{returnType}} + {{/returnContainer}} + {{/returnType}} + {{^returnType}} + String + {{/returnType}} + > + {{classname}}:: + {{! Method name }} + {{nickname}}( + {{! Params }} + {{#allParams}} + {{! Arrays }} + {{#isContainer}}{{{dataType}}}<{{baseType}}> {{paramName}}{{/isContainer}}{{#isMap}}// TODO: Implement Maps{{/isMap}} + {{! Normal types/objects }} + {{^isContainer}}{{{dataType}}} {{paramName}}{{/isContainer}} + {{^-last}}, {{/-last}} + {{/allParams}} + ) + {{! Method start}} + { + std::string url = basepath + "{{{path}}}"; //{{#pathParams}}{{{paramName}}} {{/pathParams}} + // Query | {{#queryParams}}{{paramName}} {{/queryParams}} + // Headers | {{#headerParams}}{{paramName}} {{/headerParams}} + // Form | {{#formParams}}{{paramName}} {{/formParams}} + // Body | {{#bodyParam}}{{paramName}}{{/bodyParam}} + + {{#pathParams}} + std::string s_{{paramName}}("{"); + s_{{paramName}}.append("{{{baseName}}}"); + s_{{paramName}}.append("}"); + + int pos = url.find(s_{{paramName}}); + + url.erase(pos, s_{{paramName}}.length()); + url.insert(pos, stringify({{paramName}})); + {{/pathParams}} + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | {{httpMethod}} + {{#bodyParam}} + http.addHeader("Content-Type", "application/json"); + + {{#isContainer}} + {{#isArray}} + {{#items}} + {{#isPrimitiveType}} + bourne::json tmp_arr = bourne::json::array(); + for(auto& var : {{paramName}}) + { + tmp_arr.append(var); + } + payload = tmp_arr.dump(); + {{/isPrimitiveType}} + + {{^isPrimitiveType}} + bourne::json tmp_arr = bourne::json::array(); + for(auto& var : {{paramName}}) + { + auto tmp = var.toJson(); + tmp_arr.append(tmp); + + } + payload = tmp_arr.dump(); + {{/isPrimitiveType}} + {{/items}} + {{/isArray}} + {{/isContainer}} + + {{^isContainer}} + {{#isPrimitiveType}} + payload = stringify({{paramName}}); + {{/isPrimitiveType}} + + {{^isPrimitiveType}} + payload = {{paramName}}.toJson().dump(); + {{/isPrimitiveType}} + {{/isContainer}} + + {{/bodyParam}} + int httpCode = http.sendRequest("{{httpMethod}}", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + {{#returnType}} + + {{#returnContainer}} + {{#isArray}} + + std::list<{{returnBaseType}}> obj = std::list<{{returnBaseType}}>(); + bourne::json jsonPayload(output_string); + + {{#returnBaseType}} + + {{#isBool}} + for(auto& var : jsonPayload.array_range()) + { + {{returnBaseType}} tmp = var.to_bool(); + obj.push_back(tmp); + } + {{/isBool}} + + {{#isInteger}} + for(auto& var : jsonPayload.array_range()) + { + {{returnBaseType}} tmp = var.to_int(); + obj.push_back(tmp); + } + {{/isInteger}} + + {{#isLong}} + for(auto& var : jsonPayload.array_range()) + { + {{returnBaseType}} tmp = (long)(var.to_int()); + obj.push_back(tmp); + } + {{/isLong}} + + {{#isFloat}} + for(auto& var : jsonPayload.array_range()) + { + {{returnBaseType}} tmp = (float)(var.to_float()); + obj.push_back(tmp); + } + {{/isFloat}} + + {{#isString}} + for(auto& var : jsonPayload.array_range()) + { + {{returnBaseType}} tmp = var.to_string(); + obj.push_back(tmp); + } + {{/isString}} + + + {{^isBool}}{{^isInteger}}{{^isLong}}{{^isString}}{{^isFloat}} + for(auto& var : jsonPayload.array_range()) + { + {{returnBaseType}} tmp(var.dump()); + obj.push_back(tmp); + } + {{/isFloat}}{{/isString}}{{/isLong}}{{/isInteger}}{{/isBool}} + + {{/returnBaseType}} + + {{/isArray}} + + {{#isMap}} + //TODO: Implement map logic here + {{/isMap}} + + {{/returnContainer}} + + {{^returnContainer}} + {{#returnTypeIsPrimitive}} + bourne::json jsonPayload(output_string); + {{returnType}} obj; + jsonToValue(&obj, jsonPayload, "{{returnType}}"); + {{/returnTypeIsPrimitive}} + + {{^returnTypeIsPrimitive}} + {{returnType}} obj(output_string); + {{/returnTypeIsPrimitive}} + {{/returnContainer}} + + {{/returnType}} + + {{#returnType}} + {{#returnContainer}} + {{#isArray}} + Response<{{returnType}}<{{returnBaseType}}>> response(obj, httpCode); + {{/isArray}} + {{#isMap}} + //TODO: No support for maps. + Response response(output, httpCode); + {{/isMap}} + {{/returnContainer}} + {{^returnContainer}} + Response<{{returnType}}> response(obj, httpCode); + {{/returnContainer}} + {{/returnType}} + {{^returnType}} + Response response(output, httpCode); + {{/returnType}} + return response; + } + {{/operation}} + + + +{{/operations}} + diff --git a/modules/openapi-generator/src/main/resources/tiny-cpp-client/service/api-header.mustache b/modules/openapi-generator/src/main/resources/tiny-cpp-client/service/api-header.mustache new file mode 100644 index 000000000000..416369dcf31a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/tiny-cpp-client/service/api-header.mustache @@ -0,0 +1,74 @@ +#ifndef TINY_CPP_CLIENT_{{classname}}_H_ +#define TINY_CPP_CLIENT_{{classname}}_H_ + +{{{defaultInclude}}} +#include "Response.h" +#include "Arduino.h" +#include "AbstractService.h" +#include "Helpers.h" +#include + +{{#imports}} +{{{import}}} +{{/imports}} + +namespace Tiny { + +{{#operations}} +/** + * Class {{basename}} + * Generated with openapi::tiny-cpp-client + */ + +class {{classname}} : public AbstractService { +public: + {{! Constructor }} + {{classname}}() = default; + + {{! Destructor }} + virtual ~{{classname}}() = default; + + {{! Service endpoint }} + {{#operation}} + /** + * {{{summary}}}. + * + * {{{notes}}}{{#allParams}} + * \param {{paramName}} {{{description}}}{{#required}} *Required*{{/required}}{{/allParams}} + */ + Response< + {{#returnType}} + {{#returnContainer}} + {{#isArray}} + {{returnType}}<{{returnBaseType}}> + {{/isArray}} + {{#isMap}} + String + {{/isMap}} + {{/returnContainer}} + {{^returnContainer}} + {{returnType}} + {{/returnContainer}} + {{/returnType}} + {{^returnType}} + String + {{/returnType}} + > + {{! Method name }} + {{nickname}}( + {{! Params }} + {{#allParams}} + {{! Arrays }} + {{#isContainer}}{{{dataType}}}<{{baseType}}> {{paramName}}{{/isContainer}} + {{! Normal types/objects }} + {{^isContainer}}{{{dataType}}} {{paramName}}{{/isContainer}} + {{^-last}}, {{/-last}} + {{/allParams}} + ); + {{/operation}} +}; {{! Service endpoint end }} +{{/operations}} + +} {{! namespace end }} + +#endif /* TINY_CPP_CLIENT_{{classname}}_H_ */ \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/tiny-cpp-client/unit-test-model.mustache b/modules/openapi-generator/src/main/resources/tiny-cpp-client/unit-test-model.mustache new file mode 100644 index 000000000000..14894973b81f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/tiny-cpp-client/unit-test-model.mustache @@ -0,0 +1,161 @@ +{{#models}}{{#model}} +#include "{{classname}}.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + +{{#vars}} +{{#isPrimitiveType}}{{^isArray}} +void test_{{classname}}_{{name}}_is_assigned_from_json() +{ + {{#isInteger}} + bourne::json input = + { + "{{name}}", 1 + }; + + {{classname}} obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.{{getter}}()); + {{/isInteger}} + + + {{#isString}} + bourne::json input = + { + "{{name}}", "hello" + }; + + {{classname}} obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.{{getter}}().c_str()); + {{/isString}} + + + {{#isBoolean}} + bourne::json input = + { + "{{name}}", true + }; + + {{classname}} obj(input.dump()); + + TEST_ASSERT(true == obj.{{getter}}()); + {{/isBoolean}} + + + {{#isLong}} + bourne::json input = + { + "{{name}}", 1 + }; + + {{classname}} obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.{{getter}}()); + {{/isLong}} + + + {{#isFloat}} + bourne::json input = + { + "{{name}}", 1.0 + }; + + {{classname}} obj(input.dump()); + + TEST_ASSERT_EQUAL_FLOAT(1.0, obj.{{getter}}()); + {{/isFloat}} +} +{{/isArray}}{{/isPrimitiveType}} +{{/vars}} + +{{#vars}} +{{#isPrimitiveType}}{{^isArray}} +void test_{{classname}}_{{name}}_is_converted_to_json() +{ + {{#isInteger}} + bourne::json input = + { + "{{name}}", 1 + }; + + {{classname}} obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["{{name}}"] == output["{{name}}"]); + {{/isInteger}} + + {{#isString}} + bourne::json input = + { + "{{name}}", "hello" + }; + + {{classname}} obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["{{name}}"] == output["{{name}}"]); + {{/isString}} + + {{#isBoolean}} + bourne::json input = + { + "{{name}}", true + }; + + {{classname}} obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["{{name}}"] == output["{{name}}"]); + {{/isBoolean}} + + {{#isLong}} + bourne::json input = + { + "{{name}}", 1 + }; + + {{classname}} obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["{{name}}"] == output["{{name}}"]); + {{/isLong}} + + {{#isFloat}} + bourne::json input = + { + "{{name}}", 1.0 + }; + + {{classname}} obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["{{name}}"] == output["{{name}}"]); + {{/isFloat}} +} +{{/isArray}}{{/isPrimitiveType}} +{{/vars}} + +{{/model}} +{{/models}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/tiny-cpp-client/unittest.mustache b/modules/openapi-generator/src/main/resources/tiny-cpp-client/unittest.mustache new file mode 100644 index 000000000000..c6a1f23a6e39 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/tiny-cpp-client/unittest.mustache @@ -0,0 +1,132 @@ +#include "Pet.h" +#include +#include +#include +#include "bourne/json.hpp" + +void setUp(){ +} + + +void tearDown(){ +} + +void test_id_is_assigned(){ + bourne::json petJSON = + { + "id", 1 + }; + + Tiny::Pet pet(petJSON.dump()); + + + TEST_ASSERT_EQUAL_INT(1, pet.getId()); +} + +void test_name_is_assigned(){ + bourne::json petJSON = + { + "name", "Shiba" + }; + + Tiny::Pet pet(petJSON.dump()); + + TEST_ASSERT_EQUAL_STRING("Shiba", pet.getName().c_str()); + +} + +void test_status_is_assigned(){ + bourne::json petJSON = + { + "status", "Sold" + }; + + Tiny::Pet pet(petJSON.dump()); + + TEST_ASSERT_EQUAL_STRING("Sold", pet.getStatus().c_str()); +} + +void test_category_object_is_assigned(){ + + bourne::json catJSON = + { + "id", 3, + "name", "Small dog" + }; + + bourne::json petJSON = + { + "category", catJSON, + }; + + Tiny::Pet pet(petJSON.dump()); + + TEST_ASSERT_EQUAL_STRING("Small dog", pet.getCategory().getName().c_str()); + TEST_ASSERT_EQUAL_INT(3, pet.getCategory().getId()); + +} + + +void test_photo_string_list_is_assigned(){ + + std::list photoList = {"url1", "url2", "url3", "url4"}; + + bourne::json photoARR = bourne::json::array("url1", "url2", "url3", "url4"); + + bourne::json petJSON = + { + "photoUrls", photoARR, + }; + + Tiny::Pet pet(petJSON.dump()); + + TEST_ASSERT(photoList == pet.getPhotoUrls()); +} + +void test_tags_object_list_is_assigned(){ + bourne::json aTag = + { + "id", 2, + "name", "Hello" + }; + + bourne::json tagsARR = bourne::json::array(aTag); + bourne::json petJSON = + { + "tags", tagsARR, + }; + + Tiny::Pet pet(petJSON.dump()); + + TEST_ASSERT_EQUAL_INT(2, pet.getTags().front().getId()); + TEST_ASSERT_EQUAL_STRING("Hello", pet.getTags().front().getName().c_str()); +} + + + +void runTests(){ + RUN_TEST(test_id_is_assigned); + RUN_TEST(test_category_object_is_assigned); + RUN_TEST(test_name_is_assigned); + RUN_TEST(test_status_is_assigned); + RUN_TEST(test_photo_string_list_is_assigned); + RUN_TEST(test_tags_object_list_is_assigned); +} + +int main(void) { + UNITY_BEGIN(); + runTests(); + return UNITY_END(); +} + +void setup() { + UNITY_BEGIN(); + runTests(); + UNITY_END(); +} + +void loop() { + +} + + diff --git a/samples/client/petstore/tiny/cpp/.gitignore b/samples/client/petstore/tiny/cpp/.gitignore new file mode 100644 index 000000000000..89cc49cbd652 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/samples/client/petstore/tiny/cpp/.openapi-generator-ignore b/samples/client/petstore/tiny/cpp/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/.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/tiny/cpp/.openapi-generator/FILES b/samples/client/petstore/tiny/cpp/.openapi-generator/FILES new file mode 100644 index 000000000000..1024d9450644 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/.openapi-generator/FILES @@ -0,0 +1,30 @@ +README.md +README.md +lib/Models/ApiResponse.cpp +lib/Models/ApiResponse.h +lib/Models/Category.cpp +lib/Models/Category.h +lib/Models/Helpers.cpp +lib/Models/Helpers.h +lib/Models/Order.cpp +lib/Models/Order.h +lib/Models/Pet.cpp +lib/Models/Pet.h +lib/Models/Tag.cpp +lib/Models/Tag.h +lib/Models/User.cpp +lib/Models/User.h +lib/service/AbstractService.cpp +lib/service/AbstractService.h +lib/service/PetApi.cpp +lib/service/PetApi.h +lib/service/Response.h +lib/service/StoreApi.cpp +lib/service/StoreApi.h +lib/service/UserApi.cpp +lib/service/UserApi.h +platformio.ini +pre_compiling_bourne.py +root.cert +src/main.cpp +test/RunTests.cpp diff --git a/samples/client/petstore/tiny/cpp/.openapi-generator/VERSION b/samples/client/petstore/tiny/cpp/.openapi-generator/VERSION new file mode 100644 index 000000000000..6555596f9311 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/tiny/cpp/README.md b/samples/client/petstore/tiny/cpp/README.md new file mode 100644 index 000000000000..e8bf721275b5 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/README.md @@ -0,0 +1,73 @@ +# Documentation for OpenAPI Petstore +This is a client generator for microcontrollers on the Espressif32 platform and the Arduino framework +After the client have been generated, you have to change these following variablies: +- root.cert | Provide your service root certificate. +- src/main.cpp | Change wifi name +- src/main.cpp | Change wifi password +- lib/service/AbstractService.h | Change to your url + +# Documentation for OpenAPI Petstore 1.0.0 Tiny client cpp (Arduino) + +The project is structured like this: +``` +samples/client/petstore/tiny/cpp/ +β”œβ”€β”€ lib +β”‚ β”œβ”€β”€ Models +β”‚ β”œβ”€β”€ service +β”‚ └── TestFiles +β”œβ”€β”€ platformio.ini +β”œβ”€β”€ pre_compiling_bourne.py +β”œβ”€β”€ README.md +β”œβ”€β”€ root.cert +β”œβ”€β”€ src +β”‚ └── main.cpp +└── test + └── RunTests.cpp +``` + +All URIs are relative to http://petstore.swagger.iohttp://petstore.swagger.io/v2 + +### PetApi +|Method | HTTP request | Description| +|------------- | ------------- | -------------| +|*addPet* | *POST* /pet | Add a new pet to the store.| +|*deletePet* | *DELETE* /pet/{petId} | Deletes a pet.| +|*findPetsByStatus* | *GET* /pet/findByStatus | Finds Pets by status.| +|*findPetsByTags* | *GET* /pet/findByTags | Finds Pets by tags.| +|*getPetById* | *GET* /pet/{petId} | Find pet by ID.| +|*updatePet* | *PUT* /pet | Update an existing pet.| +|*updatePetWithForm* | *POST* /pet/{petId} | Updates a pet in the store with form data.| +|*uploadFile* | *POST* /pet/{petId}/uploadImage | uploads an image.| + +### StoreApi +|Method | HTTP request | Description| +|------------- | ------------- | -------------| +|*deleteOrder* | *DELETE* /store/order/{orderId} | Delete purchase order by ID.| +|*getInventory* | *GET* /store/inventory | Returns pet inventories by status.| +|*getOrderById* | *GET* /store/order/{orderId} | Find purchase order by ID.| +|*placeOrder* | *POST* /store/order | Place an order for a pet.| + +### UserApi +|Method | HTTP request | Description| +|------------- | ------------- | -------------| +|*createUser* | *POST* /user | Create user.| +|*createUsersWithArrayInput* | *POST* /user/createWithArray | Creates list of users with given input array.| +|*createUsersWithListInput* | *POST* /user/createWithList | Creates list of users with given input array.| +|*deleteUser* | *DELETE* /user/{username} | Delete user.| +|*getUserByName* | *GET* /user/{username} | Get user by user name.| +|*loginUser* | *GET* /user/login | Logs user into the system.| +|*logoutUser* | *GET* /user/logout | Logs out current logged in user session.| +|*updateUser* | *PUT* /user/{username} | Updated user.| + + +## What are the Model files for the data structures/objects? +|Class | Description| +|------------- | -------------| +|*ApiResponse* | Describes the result of uploading an image resource| +|*Category* | A category for a pet| +|*Order* | An order for a pets from the pet store| +|*Pet* | A pet for sale in the pet store| +|*Tag* | A tag for a pet| +|*User* | A User who is purchasing from the pet store| + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/ApiResponse.cpp b/samples/client/petstore/tiny/cpp/lib/Models/ApiResponse.cpp new file mode 100644 index 000000000000..e9be9e2b6187 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/ApiResponse.cpp @@ -0,0 +1,139 @@ + + +#include "ApiResponse.h" + +using namespace Tiny; + +ApiResponse::ApiResponse() +{ + code = int(0); + type = std::string(); + message = std::string(); +} + +ApiResponse::ApiResponse(std::string jsonString) +{ + this->fromJson(jsonString); +} + +ApiResponse::~ApiResponse() +{ + +} + +void +ApiResponse::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *codeKey = "code"; + + if(object.has_key(codeKey)) + { + bourne::json value = object[codeKey]; + + + + jsonToValue(&code, value, "int"); + + + } + + const char *typeKey = "type"; + + if(object.has_key(typeKey)) + { + bourne::json value = object[typeKey]; + + + + jsonToValue(&type, value, "std::string"); + + + } + + const char *messageKey = "message"; + + if(object.has_key(messageKey)) + { + bourne::json value = object[messageKey]; + + + + jsonToValue(&message, value, "std::string"); + + + } + + +} + +bourne::json +ApiResponse::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["code"] = getCode(); + + + + + + + object["type"] = getType(); + + + + + + + object["message"] = getMessage(); + + + + return object; + +} + +int +ApiResponse::getCode() +{ + return code; +} + +void +ApiResponse::setCode(int code) +{ + this->code = code; +} + +std::string +ApiResponse::getType() +{ + return type; +} + +void +ApiResponse::setType(std::string type) +{ + this->type = type; +} + +std::string +ApiResponse::getMessage() +{ + return message; +} + +void +ApiResponse::setMessage(std::string message) +{ + this->message = message; +} + + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/ApiResponse.h b/samples/client/petstore/tiny/cpp/lib/Models/ApiResponse.h new file mode 100644 index 000000000000..dbaf8abcaf38 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/ApiResponse.h @@ -0,0 +1,78 @@ + +/* + * ApiResponse.h + * + * Describes the result of uploading an image resource + */ + +#ifndef TINY_CPP_CLIENT_ApiResponse_H_ +#define TINY_CPP_CLIENT_ApiResponse_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief Describes the result of uploading an image resource + * + * \ingroup Models + * + */ + +class ApiResponse{ +public: + + /*! \brief Constructor. + */ + ApiResponse(); + ApiResponse(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~ApiResponse(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + int getCode(); + + /*! \brief Set + */ + void setCode(int code); + /*! \brief Get + */ + std::string getType(); + + /*! \brief Set + */ + void setType(std::string type); + /*! \brief Get + */ + std::string getMessage(); + + /*! \brief Set + */ + void setMessage(std::string message); + + + private: + int code{}; + std::string type{}; + std::string message{}; +}; +} + +#endif /* TINY_CPP_CLIENT_ApiResponse_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Category.cpp b/samples/client/petstore/tiny/cpp/lib/Models/Category.cpp new file mode 100644 index 000000000000..950b06ffd44a --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Category.cpp @@ -0,0 +1,106 @@ + + +#include "Category.h" + +using namespace Tiny; + +Category::Category() +{ + id = long(0); + name = std::string(); +} + +Category::Category(std::string jsonString) +{ + this->fromJson(jsonString); +} + +Category::~Category() +{ + +} + +void +Category::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *nameKey = "name"; + + if(object.has_key(nameKey)) + { + bourne::json value = object[nameKey]; + + + + jsonToValue(&name, value, "std::string"); + + + } + + +} + +bourne::json +Category::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + object["name"] = getName(); + + + + return object; + +} + +long +Category::getId() +{ + return id; +} + +void +Category::setId(long id) +{ + this->id = id; +} + +std::string +Category::getName() +{ + return name; +} + +void +Category::setName(std::string name) +{ + this->name = name; +} + + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Category.h b/samples/client/petstore/tiny/cpp/lib/Models/Category.h new file mode 100644 index 000000000000..9c90e3dd4160 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Category.h @@ -0,0 +1,70 @@ + +/* + * Category.h + * + * A category for a pet + */ + +#ifndef TINY_CPP_CLIENT_Category_H_ +#define TINY_CPP_CLIENT_Category_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief A category for a pet + * + * \ingroup Models + * + */ + +class Category{ +public: + + /*! \brief Constructor. + */ + Category(); + Category(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~Category(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + std::string getName(); + + /*! \brief Set + */ + void setName(std::string name); + + + private: + long id{}; + std::string name{}; +}; +} + +#endif /* TINY_CPP_CLIENT_Category_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Helpers.cpp b/samples/client/petstore/tiny/cpp/lib/Models/Helpers.cpp new file mode 100644 index 000000000000..c3935b37cde9 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Helpers.cpp @@ -0,0 +1,102 @@ +#include "Helpers.h" +#include +#include + +bool isprimitive(std::string type){ + if(type == "std::string" || + type == "int" || + type == "float" || + type == "long" || + type == "double" || + type == "bool" || + type == "std::map" || + type == "std::list") + { + return true; + } + return false; +} + + +void +jsonToValue(void* target, bourne::json value, std::string type) +{ + if (target == NULL || value.is_null()) { + return; + } + + else if (type.compare("bool") == 0) + { + bool* val = static_cast (target); + *val = value.to_bool(); + } + + else if (type.compare("int") == 0) + { + int* val = static_cast (target); + *val = value.to_int(); + } + + else if (type.compare("float") == 0) + { + float* val = static_cast (target); + *val = (float)(value.to_float()); + } + + else if (type.compare("long") == 0) + { + long* val = static_cast (target); + *val = (long)(value.to_int()); + } + + else if (type.compare("double") == 0) + { + double* val = static_cast (target); + *val = value.to_float(); + } + + else if (type.compare("std::string") == 0) + { + std::string* val = static_cast (target); + *val = value.to_string(); + } + else { + return; + } +} + +std::string +stringify(long input){ + std::stringstream stream; + stream << input; + return stream.str(); + +}; + +std::string +stringify(int input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(double input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(float input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(std::string input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Helpers.h b/samples/client/petstore/tiny/cpp/lib/Models/Helpers.h new file mode 100644 index 000000000000..5ef7d9afdf77 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Helpers.h @@ -0,0 +1,22 @@ +#ifndef TINY_CPP_CLIENT_HELPERS_H_ +#define TINY_CPP_CLIENT_HELPERS_H_ + +#include +#include "bourne/json.hpp" + +bool isprimitive(std::string type); + +void jsonToValue(void* target, bourne::json value, std::string type); + +std::string stringify(long input); + +std::string stringify(int input); + +std::string stringify(double input); + +std::string stringify(float input); + +std::string stringify(std::string input); + +#endif /* TINY_CPP_CLIENT_HELPERS_H_ */ + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Order.cpp b/samples/client/petstore/tiny/cpp/lib/Models/Order.cpp new file mode 100644 index 000000000000..b8b7e00d3fc8 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Order.cpp @@ -0,0 +1,238 @@ + + +#include "Order.h" + +using namespace Tiny; + +Order::Order() +{ + id = long(0); + petId = long(0); + quantity = int(0); + shipDate = std::string(); + status = std::string(); + complete = bool(false); +} + +Order::Order(std::string jsonString) +{ + this->fromJson(jsonString); +} + +Order::~Order() +{ + +} + +void +Order::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *petIdKey = "petId"; + + if(object.has_key(petIdKey)) + { + bourne::json value = object[petIdKey]; + + + + jsonToValue(&petId, value, "long"); + + + } + + const char *quantityKey = "quantity"; + + if(object.has_key(quantityKey)) + { + bourne::json value = object[quantityKey]; + + + + jsonToValue(&quantity, value, "int"); + + + } + + const char *shipDateKey = "shipDate"; + + if(object.has_key(shipDateKey)) + { + bourne::json value = object[shipDateKey]; + + + + jsonToValue(&shipDate, value, "std::string"); + + + } + + const char *statusKey = "status"; + + if(object.has_key(statusKey)) + { + bourne::json value = object[statusKey]; + + + + jsonToValue(&status, value, "std::string"); + + + } + + const char *completeKey = "complete"; + + if(object.has_key(completeKey)) + { + bourne::json value = object[completeKey]; + + + + jsonToValue(&complete, value, "bool"); + + + } + + +} + +bourne::json +Order::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + object["petId"] = getPetId(); + + + + + + + object["quantity"] = getQuantity(); + + + + + + + object["shipDate"] = getShipDate(); + + + + + + + object["status"] = getStatus(); + + + + + + + object["complete"] = isComplete(); + + + + return object; + +} + +long +Order::getId() +{ + return id; +} + +void +Order::setId(long id) +{ + this->id = id; +} + +long +Order::getPetId() +{ + return petId; +} + +void +Order::setPetId(long petId) +{ + this->petId = petId; +} + +int +Order::getQuantity() +{ + return quantity; +} + +void +Order::setQuantity(int quantity) +{ + this->quantity = quantity; +} + +std::string +Order::getShipDate() +{ + return shipDate; +} + +void +Order::setShipDate(std::string shipDate) +{ + this->shipDate = shipDate; +} + +std::string +Order::getStatus() +{ + return status; +} + +void +Order::setStatus(std::string status) +{ + this->status = status; +} + +bool +Order::isComplete() +{ + return complete; +} + +void +Order::setComplete(bool complete) +{ + this->complete = complete; +} + + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Order.h b/samples/client/petstore/tiny/cpp/lib/Models/Order.h new file mode 100644 index 000000000000..6f36404f959a --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Order.h @@ -0,0 +1,102 @@ + +/* + * Order.h + * + * An order for a pets from the pet store + */ + +#ifndef TINY_CPP_CLIENT_Order_H_ +#define TINY_CPP_CLIENT_Order_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief An order for a pets from the pet store + * + * \ingroup Models + * + */ + +class Order{ +public: + + /*! \brief Constructor. + */ + Order(); + Order(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~Order(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + long getPetId(); + + /*! \brief Set + */ + void setPetId(long petId); + /*! \brief Get + */ + int getQuantity(); + + /*! \brief Set + */ + void setQuantity(int quantity); + /*! \brief Get + */ + std::string getShipDate(); + + /*! \brief Set + */ + void setShipDate(std::string shipDate); + /*! \brief Get Order Status + */ + std::string getStatus(); + + /*! \brief Set Order Status + */ + void setStatus(std::string status); + /*! \brief Get + */ + bool isComplete(); + + /*! \brief Set + */ + void setComplete(bool complete); + + + private: + long id{}; + long petId{}; + int quantity{}; + std::string shipDate{}; + std::string status{}; + bool complete{}; +}; +} + +#endif /* TINY_CPP_CLIENT_Order_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Pet.cpp b/samples/client/petstore/tiny/cpp/lib/Models/Pet.cpp new file mode 100644 index 000000000000..57f7781aef2a --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Pet.cpp @@ -0,0 +1,274 @@ + + +#include "Pet.h" + +using namespace Tiny; + +Pet::Pet() +{ + id = long(0); + category = Category(); + name = std::string(); + photoUrls = std::list(); + tags = std::list(); + status = std::string(); +} + +Pet::Pet(std::string jsonString) +{ + this->fromJson(jsonString); +} + +Pet::~Pet() +{ + +} + +void +Pet::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *categoryKey = "category"; + + if(object.has_key(categoryKey)) + { + bourne::json value = object[categoryKey]; + + + + + Category* obj = &category; + obj->fromJson(value.dump()); + + } + + const char *nameKey = "name"; + + if(object.has_key(nameKey)) + { + bourne::json value = object[nameKey]; + + + + jsonToValue(&name, value, "std::string"); + + + } + + const char *photoUrlsKey = "photoUrls"; + + if(object.has_key(photoUrlsKey)) + { + bourne::json value = object[photoUrlsKey]; + + + std::list photoUrls_list; + std::string element; + for(auto& var : value.array_range()) + { + + jsonToValue(&element, var, "std::string"); + + + photoUrls_list.push_back(element); + } + photoUrls = photoUrls_list; + + + } + + const char *tagsKey = "tags"; + + if(object.has_key(tagsKey)) + { + bourne::json value = object[tagsKey]; + + + std::list tags_list; + Tag element; + for(auto& var : value.array_range()) + { + + + element.fromJson(var.dump()); + + tags_list.push_back(element); + } + tags = tags_list; + + + } + + const char *statusKey = "status"; + + if(object.has_key(statusKey)) + { + bourne::json value = object[statusKey]; + + + + jsonToValue(&status, value, "std::string"); + + + } + + +} + +bourne::json +Pet::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + + object["category"] = getCategory().toJson(); + + + + + + object["name"] = getName(); + + + + + + std::list photoUrls_list = getPhotoUrls(); + bourne::json photoUrls_arr = bourne::json::array(); + + for(auto& var : photoUrls_list) + { + photoUrls_arr.append(var); + } + object["photoUrls"] = photoUrls_arr; + + + + + + + + + std::list tags_list = getTags(); + bourne::json tags_arr = bourne::json::array(); + + for(auto& var : tags_list) + { + Tag obj = var; + tags_arr.append(obj.toJson()); + } + object["tags"] = tags_arr; + + + + + + + + object["status"] = getStatus(); + + + + return object; + +} + +long +Pet::getId() +{ + return id; +} + +void +Pet::setId(long id) +{ + this->id = id; +} + +Category +Pet::getCategory() +{ + return category; +} + +void +Pet::setCategory(Category category) +{ + this->category = category; +} + +std::string +Pet::getName() +{ + return name; +} + +void +Pet::setName(std::string name) +{ + this->name = name; +} + +std::list +Pet::getPhotoUrls() +{ + return photoUrls; +} + +void +Pet::setPhotoUrls(std::list photoUrls) +{ + this->photoUrls = photoUrls; +} + +std::list +Pet::getTags() +{ + return tags; +} + +void +Pet::setTags(std::list tags) +{ + this->tags = tags; +} + +std::string +Pet::getStatus() +{ + return status; +} + +void +Pet::setStatus(std::string status) +{ + this->status = status; +} + + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Pet.h b/samples/client/petstore/tiny/cpp/lib/Models/Pet.h new file mode 100644 index 000000000000..3329735f8a16 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Pet.h @@ -0,0 +1,105 @@ + +/* + * Pet.h + * + * A pet for sale in the pet store + */ + +#ifndef TINY_CPP_CLIENT_Pet_H_ +#define TINY_CPP_CLIENT_Pet_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" +#include "Category.h" +#include "Tag.h" +#include + +namespace Tiny { + + +/*! \brief A pet for sale in the pet store + * + * \ingroup Models + * + */ + +class Pet{ +public: + + /*! \brief Constructor. + */ + Pet(); + Pet(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~Pet(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + Category getCategory(); + + /*! \brief Set + */ + void setCategory(Category category); + /*! \brief Get + */ + std::string getName(); + + /*! \brief Set + */ + void setName(std::string name); + /*! \brief Get + */ + std::list getPhotoUrls(); + + /*! \brief Set + */ + void setPhotoUrls(std::list photoUrls); + /*! \brief Get + */ + std::list getTags(); + + /*! \brief Set + */ + void setTags(std::list tags); + /*! \brief Get pet status in the store + */ + std::string getStatus(); + + /*! \brief Set pet status in the store + */ + void setStatus(std::string status); + + + private: + long id{}; + Category category; + std::string name{}; + std::list photoUrls; + std::list tags; + std::string status{}; +}; +} + +#endif /* TINY_CPP_CLIENT_Pet_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Tag.cpp b/samples/client/petstore/tiny/cpp/lib/Models/Tag.cpp new file mode 100644 index 000000000000..e46d94258a1d --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Tag.cpp @@ -0,0 +1,106 @@ + + +#include "Tag.h" + +using namespace Tiny; + +Tag::Tag() +{ + id = long(0); + name = std::string(); +} + +Tag::Tag(std::string jsonString) +{ + this->fromJson(jsonString); +} + +Tag::~Tag() +{ + +} + +void +Tag::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *nameKey = "name"; + + if(object.has_key(nameKey)) + { + bourne::json value = object[nameKey]; + + + + jsonToValue(&name, value, "std::string"); + + + } + + +} + +bourne::json +Tag::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + object["name"] = getName(); + + + + return object; + +} + +long +Tag::getId() +{ + return id; +} + +void +Tag::setId(long id) +{ + this->id = id; +} + +std::string +Tag::getName() +{ + return name; +} + +void +Tag::setName(std::string name) +{ + this->name = name; +} + + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Tag.h b/samples/client/petstore/tiny/cpp/lib/Models/Tag.h new file mode 100644 index 000000000000..e05bcdc92900 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Tag.h @@ -0,0 +1,70 @@ + +/* + * Tag.h + * + * A tag for a pet + */ + +#ifndef TINY_CPP_CLIENT_Tag_H_ +#define TINY_CPP_CLIENT_Tag_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief A tag for a pet + * + * \ingroup Models + * + */ + +class Tag{ +public: + + /*! \brief Constructor. + */ + Tag(); + Tag(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~Tag(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + std::string getName(); + + /*! \brief Set + */ + void setName(std::string name); + + + private: + long id{}; + std::string name{}; +}; +} + +#endif /* TINY_CPP_CLIENT_Tag_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/Models/User.cpp b/samples/client/petstore/tiny/cpp/lib/Models/User.cpp new file mode 100644 index 000000000000..ac84c40205a9 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/User.cpp @@ -0,0 +1,304 @@ + + +#include "User.h" + +using namespace Tiny; + +User::User() +{ + id = long(0); + username = std::string(); + firstName = std::string(); + lastName = std::string(); + email = std::string(); + password = std::string(); + phone = std::string(); + userStatus = int(0); +} + +User::User(std::string jsonString) +{ + this->fromJson(jsonString); +} + +User::~User() +{ + +} + +void +User::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *usernameKey = "username"; + + if(object.has_key(usernameKey)) + { + bourne::json value = object[usernameKey]; + + + + jsonToValue(&username, value, "std::string"); + + + } + + const char *firstNameKey = "firstName"; + + if(object.has_key(firstNameKey)) + { + bourne::json value = object[firstNameKey]; + + + + jsonToValue(&firstName, value, "std::string"); + + + } + + const char *lastNameKey = "lastName"; + + if(object.has_key(lastNameKey)) + { + bourne::json value = object[lastNameKey]; + + + + jsonToValue(&lastName, value, "std::string"); + + + } + + const char *emailKey = "email"; + + if(object.has_key(emailKey)) + { + bourne::json value = object[emailKey]; + + + + jsonToValue(&email, value, "std::string"); + + + } + + const char *passwordKey = "password"; + + if(object.has_key(passwordKey)) + { + bourne::json value = object[passwordKey]; + + + + jsonToValue(&password, value, "std::string"); + + + } + + const char *phoneKey = "phone"; + + if(object.has_key(phoneKey)) + { + bourne::json value = object[phoneKey]; + + + + jsonToValue(&phone, value, "std::string"); + + + } + + const char *userStatusKey = "userStatus"; + + if(object.has_key(userStatusKey)) + { + bourne::json value = object[userStatusKey]; + + + + jsonToValue(&userStatus, value, "int"); + + + } + + +} + +bourne::json +User::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + object["username"] = getUsername(); + + + + + + + object["firstName"] = getFirstName(); + + + + + + + object["lastName"] = getLastName(); + + + + + + + object["email"] = getEmail(); + + + + + + + object["password"] = getPassword(); + + + + + + + object["phone"] = getPhone(); + + + + + + + object["userStatus"] = getUserStatus(); + + + + return object; + +} + +long +User::getId() +{ + return id; +} + +void +User::setId(long id) +{ + this->id = id; +} + +std::string +User::getUsername() +{ + return username; +} + +void +User::setUsername(std::string username) +{ + this->username = username; +} + +std::string +User::getFirstName() +{ + return firstName; +} + +void +User::setFirstName(std::string firstName) +{ + this->firstName = firstName; +} + +std::string +User::getLastName() +{ + return lastName; +} + +void +User::setLastName(std::string lastName) +{ + this->lastName = lastName; +} + +std::string +User::getEmail() +{ + return email; +} + +void +User::setEmail(std::string email) +{ + this->email = email; +} + +std::string +User::getPassword() +{ + return password; +} + +void +User::setPassword(std::string password) +{ + this->password = password; +} + +std::string +User::getPhone() +{ + return phone; +} + +void +User::setPhone(std::string phone) +{ + this->phone = phone; +} + +int +User::getUserStatus() +{ + return userStatus; +} + +void +User::setUserStatus(int userStatus) +{ + this->userStatus = userStatus; +} + + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/User.h b/samples/client/petstore/tiny/cpp/lib/Models/User.h new file mode 100644 index 000000000000..84de5204ced8 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/User.h @@ -0,0 +1,118 @@ + +/* + * User.h + * + * A User who is purchasing from the pet store + */ + +#ifndef TINY_CPP_CLIENT_User_H_ +#define TINY_CPP_CLIENT_User_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief A User who is purchasing from the pet store + * + * \ingroup Models + * + */ + +class User{ +public: + + /*! \brief Constructor. + */ + User(); + User(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~User(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + std::string getUsername(); + + /*! \brief Set + */ + void setUsername(std::string username); + /*! \brief Get + */ + std::string getFirstName(); + + /*! \brief Set + */ + void setFirstName(std::string firstName); + /*! \brief Get + */ + std::string getLastName(); + + /*! \brief Set + */ + void setLastName(std::string lastName); + /*! \brief Get + */ + std::string getEmail(); + + /*! \brief Set + */ + void setEmail(std::string email); + /*! \brief Get + */ + std::string getPassword(); + + /*! \brief Set + */ + void setPassword(std::string password); + /*! \brief Get + */ + std::string getPhone(); + + /*! \brief Set + */ + void setPhone(std::string phone); + /*! \brief Get User Status + */ + int getUserStatus(); + + /*! \brief Set User Status + */ + void setUserStatus(int userStatus); + + + private: + long id{}; + std::string username{}; + std::string firstName{}; + std::string lastName{}; + std::string email{}; + std::string password{}; + std::string phone{}; + int userStatus{}; +}; +} + +#endif /* TINY_CPP_CLIENT_User_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/TestFiles/ApiResponseTest.cpp b/samples/client/petstore/tiny/cpp/lib/TestFiles/ApiResponseTest.cpp new file mode 100644 index 000000000000..160f4217f5df --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/TestFiles/ApiResponseTest.cpp @@ -0,0 +1,139 @@ + +#include "ApiResponse.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_ApiResponse_code_is_assigned_from_json() +{ + bourne::json input = + { + "code", 1 + }; + + ApiResponse obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getCode()); + + + + + + + + +} + + +void test_ApiResponse_type_is_assigned_from_json() +{ + + + bourne::json input = + { + "type", "hello" + }; + + ApiResponse obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getType().c_str()); + + + + + + +} + + +void test_ApiResponse_message_is_assigned_from_json() +{ + + + bourne::json input = + { + "message", "hello" + }; + + ApiResponse obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getMessage().c_str()); + + + + + + +} + + + +void test_ApiResponse_code_is_converted_to_json() +{ + bourne::json input = + { + "code", 1 + }; + + ApiResponse obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["code"] == output["code"]); + + + + +} + + +void test_ApiResponse_type_is_converted_to_json() +{ + + bourne::json input = + { + "type", "hello" + }; + + ApiResponse obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["type"] == output["type"]); + + + +} + + +void test_ApiResponse_message_is_converted_to_json() +{ + + bourne::json input = + { + "message", "hello" + }; + + ApiResponse obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["message"] == output["message"]); + + + +} + + diff --git a/samples/client/petstore/tiny/cpp/lib/TestFiles/CategoryTest.cpp b/samples/client/petstore/tiny/cpp/lib/TestFiles/CategoryTest.cpp new file mode 100644 index 000000000000..2951856e6a58 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/TestFiles/CategoryTest.cpp @@ -0,0 +1,97 @@ + +#include "Category.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_Category_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + Category obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + +void test_Category_name_is_assigned_from_json() +{ + + + bourne::json input = + { + "name", "hello" + }; + + Category obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getName().c_str()); + + + + + + +} + + + +void test_Category_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + Category obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + +void test_Category_name_is_converted_to_json() +{ + + bourne::json input = + { + "name", "hello" + }; + + Category obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["name"] == output["name"]); + + + +} + + diff --git a/samples/client/petstore/tiny/cpp/lib/TestFiles/OrderTest.cpp b/samples/client/petstore/tiny/cpp/lib/TestFiles/OrderTest.cpp new file mode 100644 index 000000000000..13125fc8fc5a --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/TestFiles/OrderTest.cpp @@ -0,0 +1,245 @@ + +#include "Order.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_Order_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + Order obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + +void test_Order_petId_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "petId", 1 + }; + + Order obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getPetId()); + + +} + + +void test_Order_quantity_is_assigned_from_json() +{ + bourne::json input = + { + "quantity", 1 + }; + + Order obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getQuantity()); + + + + + + + + +} + + +void test_Order_shipDate_is_assigned_from_json() +{ + + + + + + + + +} + + +void test_Order_status_is_assigned_from_json() +{ + + + bourne::json input = + { + "status", "hello" + }; + + Order obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getStatus().c_str()); + + + + + + +} + + +void test_Order_complete_is_assigned_from_json() +{ + + + + + bourne::json input = + { + "complete", true + }; + + Order obj(input.dump()); + + TEST_ASSERT(true == obj.isComplete()); + + + + +} + + + +void test_Order_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + +void test_Order_petId_is_converted_to_json() +{ + + + + bourne::json input = + { + "petId", 1 + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["petId"] == output["petId"]); + +} + + +void test_Order_quantity_is_converted_to_json() +{ + bourne::json input = + { + "quantity", 1 + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["quantity"] == output["quantity"]); + + + + +} + + +void test_Order_shipDate_is_converted_to_json() +{ + + + + +} + + +void test_Order_status_is_converted_to_json() +{ + + bourne::json input = + { + "status", "hello" + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["status"] == output["status"]); + + + +} + + +void test_Order_complete_is_converted_to_json() +{ + + + bourne::json input = + { + "complete", true + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["complete"] == output["complete"]); + + +} + + diff --git a/samples/client/petstore/tiny/cpp/lib/TestFiles/PetTest.cpp b/samples/client/petstore/tiny/cpp/lib/TestFiles/PetTest.cpp new file mode 100644 index 000000000000..04dad4640939 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/TestFiles/PetTest.cpp @@ -0,0 +1,145 @@ + +#include "Pet.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_Pet_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + Pet obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + + +void test_Pet_name_is_assigned_from_json() +{ + + + bourne::json input = + { + "name", "hello" + }; + + Pet obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getName().c_str()); + + + + + + +} + + + + +void test_Pet_status_is_assigned_from_json() +{ + + + bourne::json input = + { + "status", "hello" + }; + + Pet obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getStatus().c_str()); + + + + + + +} + + + +void test_Pet_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + Pet obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + + +void test_Pet_name_is_converted_to_json() +{ + + bourne::json input = + { + "name", "hello" + }; + + Pet obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["name"] == output["name"]); + + + +} + + + + +void test_Pet_status_is_converted_to_json() +{ + + bourne::json input = + { + "status", "hello" + }; + + Pet obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["status"] == output["status"]); + + + +} + + diff --git a/samples/client/petstore/tiny/cpp/lib/TestFiles/TagTest.cpp b/samples/client/petstore/tiny/cpp/lib/TestFiles/TagTest.cpp new file mode 100644 index 000000000000..41ea1d0095dd --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/TestFiles/TagTest.cpp @@ -0,0 +1,97 @@ + +#include "Tag.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_Tag_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + Tag obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + +void test_Tag_name_is_assigned_from_json() +{ + + + bourne::json input = + { + "name", "hello" + }; + + Tag obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getName().c_str()); + + + + + + +} + + + +void test_Tag_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + Tag obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + +void test_Tag_name_is_converted_to_json() +{ + + bourne::json input = + { + "name", "hello" + }; + + Tag obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["name"] == output["name"]); + + + +} + + diff --git a/samples/client/petstore/tiny/cpp/lib/TestFiles/UserTest.cpp b/samples/client/petstore/tiny/cpp/lib/TestFiles/UserTest.cpp new file mode 100644 index 000000000000..689ee582bee3 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/TestFiles/UserTest.cpp @@ -0,0 +1,349 @@ + +#include "User.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_User_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + +void test_User_username_is_assigned_from_json() +{ + + + bourne::json input = + { + "username", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getUsername().c_str()); + + + + + + +} + + +void test_User_firstName_is_assigned_from_json() +{ + + + bourne::json input = + { + "firstName", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getFirstName().c_str()); + + + + + + +} + + +void test_User_lastName_is_assigned_from_json() +{ + + + bourne::json input = + { + "lastName", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getLastName().c_str()); + + + + + + +} + + +void test_User_email_is_assigned_from_json() +{ + + + bourne::json input = + { + "email", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getEmail().c_str()); + + + + + + +} + + +void test_User_password_is_assigned_from_json() +{ + + + bourne::json input = + { + "password", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getPassword().c_str()); + + + + + + +} + + +void test_User_phone_is_assigned_from_json() +{ + + + bourne::json input = + { + "phone", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getPhone().c_str()); + + + + + + +} + + +void test_User_userStatus_is_assigned_from_json() +{ + bourne::json input = + { + "userStatus", 1 + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getUserStatus()); + + + + + + + + +} + + + +void test_User_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + +void test_User_username_is_converted_to_json() +{ + + bourne::json input = + { + "username", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["username"] == output["username"]); + + + +} + + +void test_User_firstName_is_converted_to_json() +{ + + bourne::json input = + { + "firstName", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["firstName"] == output["firstName"]); + + + +} + + +void test_User_lastName_is_converted_to_json() +{ + + bourne::json input = + { + "lastName", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["lastName"] == output["lastName"]); + + + +} + + +void test_User_email_is_converted_to_json() +{ + + bourne::json input = + { + "email", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["email"] == output["email"]); + + + +} + + +void test_User_password_is_converted_to_json() +{ + + bourne::json input = + { + "password", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["password"] == output["password"]); + + + +} + + +void test_User_phone_is_converted_to_json() +{ + + bourne::json input = + { + "phone", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["phone"] == output["phone"]); + + + +} + + +void test_User_userStatus_is_converted_to_json() +{ + bourne::json input = + { + "userStatus", 1 + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["userStatus"] == output["userStatus"]); + + + + +} + + diff --git a/samples/client/petstore/tiny/cpp/lib/service/AbstractService.cpp b/samples/client/petstore/tiny/cpp/lib/service/AbstractService.cpp new file mode 100644 index 000000000000..ac7e992cecc2 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/AbstractService.cpp @@ -0,0 +1,8 @@ +#include "AbstractService.h" +#include "Arduino.h" + + + +void Tiny::AbstractService::begin(std::string url){ + http.begin(String(url.c_str()), test_root_ca); //HTTPS connection +} diff --git a/samples/client/petstore/tiny/cpp/lib/service/AbstractService.h b/samples/client/petstore/tiny/cpp/lib/service/AbstractService.h new file mode 100644 index 000000000000..07214896d7f2 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/AbstractService.h @@ -0,0 +1,28 @@ +#ifndef TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ +#define TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ + +#include "HTTPClient.h" +#include "Response.h" +namespace Tiny { + +/** +* Class +* Generated with openapi::tiny-cpp-client +*/ +class AbstractService { +public: +HTTPClient http; +std::string basepath = "https://petstore3.swagger.io/api/v3"; // TODO: change to your url + +void begin(std::string url); + +// Go and comment out a certificate in root.cert, if you get an error here +// Certificate from file +const char* test_root_ca = +#include "../../root.cert" +; + +}; // end class +}// namespace Tinyclient + +#endif /* TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/service/PetApi.cpp b/samples/client/petstore/tiny/cpp/lib/service/PetApi.cpp new file mode 100644 index 000000000000..1fa081a04b4d --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/PetApi.cpp @@ -0,0 +1,418 @@ +#include "PetApi.h" + +using namespace Tiny; + + + + Response< + Pet + > + PetApi:: + addPet( + + Pet pet + + ) + { + std::string url = basepath + "/pet"; // + // Query | + // Headers | + // Form | + // Body | pet + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + + payload = pet.toJson().dump(); + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Pet obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + String + > + PetApi:: + deletePet( + + long petId + , + + std::string apiKey + + ) + { + std::string url = basepath + "/pet/{petId}"; //petId + // Query | + // Headers | apiKey + // Form | + // Body | + + std::string s_petId("{"); + s_petId.append("petId"); + s_petId.append("}"); + + int pos = url.find(s_petId); + + url.erase(pos, s_petId.length()); + url.insert(pos, stringify(petId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | DELETE + int httpCode = http.sendRequest("DELETE", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + std::list + > + PetApi:: + findPetsByStatus( + std::list status + + + ) + { + std::string url = basepath + "/pet/findByStatus"; // + // Query | status + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + std::list obj = std::list(); + bourne::json jsonPayload(output_string); + + + + + + + + + + for(auto& var : jsonPayload.array_range()) + { + Pet tmp(var.dump()); + obj.push_back(tmp); + } + + + + + + + + + Response> response(obj, httpCode); + return response; + } + + Response< + std::list + > + PetApi:: + findPetsByTags( + std::list tags + + + ) + { + std::string url = basepath + "/pet/findByTags"; // + // Query | tags + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + std::list obj = std::list(); + bourne::json jsonPayload(output_string); + + + + + + + + + + for(auto& var : jsonPayload.array_range()) + { + Pet tmp(var.dump()); + obj.push_back(tmp); + } + + + + + + + + + Response> response(obj, httpCode); + return response; + } + + Response< + Pet + > + PetApi:: + getPetById( + + long petId + + ) + { + std::string url = basepath + "/pet/{petId}"; //petId + // Query | + // Headers | + // Form | + // Body | + + std::string s_petId("{"); + s_petId.append("petId"); + s_petId.append("}"); + + int pos = url.find(s_petId); + + url.erase(pos, s_petId.length()); + url.insert(pos, stringify(petId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Pet obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + Pet + > + PetApi:: + updatePet( + + Pet pet + + ) + { + std::string url = basepath + "/pet"; // + // Query | + // Headers | + // Form | + // Body | pet + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | PUT + http.addHeader("Content-Type", "application/json"); + + + + payload = pet.toJson().dump(); + + int httpCode = http.sendRequest("PUT", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Pet obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + String + > + PetApi:: + updatePetWithForm( + + long petId + , + + std::string name + , + + std::string status + + ) + { + std::string url = basepath + "/pet/{petId}"; //petId + // Query | + // Headers | + // Form | name status + // Body | + + std::string s_petId("{"); + s_petId.append("petId"); + s_petId.append("}"); + + int pos = url.find(s_petId); + + url.erase(pos, s_petId.length()); + url.insert(pos, stringify(petId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + ApiResponse + > + PetApi:: + uploadFile( + + long petId + , + + std::string additionalMetadata + , + + std::string file + + ) + { + std::string url = basepath + "/pet/{petId}/uploadImage"; //petId + // Query | + // Headers | + // Form | additionalMetadata file + // Body | + + std::string s_petId("{"); + s_petId.append("petId"); + s_petId.append("}"); + + int pos = url.find(s_petId); + + url.erase(pos, s_petId.length()); + url.insert(pos, stringify(petId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + ApiResponse obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + + + diff --git a/samples/client/petstore/tiny/cpp/lib/service/PetApi.h b/samples/client/petstore/tiny/cpp/lib/service/PetApi.h new file mode 100644 index 000000000000..abcb0af0de90 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/PetApi.h @@ -0,0 +1,163 @@ +#ifndef TINY_CPP_CLIENT_PetApi_H_ +#define TINY_CPP_CLIENT_PetApi_H_ + + +#include "Response.h" +#include "Arduino.h" +#include "AbstractService.h" +#include "Helpers.h" +#include + +#include "ApiResponse.h" +#include "Pet.h" + +namespace Tiny { + +/** + * Class + * Generated with openapi::tiny-cpp-client + */ + +class PetApi : public AbstractService { +public: + PetApi() = default; + + virtual ~PetApi() = default; + + /** + * Add a new pet to the store. + * + * + * \param pet Pet object that needs to be added to the store *Required* + */ + Response< + Pet + > + addPet( + + Pet pet + + ); + /** + * Deletes a pet. + * + * + * \param petId Pet id to delete *Required* + * \param apiKey + */ + Response< + String + > + deletePet( + + long petId + , + + std::string apiKey + + ); + /** + * Finds Pets by status. + * + * Multiple status values can be provided with comma separated strings + * \param status Status values that need to be considered for filter *Required* + */ + Response< + std::list + > + findPetsByStatus( + std::list status + + + ); + /** + * Finds Pets by tags. + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * \param tags Tags to filter by *Required* + */ + Response< + std::list + > + findPetsByTags( + std::list tags + + + ); + /** + * Find pet by ID. + * + * Returns a single pet + * \param petId ID of pet to return *Required* + */ + Response< + Pet + > + getPetById( + + long petId + + ); + /** + * Update an existing pet. + * + * + * \param pet Pet object that needs to be added to the store *Required* + */ + Response< + Pet + > + updatePet( + + Pet pet + + ); + /** + * Updates a pet in the store with form data. + * + * + * \param petId ID of pet that needs to be updated *Required* + * \param name Updated name of the pet + * \param status Updated status of the pet + */ + Response< + String + > + updatePetWithForm( + + long petId + , + + std::string name + , + + std::string status + + ); + /** + * uploads an image. + * + * + * \param petId ID of pet to update *Required* + * \param additionalMetadata Additional data to pass to server + * \param file file to upload + */ + Response< + ApiResponse + > + uploadFile( + + long petId + , + + std::string additionalMetadata + , + + std::string file + + ); +}; + +} + +#endif /* TINY_CPP_CLIENT_PetApi_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/tiny/cpp/lib/service/Response.h b/samples/client/petstore/tiny/cpp/lib/service/Response.h new file mode 100644 index 000000000000..9b7b616b8f1b --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/Response.h @@ -0,0 +1,25 @@ +#ifndef TINY_CPP_CLIENT_RESPONSE_H_ +#define TINY_CPP_CLIENT_RESPONSE_H_ +#include + +namespace Tiny { + +/** +* Class +* Generated with openapi::tiny-cpp-client +*/ +template + class Response { + public: + + Response(T _obj, int _code){ + obj = _obj; + code = _code; + } + + int code; + T obj; + }; + } // namespace Tinyclient + +#endif /* TINY_CPP_CLIENT_RESPONSE_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/service/StoreApi.cpp b/samples/client/petstore/tiny/cpp/lib/service/StoreApi.cpp new file mode 100644 index 000000000000..210eb8277ac6 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/StoreApi.cpp @@ -0,0 +1,185 @@ +#include "StoreApi.h" + +using namespace Tiny; + + + + Response< + String + > + StoreApi:: + deleteOrder( + + std::string orderId + + ) + { + std::string url = basepath + "/store/order/{orderId}"; //orderId + // Query | + // Headers | + // Form | + // Body | + + std::string s_orderId("{"); + s_orderId.append("orderId"); + s_orderId.append("}"); + + int pos = url.find(s_orderId); + + url.erase(pos, s_orderId.length()); + url.insert(pos, stringify(orderId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | DELETE + int httpCode = http.sendRequest("DELETE", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + StoreApi:: + getInventory( + ) + { + std::string url = basepath + "/store/inventory"; // + // Query | + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + //TODO: Implement map logic here + + + + + //TODO: No support for maps. + Response response(output, httpCode); + return response; + } + + Response< + Order + > + StoreApi:: + getOrderById( + + long orderId + + ) + { + std::string url = basepath + "/store/order/{orderId}"; //orderId + // Query | + // Headers | + // Form | + // Body | + + std::string s_orderId("{"); + s_orderId.append("orderId"); + s_orderId.append("}"); + + int pos = url.find(s_orderId); + + url.erase(pos, s_orderId.length()); + url.insert(pos, stringify(orderId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Order obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + Order + > + StoreApi:: + placeOrder( + + Order order + + ) + { + std::string url = basepath + "/store/order"; // + // Query | + // Headers | + // Form | + // Body | order + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + + payload = order.toJson().dump(); + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Order obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + + + diff --git a/samples/client/petstore/tiny/cpp/lib/service/StoreApi.h b/samples/client/petstore/tiny/cpp/lib/service/StoreApi.h new file mode 100644 index 000000000000..1bf0db023737 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/StoreApi.h @@ -0,0 +1,83 @@ +#ifndef TINY_CPP_CLIENT_StoreApi_H_ +#define TINY_CPP_CLIENT_StoreApi_H_ + + +#include "Response.h" +#include "Arduino.h" +#include "AbstractService.h" +#include "Helpers.h" +#include + +#include +#include "Order.h" + +namespace Tiny { + +/** + * Class + * Generated with openapi::tiny-cpp-client + */ + +class StoreApi : public AbstractService { +public: + StoreApi() = default; + + virtual ~StoreApi() = default; + + /** + * Delete purchase order by ID. + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * \param orderId ID of the order that needs to be deleted *Required* + */ + Response< + String + > + deleteOrder( + + std::string orderId + + ); + /** + * Returns pet inventories by status. + * + * Returns a map of status codes to quantities + */ + Response< + String + > + getInventory( + ); + /** + * Find purchase order by ID. + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * \param orderId ID of pet that needs to be fetched *Required* + */ + Response< + Order + > + getOrderById( + + long orderId + + ); + /** + * Place an order for a pet. + * + * + * \param order order placed for purchasing the pet *Required* + */ + Response< + Order + > + placeOrder( + + Order order + + ); +}; + +} + +#endif /* TINY_CPP_CLIENT_StoreApi_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/tiny/cpp/lib/service/UserApi.cpp b/samples/client/petstore/tiny/cpp/lib/service/UserApi.cpp new file mode 100644 index 000000000000..d1cf12b80a9e --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/UserApi.cpp @@ -0,0 +1,366 @@ +#include "UserApi.h" + +using namespace Tiny; + + + + Response< + String + > + UserApi:: + createUser( + + User user + + ) + { + std::string url = basepath + "/user"; // + // Query | + // Headers | + // Form | + // Body | user + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + + payload = user.toJson().dump(); + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + UserApi:: + createUsersWithArrayInput( + std::list user + + + ) + { + std::string url = basepath + "/user/createWithArray"; // + // Query | + // Headers | + // Form | + // Body | user + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + bourne::json tmp_arr = bourne::json::array(); + for(auto& var : user) + { + auto tmp = var.toJson(); + tmp_arr.append(tmp); + + } + payload = tmp_arr.dump(); + + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + UserApi:: + createUsersWithListInput( + std::list user + + + ) + { + std::string url = basepath + "/user/createWithList"; // + // Query | + // Headers | + // Form | + // Body | user + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + bourne::json tmp_arr = bourne::json::array(); + for(auto& var : user) + { + auto tmp = var.toJson(); + tmp_arr.append(tmp); + + } + payload = tmp_arr.dump(); + + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + UserApi:: + deleteUser( + + std::string username + + ) + { + std::string url = basepath + "/user/{username}"; //username + // Query | + // Headers | + // Form | + // Body | + + std::string s_username("{"); + s_username.append("username"); + s_username.append("}"); + + int pos = url.find(s_username); + + url.erase(pos, s_username.length()); + url.insert(pos, stringify(username)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | DELETE + int httpCode = http.sendRequest("DELETE", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + User + > + UserApi:: + getUserByName( + + std::string username + + ) + { + std::string url = basepath + "/user/{username}"; //username + // Query | + // Headers | + // Form | + // Body | + + std::string s_username("{"); + s_username.append("username"); + s_username.append("}"); + + int pos = url.find(s_username); + + url.erase(pos, s_username.length()); + url.insert(pos, stringify(username)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + User obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + std::string + > + UserApi:: + loginUser( + + std::string username + , + + std::string password + + ) + { + std::string url = basepath + "/user/login"; // + // Query | username password + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + bourne::json jsonPayload(output_string); + std::string obj; + jsonToValue(&obj, jsonPayload, "std::string"); + + + + Response response(obj, httpCode); + return response; + } + + Response< + String + > + UserApi:: + logoutUser( + ) + { + std::string url = basepath + "/user/logout"; // + // Query | + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + UserApi:: + updateUser( + + std::string username + , + + User user + + ) + { + std::string url = basepath + "/user/{username}"; //username + // Query | + // Headers | + // Form | + // Body | user + + std::string s_username("{"); + s_username.append("username"); + s_username.append("}"); + + int pos = url.find(s_username); + + url.erase(pos, s_username.length()); + url.insert(pos, stringify(username)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | PUT + http.addHeader("Content-Type", "application/json"); + + + + payload = user.toJson().dump(); + + int httpCode = http.sendRequest("PUT", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + + + diff --git a/samples/client/petstore/tiny/cpp/lib/service/UserApi.h b/samples/client/petstore/tiny/cpp/lib/service/UserApi.h new file mode 100644 index 000000000000..afdaefa0f8c9 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/UserApi.h @@ -0,0 +1,147 @@ +#ifndef TINY_CPP_CLIENT_UserApi_H_ +#define TINY_CPP_CLIENT_UserApi_H_ + + +#include "Response.h" +#include "Arduino.h" +#include "AbstractService.h" +#include "Helpers.h" +#include + +#include "User.h" +#include + +namespace Tiny { + +/** + * Class + * Generated with openapi::tiny-cpp-client + */ + +class UserApi : public AbstractService { +public: + UserApi() = default; + + virtual ~UserApi() = default; + + /** + * Create user. + * + * This can only be done by the logged in user. + * \param user Created user object *Required* + */ + Response< + String + > + createUser( + + User user + + ); + /** + * Creates list of users with given input array. + * + * + * \param user List of user object *Required* + */ + Response< + String + > + createUsersWithArrayInput( + std::list user + + + ); + /** + * Creates list of users with given input array. + * + * + * \param user List of user object *Required* + */ + Response< + String + > + createUsersWithListInput( + std::list user + + + ); + /** + * Delete user. + * + * This can only be done by the logged in user. + * \param username The name that needs to be deleted *Required* + */ + Response< + String + > + deleteUser( + + std::string username + + ); + /** + * Get user by user name. + * + * + * \param username The name that needs to be fetched. Use user1 for testing. *Required* + */ + Response< + User + > + getUserByName( + + std::string username + + ); + /** + * Logs user into the system. + * + * + * \param username The user name for login *Required* + * \param password The password for login in clear text *Required* + */ + Response< + std::string + > + loginUser( + + std::string username + , + + std::string password + + ); + /** + * Logs out current logged in user session. + * + * + */ + Response< + String + > + logoutUser( + ); + /** + * Updated user. + * + * This can only be done by the logged in user. + * \param username name that need to be deleted *Required* + * \param user Updated user object *Required* + */ + Response< + String + > + updateUser( + + std::string username + , + + User user + + ); +}; + +} + +#endif /* TINY_CPP_CLIENT_UserApi_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/tiny/cpp/platformio.ini b/samples/client/petstore/tiny/cpp/platformio.ini new file mode 100644 index 000000000000..00781178d10b --- /dev/null +++ b/samples/client/petstore/tiny/cpp/platformio.ini @@ -0,0 +1,7 @@ +[env:esp32] +platform = espressif32 +board = nodemcu-32s +framework = arduino +lib_deps = https://github.com/steinwurf/bourne.git +extra_scripts = pre_compiling_bourne.py + diff --git a/samples/client/petstore/tiny/cpp/pre_compiling_bourne.py b/samples/client/petstore/tiny/cpp/pre_compiling_bourne.py new file mode 100644 index 000000000000..96356dcdf158 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/pre_compiling_bourne.py @@ -0,0 +1,25 @@ +Import("env") + +## Compatibility for bourne to work on microcontrollers +# We insert '#define _GLIBCXX_USE_C99' in files that use std::stoll or std::to_string +def insert_c99_into(file): + import fileinput + + path = env['PROJECT_LIBDEPS_DIR'] + "/" + env['PIOENV'] + "/bourne/src/bourne/" + file + value = '#define _GLIBCXX_USE_C99 1\n' + + for line in fileinput.FileInput(path,inplace=1): + if line.startswith('#define _GLIBCXX_USE_C99'): + continue + elif line.startswith('// D'): + line=line.replace(line,line+value) + print(line, end='') + +def fix_parser(): + insert_c99_into('detail/parser.cpp') + +def fix_json(): + insert_c99_into('json.cpp') + +fix_parser() +fix_json() \ No newline at end of file diff --git a/samples/client/petstore/tiny/cpp/root.cert b/samples/client/petstore/tiny/cpp/root.cert new file mode 100644 index 000000000000..bad9c08efad1 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/root.cert @@ -0,0 +1,53 @@ +// TODO: Provide your service root certificate. +// Below is two examples of root certificates. + +// Let's encrypt root certificate +/** +"-----BEGIN CERTIFICATE-----\n" \ +"MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n" \ +"MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" \ +"d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n" \ +"QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n" \ +"MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n" \ +"b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n" \ +"9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n" \ +"CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n" \ +"nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n" \ +"43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n" \ +"T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n" \ +"gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n" \ +"BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n" \ +"TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n" \ +"DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n" \ +"hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n" \ +"06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n" \ +"PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n" \ +"YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n" \ +"CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n" \ +"-----END CERTIFICATE-----\n" +*/ + +// Amazon_Root_CA_1.pem +/** +"-----BEGIN CERTIFICATE-----\n" \ +"MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF\n" \ +"ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\n" \ +"b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL\n" \ +"MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv\n" \ +"b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj\n" \ +"ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM\n" \ +"9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw\n" \ +"IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6\n" \ +"VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L\n" \ +"93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm\n" \ +"jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\n" \ +"AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA\n" \ +"A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI\n" \ +"U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs\n" \ +"N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv\n" \ +"o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU\n" \ +"5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy\n" \ +"rqXRfboQnoZsG4q5WTP468SQvvG5\n" \ +"-----END CERTIFICATE-----\n" \ +*/ + diff --git a/samples/client/petstore/tiny/cpp/src/main.cpp b/samples/client/petstore/tiny/cpp/src/main.cpp new file mode 100644 index 000000000000..34ba455fbdd3 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/src/main.cpp @@ -0,0 +1,37 @@ +#include "PetApi.h" + +const char* ssid = "your wifi name"; // TODO Change wifi name +const char* password = "Your wifi password"; //TODO Change wifi password + + +void setup(){ + //Initialize serial and wait for port to open: + Serial.begin(9600); + delay(100); + + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + WiFi.begin(ssid, password); + + // attempt to connect to Wifi network: + while (WiFi.status() != WL_CONNECTED) { + Serial.print("."); + // wait 1 second for re-trying + delay(1000); + } + + Serial.print("Connected to "); + Serial.println(ssid); + + //Print LAN IP. + Serial.print("IP address set: "); + Serial.println(WiFi.localIP()); + + Tiny::PetApi petapi; + auto resp = petapi.getPetById(10); + Serial.println(resp.code); + Tiny::Pet pet = resp.obj; + Serial.println(pet.toJson().dump().c_str()); +} + +void loop(){} diff --git a/samples/client/petstore/tiny/cpp/test/RunTests.cpp b/samples/client/petstore/tiny/cpp/test/RunTests.cpp new file mode 100644 index 000000000000..4caafb4ee441 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/test/RunTests.cpp @@ -0,0 +1,204 @@ + +#include "ApiResponseTest.cpp" + +#include "CategoryTest.cpp" + +#include "OrderTest.cpp" + +#include "PetTest.cpp" + +#include "TagTest.cpp" + +#include "UserTest.cpp" + + + +void setUp(){} + +void tearDown(){} + +void runTests(){ + + + RUN_TEST(test_ApiResponse_code_is_assigned_from_json); + + + RUN_TEST(test_ApiResponse_type_is_assigned_from_json); + + + RUN_TEST(test_ApiResponse_message_is_assigned_from_json); + + + + RUN_TEST(test_Category_id_is_assigned_from_json); + + + RUN_TEST(test_Category_name_is_assigned_from_json); + + + + RUN_TEST(test_Order_id_is_assigned_from_json); + + + RUN_TEST(test_Order_petId_is_assigned_from_json); + + + RUN_TEST(test_Order_quantity_is_assigned_from_json); + + + RUN_TEST(test_Order_shipDate_is_assigned_from_json); + + + RUN_TEST(test_Order_status_is_assigned_from_json); + + + RUN_TEST(test_Order_complete_is_assigned_from_json); + + + + RUN_TEST(test_Pet_id_is_assigned_from_json); + + + + RUN_TEST(test_Pet_name_is_assigned_from_json); + + + + + RUN_TEST(test_Pet_status_is_assigned_from_json); + + + + RUN_TEST(test_Tag_id_is_assigned_from_json); + + + RUN_TEST(test_Tag_name_is_assigned_from_json); + + + + RUN_TEST(test_User_id_is_assigned_from_json); + + + RUN_TEST(test_User_username_is_assigned_from_json); + + + RUN_TEST(test_User_firstName_is_assigned_from_json); + + + RUN_TEST(test_User_lastName_is_assigned_from_json); + + + RUN_TEST(test_User_email_is_assigned_from_json); + + + RUN_TEST(test_User_password_is_assigned_from_json); + + + RUN_TEST(test_User_phone_is_assigned_from_json); + + + RUN_TEST(test_User_userStatus_is_assigned_from_json); + + + + + + RUN_TEST(test_ApiResponse_code_is_converted_to_json); + + + RUN_TEST(test_ApiResponse_type_is_converted_to_json); + + + RUN_TEST(test_ApiResponse_message_is_converted_to_json); + + + + RUN_TEST(test_Category_id_is_converted_to_json); + + + RUN_TEST(test_Category_name_is_converted_to_json); + + + + RUN_TEST(test_Order_id_is_converted_to_json); + + + RUN_TEST(test_Order_petId_is_converted_to_json); + + + RUN_TEST(test_Order_quantity_is_converted_to_json); + + + RUN_TEST(test_Order_shipDate_is_converted_to_json); + + + RUN_TEST(test_Order_status_is_converted_to_json); + + + RUN_TEST(test_Order_complete_is_converted_to_json); + + + + RUN_TEST(test_Pet_id_is_converted_to_json); + + + + RUN_TEST(test_Pet_name_is_converted_to_json); + + + + + RUN_TEST(test_Pet_status_is_converted_to_json); + + + + RUN_TEST(test_Tag_id_is_converted_to_json); + + + RUN_TEST(test_Tag_name_is_converted_to_json); + + + + RUN_TEST(test_User_id_is_converted_to_json); + + + RUN_TEST(test_User_username_is_converted_to_json); + + + RUN_TEST(test_User_firstName_is_converted_to_json); + + + RUN_TEST(test_User_lastName_is_converted_to_json); + + + RUN_TEST(test_User_email_is_converted_to_json); + + + RUN_TEST(test_User_password_is_converted_to_json); + + + RUN_TEST(test_User_phone_is_converted_to_json); + + + RUN_TEST(test_User_userStatus_is_converted_to_json); + + + + +} + +int main(void) { + UNITY_BEGIN(); + runTests(); + return UNITY_END(); +} + +void setup() { + UNITY_BEGIN(); + runTests(); + UNITY_END(); +} + +void loop() { + +}