diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerCodegen.java index a6d17cbfbff..ca3e6c02f48 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerCodegen.java @@ -315,13 +315,14 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen { if (!foundInNewList) { if (op1.path.equals(op.path)) { foundInNewList = true; - List currentOtherMethodList = (List) op1.vendorExtensions.get("x-codegen-otherMethods"); + final String X_CODEGEN_OTHER_METHODS = "x-codegen-other-methods"; + List currentOtherMethodList = (List) op1.vendorExtensions.get(X_CODEGEN_OTHER_METHODS); if (currentOtherMethodList == null) { currentOtherMethodList = new ArrayList(); } op.operationIdCamelCase = op1.operationIdCamelCase; currentOtherMethodList.add(op); - op1.vendorExtensions.put("x-codegen-other-methods", currentOtherMethodList); + op1.vendorExtensions.put(X_CODEGEN_OTHER_METHODS, currentOtherMethodList); } } } diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-header.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-header.mustache index 30e1154cff5..80c7b0d4dd7 100644 --- a/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-header.mustache @@ -11,10 +11,13 @@ {{{defaultInclude}}} #include #include +#include #include #include +#include #include +#include {{#imports}}{{{import}}} {{/imports}} @@ -25,6 +28,22 @@ namespace {{this}} { using namespace {{modelNamespace}}; +/// +/// Exception to flag problems in the handlers +/// +class {{declspec}} {{classname}}Exception: public std::exception +{ +public: + {{classname}}Exception(int status_code, std::string what); + + int getStatus() const; + const char* what() const noexcept override; + +private: + int m_status; + std::string m_what; +}; + {{#operation}} /// /// {{summary}} @@ -35,60 +54,143 @@ using namespace {{modelNamespace}}; class {{declspec}} {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource: public restbed::Resource { public: - {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(); + {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(const std::string& context = "{{contextPath}}"); virtual ~{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(); - void {{httpMethod}}_method_handler(const std::shared_ptr session); + +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual {{#returnType}}std::pair{{/returnType}}{{^returnType}}int{{/returnType}} handler_{{httpMethod}}( + {{#allParams}}{{{dataType}}} const & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}); + {{#vendorExtensions.x-codegen-other-methods}} - void {{httpMethod}}_method_handler(const std::shared_ptr session); + virtual {{#returnType}}std::pair{{/returnType}}{{^returnType}}int{{/returnType}} handler_{{httpMethod}}( + {{#allParams}}{{{dataType}}} const & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}); {{/vendorExtensions.x-codegen-other-methods}} - void set_handler_{{httpMethod}}( - std::function( - {{#allParams}}{{{dataType}}} const &{{^-last}}, {{/-last}}{{/allParams}} - )> handler - ); +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// - {{#vendorExtensions.x-codegen-other-methods}} - void set_handler_{{httpMethod}}( - std::function( - {{#allParams}}{{{dataType}}} const &{{^-last}}, {{/-last}}{{/allParams}} - )> handler - ); - {{/vendorExtensions.x-codegen-other-methods}} + virtual std::string extractBodyContent(const std::shared_ptr& session); + + {{#hasPathParams}} + {{#pathParams}} + {{#isPrimitiveType}} + virtual {{{dataType}}} getPathParam_{{{paramName}}}(const std::shared_ptr& request) + { + return request->get_path_parameter("{{{paramName}}}", {{{defaultValue}}}); + } + + {{/isPrimitiveType}} + {{/pathParams}} + {{/hasPathParams}} + {{#hasQueryParams}} + {{#queryParams}} + {{#isPrimitiveType}} + virtual {{{dataType}}} getQueryParam_{{{paramName}}}(const std::shared_ptr& request) + { + return request->get_query_parameter("{{{paramName}}}", {{{defaultValue}}}); + } + + {{/isPrimitiveType}} + {{/queryParams}} + {{/hasQueryParams}} + {{#hasHeaderParams}} + {{#headerParams}} + {{#isPrimitiveType}} + virtual {{{dataType}}} getHeader_{{{baseName}}}(const std::shared_ptr& request) + { + return request->get_header("{{baseName}}", {{{defaultValue}}}); + } + + {{/isPrimitiveType}} + {{/headerParams}} + {{/hasHeaderParams}} + + {{#vendorExtensions.x-codegen-other-methods}} + {{#hasPathParams}} + {{#pathParams}} + {{#isPrimitiveType}} + virtual {{{dataType}}} getPathParam_{{{paramName}}}_x_extension(const std::shared_ptr& request) + { + return request->get_path_parameter("{{{paramName}}}", {{{defaultValue}}}); + } + {{/isPrimitiveType}} + {{/pathParams}} + {{/hasPathParams}} + {{#hasQueryParams}} + {{#queryParams}} + {{#isPrimitiveType}} + virtual {{{dataType}}} getQueryParam_{{{paramName}}}_x_extension(const std::shared_ptr& request) + { + return request->get_query_parameter("{{{paramName}}}", {{{defaultValue}}}); + } + {{/isPrimitiveType}} + {{/queryParams}} + {{/hasQueryParams}} + {{#hasHeaderParams}} + {{#headerParams}} + {{#isPrimitiveType}} + virtual {{{dataType}}} getHeader_{{{baseName}}}_x_extension(const std::shared_ptr& request) + { + return request->get_header("{{baseName}}", {{{defaultValue}}}); + } + {{/isPrimitiveType}} + {{/headerParams}} + {{/hasHeaderParams}} + {{/vendorExtensions.x-codegen-other-methods}} + + virtual std::pair handle{{classname}}Exception(const {{classname}}Exception& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); private: - std::function( - {{#allParams}}{{{dataType}}} const &{{^-last}}, {{/-last}}{{/allParams}} - )> handler_{{httpMethod}}_; - - {{#vendorExtensions.x-codegen-other-methods}} - std::function( - {{#allParams}}{{{dataType}}} const &{{^-last}}, {{/-last}}{{/allParams}} - )> handler_{{httpMethod}}_; - {{/vendorExtensions.x-codegen-other-methods}} - - {{#allParams}} - {{{dataType}}} {{paramName}}{}; - {{/allParams}} + void handler_{{httpMethod}}_internal(const std::shared_ptr session); + {{#vendorExtensions.x-codegen-other-methods}} + void handler_{{httpMethod}}_internal(const std::shared_ptr session); + {{/vendorExtensions.x-codegen-other-methods}} }; + {{/operation}} // // The restbed service to actually implement the REST server // -class {{declspec}} {{classname}}: public restbed::Service +class {{declspec}} {{classname}} { public: - {{classname}}(); - ~{{classname}}(); - void startService(int const& port); - void stopService(); + explicit {{classname}}(std::shared_ptr const& restbedService); + virtual ~{{classname}}(); + + {{#operation}} + virtual void set{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(std::shared_ptr<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource> sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource); + {{/operation}} + + virtual void publishDefaultResources(); + + virtual std::shared_ptr service(); protected: {{#operation}} std::shared_ptr<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource> m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource; {{/operation}} + +private: + std::shared_ptr m_service; }; diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-source.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-source.mustache index e80c89321fc..6a9c99ab284 100644 --- a/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-source.mustache @@ -5,6 +5,11 @@ #include #include #include +#include +#include +#include +#include +#include #include "{{classname}}.h" @@ -14,43 +19,73 @@ namespace {{this}} { using namespace {{modelNamespace}}; -{{classname}}::{{classname}}() { +{{classname}}Exception::{{classname}}Exception(int status_code, std::string what) + : m_status(status_code), + m_what(what) +{ + +} +int {{classname}}Exception::getStatus() const +{ + return m_status; +} +const char* {{classname}}Exception::what() const noexcept +{ + return m_what.c_str(); } -{{classname}}::~{{classname}}() {} -void {{classname}}::startService(int const& port) { - // A typical pattern is to derive a class from {{classname}} and allocate the shared pointers for restbed::Resource objects - // and manipulate them (e.g. binding GET/POST handler functions) before this startService() gets called. - // In such a case we want to use our m_spXXX variables. - // However in case these shared pointers are nullptr, then allocate the restbed::Resources now: - {{#operation}} - if (!m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource) - m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource = std::make_shared<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource>(); - this->publish(m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource); - {{/operation}} +template +std::shared_ptr extractJsonModelBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); - std::shared_ptr settings = std::make_shared(); - settings->set_port(port); - settings->set_root("{{contextPath}}"); - - this->start(settings); + auto model = std::make_shared(pt); + return model; } -void {{classname}}::stopService() { - this->stop(); +template +std::vector> extractJsonArrayBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto arrayRet = std::vector>(); + for (const auto& child: pt) { + arrayRet.emplace_back(std::make_shared(child.second)); + } + return arrayRet; +} + +template +std::string convertMapResponse(const std::map& map) +{ + boost::property_tree::ptree pt; + for(const auto &kv: map) { + pt.push_back(boost::property_tree::ptree::value_type( + boost::lexical_cast(kv.first), + boost::property_tree::ptree( + boost::lexical_cast(kv.second)))); + } + std::stringstream sstream; + write_json(sstream, pt); + std::string result = sstream.str(); + return result; } {{#operation}} -{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource() +{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(const std::string& context /* = "{{contextPath}}" */) { - this->set_path("{{path}}"); + this->set_path(context + "{{path}}"); this->set_method_handler("{{httpMethod}}", - std::bind(&{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::{{httpMethod}}_method_handler, this, + std::bind(&{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}_internal, this, std::placeholders::_1)); {{#vendorExtensions.x-codegen-other-methods}} this->set_method_handler("{{httpMethod}}", - std::bind(&{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::{{httpMethod}}_method_handler, this, + std::bind(&{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}_internal, this, std::placeholders::_1)); {{/vendorExtensions.x-codegen-other-methods}} } @@ -59,169 +94,305 @@ void {{classname}}::stopService() { { } -void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::set_handler_{{httpMethod}}( - std::function( - {{#allParams}}{{{dataType}}} const &{{^-last}}, {{/-last}}{{/allParams}} - )> handler) { - handler_{{httpMethod}}_ = std::move(handler); +std::pair {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handle{{classname}}Exception(const {{classname}}Exception& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + {{#hasBodyParam}} + std::string bodyContent = extractBodyContent(session); + + // Get body params or form params here from the body content string + {{#allParams}} + {{#isModel}} + auto {{paramName}} = extractJsonModelBodyParam<{{{baseType}}}>(bodyContent); + {{/isModel}} + {{#isArray}} + auto {{paramName}} = extractJsonArrayBodyParam<{{{baseType}}}>(bodyContent); + {{/isArray}} + {{/allParams}} + {{/hasBodyParam}} + + {{#hasPathParams}} + // Getting the path params + {{#pathParams}} + {{#isPrimitiveType}} + const {{{dataType}}} {{{paramName}}} = getPathParam_{{paramName}}(request); + {{/isPrimitiveType}} + {{/pathParams}} + {{/hasPathParams}} + + {{#hasQueryParams}} + // Getting the query params + {{#queryParams}} + {{#isPrimitiveType}} + const {{{dataType}}} {{{paramName}}} = getQueryParam_{{paramName}}(request); + {{/isPrimitiveType}} + {{/queryParams}} + {{/hasQueryParams}} + + {{#hasHeaderParams}} + // Getting the headers + {{#headerParams}} + {{#isPrimitiveType}} + const {{{dataType}}} {{{paramName}}} = getHeader_{{baseName}}(request); + {{/isPrimitiveType}} + {{/headerParams}} + {{/hasHeaderParams}} + + int status_code = 500; + {{#returnType}} + {{{.}}} resultObject = {{{defaultResponse}}}; + {{/returnType}} + std::string result = ""; + + try { + {{#returnType}} + std::tie(status_code, resultObject) = + {{/returnType}} + {{^returnType}} + status_code = + {{/returnType}} + handler_{{httpMethod}}({{#allParams}}{{paramName}}{{^-last}}, {{ / -last}}{{ / allParams}}); + } + catch(const {{classname}}Exception& e) { + std::tie(status_code, result) = handle{{classname}}Exception(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + {{#responses}} + if (status_code == {{code}}) { + {{#returnType}} + {{#isModel}} + {{#isString}} + result = resultObject; + {{/isString}} + {{^isString}} + result = resultObject->toJsonString(); + {{/isString}} + {{/isModel}} + {{#isMap}} + result = convertMapResponse(resultObject); + {{/isMap}} + {{/returnType}} + {{#headers}} + // Description: {{{description}}} + setResponseHeader(session, "{{baseName}}"); + {{/headers}} + + {{#primitiveType}} + const constexpr auto contentType = "text/plain"; + {{/primitiveType}} + {{^primitiveType}} + const constexpr auto contentType = "application/json"; + {{/primitiveType}} + returnResponse(session, {{code}}, result.empty() ? "{{message}}" : result, contentType); + return; + } + {{/responses}} + defaultSessionClose(session, status_code, result); } {{#vendorExtensions.x-codegen-other-methods}} -void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::set_handler_{{httpMethod}}( - std::function( - {{#allParams}}{{{dataType}}} const &{{^-last}}, {{/-last}}{{/allParams}} - )> handler) { - handler_{{httpMethod}}_ = std::move(handler); +// x-extension +void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}_internal(const std::shared_ptr session) { + + const auto request = session->get_request(); + {{#hasBodyParam}} + std::string bodyContent = extractBodyContent(session); + + // body params or form params here from the body content string + {{#allParams}} + {{#isModel}} + auto {{paramName}} = extractJsonModelBodyParam<{{{baseType}}}>(bodyContent); + {{/isModel}} + {{#isArray}} + auto {{paramName}} = extractJsonArrayBodyParam<{{{baseType}}}>(bodyContent); + {{/isArray}} + {{^isModel}} + {{^isArray}} + auto {{paramName}} = std::make_shared<{{{baseType}}}>(bodyContent); + {{/isArray}} + {{/isModel}} + {{/allParams}} + {{/hasBodyParam}} + + {{#hasPathParams}} + // Getting the path params + {{#pathParams}} + {{#isPrimitiveType}} + const {{{dataType}}} {{{paramName}}} = getPathParam_{{paramName}}_x_extension(request); + + {{/isPrimitiveType}} + {{/pathParams}} + {{/hasPathParams}} + {{#hasQueryParams}} + // Getting the query params + {{#queryParams}} + {{#isPrimitiveType}} + const {{{dataType}}} {{{paramName}}} = getQueryParam_{{paramName}}_x_extension(request); + + {{/isPrimitiveType}} + {{/queryParams}} + {{/hasQueryParams}} + {{#hasHeaderParams}} + // Getting the headers + {{#headerParams}} + {{#isPrimitiveType}} + const {{{dataType}}} {{{paramName}}} = getHeader_{{baseName}}_x_extension(request); + + {{/isPrimitiveType}} + {{/headerParams}} + {{/hasHeaderParams}} + + int status_code = 500; + {{#returnType}} + {{{.}}} resultObject = {{{defaultResponse}}}; + {{/returnType}} + std::string result = ""; + + try { + {{#returnType}} + std::tie(status_code, resultObject) = + {{/returnType}} + {{^returnType}} + status_code = + {{/returnType}} + handler_{{httpMethod}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + } + catch(const {{classname}}Exception& e) { + std::tie(status_code, result) = handle{{classname}}Exception(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + {{#responses}} + if (status_code == {{code}}) { + {{#returnType}} + {{#isModel}} + {{#isString}} + result = resultObject; + {{/isString}} + {{^isString}} + result = resultObject->toJsonString(); + {{/isString}} + {{/isModel}} + {{#isMap}} + result = convertMapResponse(resultObject); + {{/isMap}} + {{/returnType}} + {{#headers}} + // Description: {{{description}}} + setResponseHeader(session, "{{baseName}}"); + {{/headers}} + + {{#primitiveType}} + const constexpr auto contentType = "text/plain"; + {{/primitiveType}} + {{^primitiveType}} + const constexpr auto contentType = "application/json"; + {{/primitiveType}} + returnResponse(session, {{code}}, result.empty() ? "{{message}}" : result, contentType); + return; + } + {{/responses}} + defaultSessionClose(session, status_code, result); } {{/vendorExtensions.x-codegen-other-methods}} -void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::{{httpMethod}}_method_handler(const std::shared_ptr session) { - - const auto request = session->get_request(); - {{#hasBodyParam}} - // Body params are present, therefore we have to fetch them - int content_length = request->get_header("Content-Length", 0); - session->fetch(content_length, - [ this ]( const std::shared_ptr session, const restbed::Bytes & body ) - { - - const auto request = session->get_request(); - std::string file = restbed::String::format("%.*s\n", ( int ) body.size( ), body.data( )); - /** - * Get body params or form params here from the file string - */ - {{/hasBodyParam}} - - {{#hasPathParams}} - // Getting the path params - {{#pathParams}} - {{#isPrimitiveType}} - const {{{dataType}}} {{{paramName}}} = request->get_path_parameter("{{paramName}}", {{{defaultValue}}}); - {{/isPrimitiveType}} - {{/pathParams}} - {{/hasPathParams}} - - {{#hasQueryParams}} - // Getting the query params - {{#queryParams}} - {{#isPrimitiveType}} - const {{{dataType}}} {{{paramName}}} = request->get_query_parameter("{{paramName}}", {{{defaultValue}}}); - {{/isPrimitiveType}} - {{/queryParams}} - {{/hasQueryParams}} - - {{#hasHeaderParams}} - // Getting the headers - {{#headerParams}} - {{#isPrimitiveType}} - const {{{dataType}}} {{{paramName}}} = request->get_header("{{paramName}}", {{{defaultValue}}}); - {{/isPrimitiveType}} - {{/headerParams}} - {{/hasHeaderParams}} - - // Change the value of this variable to the appropriate response before sending the response - int status_code = 200; - std::string result = "successful operation"; - - if (handler_{{httpMethod}}_) - { - std::tie(status_code, result) = handler_{{httpMethod}}_( - {{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}} - ); - } - - {{#responses}} - if (status_code == {{code}}) { - {{#headers}} - // Description: {{description}} - session->set_header("{{baseName}}", ""); // Change second param to your header value - {{/headers}} - session->close({{code}}, result.empty() ? "{{message}}" : std::move(result), { {"Connection", "close"} }); - return; - } - {{/responses}} - - {{#hasBodyParam}} - }); - {{/hasBodyParam}} +{{#returnType}}std::pair{{/returnType}}{{^returnType}}int{{/returnType}} {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}( + {{#allParams}}{{{dataType}}} const & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) +{ + throw {{classname}}Exception(501, "Not implemented"); } {{#vendorExtensions.x-codegen-other-methods}} -void {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::{{httpMethod}}_method_handler(const std::shared_ptr session) { - - const auto request = session->get_request(); - {{#hasBodyParam}} - // Body params are present, therefore we have to fetch them - int content_length = request->get_header("Content-Length", 0); - session->fetch(content_length, - [ this ]( const std::shared_ptr session, const restbed::Bytes & body ) - { - - const auto request = session->get_request(); - std::string file = restbed::String::format("%.*s\n", ( int ) body.size( ), body.data( )); - {{/hasBodyParam}} - - {{#hasPathParams}} - // Getting the path params - {{#pathParams}} - {{#isPrimitiveType}} - const {{{dataType}}} {{{paramName}}} = request->get_path_parameter("{{paramName}}", {{{defaultValue}}}); - {{/isPrimitiveType}} - {{/pathParams}} - {{/hasPathParams}} - - {{#hasQueryParams}} - // Getting the query params - {{#queryParams}} - {{#isPrimitiveType}} - const {{{dataType}}} {{{paramName}}} = request->get_query_parameter("{{paramName}}", {{{defaultValue}}}); - {{/isPrimitiveType}} - {{/queryParams}} - {{/hasQueryParams}} - - {{#hasHeaderParams}} - // Getting the headers - {{#headerParams}} - {{#isPrimitiveType}} - const {{{dataType}}} {{{paramName}}} = request->get_header("{{paramName}}", {{{defaultValue}}}); - {{/isPrimitiveType}} - {{/headerParams}} - {{/hasHeaderParams}} - - // Change the value of this variable to the appropriate response before sending the response - int status_code = 200; - std::string result = "successful operation"; - - if (handler_{{httpMethod}}_) - { - std::tie(status_code, result) = handler_{{httpMethod}}_( - {{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}} - ); - } - - {{#responses}} - if (status_code == {{code}}) { - {{#baseType}} - std::shared_ptr<{{.}}> response = NULL; - {{/baseType}} - {{#headers}} - // Description: {{description}} - session->set_header("{{baseName}}", ""); // Change second param to your header value - {{/headers}} - session->close({{code}}, result.empty() ? "{{message}}" : std::move(result), { {"Connection", "close"} }); - return; - } - {{/responses}} - - {{#hasBodyParam}} - }); - {{/hasBodyParam}} +{{#returnType}}std::pair{{/returnType}}{{^returnType}}int{{/returnType}} {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::handler_{{httpMethod}}( + {{#allParams}}{{{dataType}}} const & {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) +{ + throw {{classname}}Exception(501, "Not implemented"); } {{/vendorExtensions.x-codegen-other-methods}} - +std::string {{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} {{/operation}} +{{classname}}::{{classname}}(std::shared_ptr const& restbedService) +: m_service(restbedService) +{ +} + +{{classname}}::~{{classname}}() {} + +{{#operation}} +void {{classname}}::set{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(std::shared_ptr<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource> sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource) { + m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource = sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource; + m_service->publish(m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource); +} +{{/operation}} + + +void {{classname}}::publishDefaultResources() { + {{#operation}} + if (!m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource) { + set{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(std::make_shared<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource>()); + } + {{/operation}} +} + +std::shared_ptr {{classname}}::service() { + return m_service; +} + + {{#apiNamespaceDeclarations}} } {{/apiNamespaceDeclarations}} diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server/model-header.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server/model-header.mustache index 805b0664ab2..2568ccb6766 100644 --- a/modules/openapi-generator/src/main/resources/cpp-restbed-server/model-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server/model-header.mustache @@ -13,6 +13,10 @@ {{#imports}}{{{this}}} {{/imports}} #include +#include +{{#hasEnums}} +#include +{{/hasEnums}} #include {{#modelNamespaceDeclarations}} @@ -28,8 +32,9 @@ class {{{this}}}; class {{declspec}} {{classname}} {{#interfaces}}{{#-first}}:{{/-first}}{{^-first}},{{/-first}} public {{{this}}}{{/interfaces}} { public: - {{classname}}(); - virtual ~{{classname}}(); + {{classname}}() = default; + explicit {{classname}}(boost::property_tree::ptree const& pt); + virtual ~{{classname}}() = default; std::string toJsonString(bool prettyJson = false); void fromJsonString(std::string const& jsonString); @@ -46,17 +51,44 @@ public: {{{dataType}}} {{getter}}() const; void {{setter}}({{{dataType}}} value); {{/vars}} + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string toJsonString_internal(bool prettyJson = false); + virtual void fromJsonString_internal(std::string const& jsonString); + virtual boost::property_tree::ptree toPropertyTree_internal(); + virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); + + protected: {{#vars}} + {{^isContainer}} + {{^isModel}} + {{{dataType}}} m_{{name}} = {{{defaultValue}}}; + {{/isModel}} + {{#isModel}} {{{dataType}}} m_{{name}}; + {{/isModel}} + {{/isContainer}} + {{#isContainer}} + {{{dataType}}} m_{{name}}; + {{/isContainer}} {{/vars}} {{#vars}} {{#isEnum}} - std::vector<{{{dataType}}}> m_{{enumName}}; + const std::array m_{{enumName}} = { + {{#allowableValues}}{{#enumVars}}"{{{value}}}"{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} + }; + {{/isEnum}} {{/vars}} }; +std::vector<{{classname}}> create{{classname}}VectorFromJsonString(const std::string& json); + {{#modelNamespaceDeclarations}} } {{/modelNamespaceDeclarations}} diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server/model-source.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server/model-source.mustache index 9d56632b7fb..395e415c6b4 100644 --- a/modules/openapi-generator/src/main/resources/cpp-restbed-server/model-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server/model-source.mustache @@ -4,6 +4,7 @@ #include "{{classname}}.h" #include +#include #include #include {{#hasEnums}} @@ -20,43 +21,39 @@ using boost::property_tree::write_json; namespace {{this}} { {{/modelNamespaceDeclarations}} -{{classname}}::{{classname}}() +{{classname}}::{{classname}}(boost::property_tree::ptree const& pt) { - {{#vars}} - {{^isContainer}} - {{#isPrimitiveType}} - m_{{name}} = {{{defaultValue}}}; - {{/isPrimitiveType}} - {{^isPrimitiveType}} - {{#isString}} - m_{{name}} = {{{defaultValue}}}; - {{/isString}} - {{#isDate}} - m_{{name}} = {{{defaultValue}}}; - {{/isDate}} - {{#isDateTime}} - m_{{name}} = {{{defaultValue}}}; - {{/isDateTime}} - {{#isEnum}} - m_{{enumName}} = { {{#allowableValues}}{{#enumVars}}{{^-first}}, {{/-first}}{{{value}}}{{/enumVars}}{{/allowableValues}} }; - {{/isEnum}} - {{/isPrimitiveType}} - {{/isContainer}} - {{/vars}} + fromPropertyTree(pt); } -{{classname}}::~{{classname}}() +std::string {{classname}}::toJsonString(bool prettyJson /* = false */) { + return toJsonString_internal(prettyJson); } -std::string {{classname}}::toJsonString(bool prettyJson) +void {{classname}}::fromJsonString(std::string const& jsonString) +{ + fromJsonString_internal(jsonString); +} + +boost::property_tree::ptree {{classname}}::toPropertyTree() +{ + return toPropertyTree_internal(); +} + +void {{classname}}::fromPropertyTree(boost::property_tree::ptree const& pt) +{ + fromPropertyTree_internal(pt); +} + +std::string {{classname}}::toJsonString_internal(bool prettyJson) { std::stringstream ss; write_json(ss, this->toPropertyTree(), prettyJson); return ss.str(); } -void {{classname}}::fromJsonString(std::string const& jsonString) +void {{classname}}::fromJsonString_internal(std::string const& jsonString) { std::stringstream ss(jsonString); ptree pt; @@ -64,7 +61,7 @@ void {{classname}}::fromJsonString(std::string const& jsonString) this->fromPropertyTree(pt); } -ptree {{classname}}::toPropertyTree() +ptree {{classname}}::toPropertyTree_internal() { ptree pt; ptree tmp_node; @@ -91,34 +88,29 @@ ptree {{classname}}::toPropertyTree() {{/isPrimitiveType}} {{/isContainer}} {{#isContainer}} - {{^isModelContainer}} // generate tree for {{name}} if (!m_{{name}}.empty()) { for (const auto &childEntry : m_{{name}}) { - ptree {{name}}_node; - {{name}}_node.put("", childEntry); - tmp_node.push_back(std::make_pair("", {{name}}_node)); + {{#items}} + {{#isModel}} + tmp_node.push_back(std::make_pair("", childEntry->toPropertyTree())); + {{/isModel}} + {{^isModel}} + ptree {{name}}_node; + {{name}}_node.put("", childEntry); + tmp_node.push_back(std::make_pair("", {{name}}_node)); + {{/isModel}} + {{/items}} } pt.add_child("{{baseName}}", tmp_node); tmp_node.clear(); } - {{/isModelContainer}} - {{#isModelContainer}} - // generate tree for vector of pointers of {{name}} - if (!m_{{name}}.empty()) { - for (const auto &childEntry : m_{{name}}) { - tmp_node.push_back(std::make_pair("", childEntry->toPropertyTree())); - } - pt.add_child("{{baseName}}", tmp_node); - tmp_node.clear(); - } - {{/isModelContainer}} {{/isContainer}} {{/vars}} return pt; } -void {{classname}}::fromPropertyTree(ptree const &pt) +void {{classname}}::fromPropertyTree_internal(ptree const &pt) { ptree tmp_node; {{#vars}} @@ -154,9 +146,37 @@ void {{classname}}::fromPropertyTree(ptree const &pt) // push all items of {{name}} into member vector if (pt.get_child_optional("{{baseName}}")) { for (const auto &childTree : pt.get_child("{{baseName}}")) { - {{#mostInnerItems}} - m_{{name}}.emplace_back({{#isNumeric}}{{^isFloat}}{{^isLong}}{{^isInteger}}std::stod{{/isInteger}}{{/isLong}}{{/isFloat}}{{#isDouble}}std::stod{{/isDouble}}{{#isFloat}}std::stof{{/isFloat}}{{#isInteger}}std::stoi{{/isInteger}}{{#isLong}}std::stol{{/isLong}}({{/isNumeric}}childTree.second.data()){{#isNumeric}}){{/isNumeric}}; - {{/mostInnerItems}} + {{#mostInnerItems}} + {{{dataType}}} val = + {{#isNumeric}} + {{^isFloat}} + {{^isLong}} + {{^isInteger}} + std::stod(childTree.second.data()); + {{/isInteger}} + {{/isLong}} + {{/isFloat}} + {{#isDouble}} + std::stod(childTree.second.data()); + {{/isDouble}} + {{#isFloat}} + std::stof(childTree.second.data()); + {{/isFloat}} + {{#isInteger}} + std::stoi(childTree.second.data()); + {{/isInteger}} + {{#isLong}} + std::stol(childTree.second.data()); + {{/isLong}} + {{/isNumeric}} + {{#isString}} + childTree.second.data(); + {{/isString}} + {{#isModel}} + std::make_shared<{{baseType}}>(childTree.second); + {{/isModel}} + m_{{name}}.emplace_back(std::move(val)); + {{/mostInnerItems}} } } {{/isModelContainer}} @@ -180,6 +200,7 @@ void {{classname}}::fromPropertyTree(ptree const &pt) { return m_{{name}}; } + void {{classname}}::{{setter}}({{{dataType}}} value) { {{#isEnum}}if (std::find(m_{{enumName}}.begin(), m_{{enumName}}.end(), value) != m_{{enumName}}.end()) { @@ -190,6 +211,20 @@ void {{classname}}::{{setter}}({{{dataType}}} value) } {{/vars}} +std::vector<{{classname}}> create{{classname}}VectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector<{{{classname}}}>(); + for (const auto& child: pt) { + vec.emplace_back({{{classname}}}(child.second)); + } + + return vec; +} + {{#modelNamespaceDeclarations}} } {{/modelNamespaceDeclarations}} diff --git a/samples/server/petstore/cpp-restbed/.openapi-generator/VERSION b/samples/server/petstore/cpp-restbed/.openapi-generator/VERSION index d99e7162d01..717311e32e3 100644 --- a/samples/server/petstore/cpp-restbed/.openapi-generator/VERSION +++ b/samples/server/petstore/cpp-restbed/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +unset \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/api/PetApi.cpp b/samples/server/petstore/cpp-restbed/api/PetApi.cpp index 1700f2fd44b..65b08975bea 100644 --- a/samples/server/petstore/cpp-restbed/api/PetApi.cpp +++ b/samples/server/petstore/cpp-restbed/api/PetApi.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 5.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator unset. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -15,6 +15,11 @@ #include #include #include +#include +#include +#include +#include +#include #include "PetApi.h" @@ -25,51 +30,71 @@ namespace api { using namespace org::openapitools::server::model; -PetApi::PetApi() { -} - -PetApi::~PetApi() {} - -void PetApi::startService(int const& port) { - // A typical pattern is to derive a class from PetApi and allocate the shared pointers for restbed::Resource objects - // and manipulate them (e.g. binding GET/POST handler functions) before this startService() gets called. - // In such a case we want to use our m_spXXX variables. - // However in case these shared pointers are nullptr, then allocate the restbed::Resources now: - if (!m_spPetApiPetResource) - m_spPetApiPetResource = std::make_shared(); - this->publish(m_spPetApiPetResource); - if (!m_spPetApiPetPetIdResource) - m_spPetApiPetPetIdResource = std::make_shared(); - this->publish(m_spPetApiPetPetIdResource); - if (!m_spPetApiPetFindByStatusResource) - m_spPetApiPetFindByStatusResource = std::make_shared(); - this->publish(m_spPetApiPetFindByStatusResource); - if (!m_spPetApiPetFindByTagsResource) - m_spPetApiPetFindByTagsResource = std::make_shared(); - this->publish(m_spPetApiPetFindByTagsResource); - if (!m_spPetApiPetPetIdUploadImageResource) - m_spPetApiPetPetIdUploadImageResource = std::make_shared(); - this->publish(m_spPetApiPetPetIdUploadImageResource); - - std::shared_ptr settings = std::make_shared(); - settings->set_port(port); - settings->set_root("/v2"); - - this->start(settings); -} - -void PetApi::stopService() { - this->stop(); -} - -PetApiPetResource::PetApiPetResource() +PetApiException::PetApiException(int status_code, std::string what) + : m_status(status_code), + m_what(what) { - this->set_path("/pet/"); + +} +int PetApiException::getStatus() const +{ + return m_status; +} +const char* PetApiException::what() const noexcept +{ + return m_what.c_str(); +} + + +template +std::shared_ptr extractJsonModelBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto model = std::make_shared(pt); + return model; +} + +template +std::vector> extractJsonArrayBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto arrayRet = std::vector>(); + for (const auto& child: pt) { + arrayRet.emplace_back(std::make_shared(child.second)); + } + return arrayRet; +} + +template +std::string convertMapResponse(const std::map& map) +{ + boost::property_tree::ptree pt; + for(const auto &kv: map) { + pt.push_back(boost::property_tree::ptree::value_type( + boost::lexical_cast(kv.first), + boost::property_tree::ptree( + boost::lexical_cast(kv.second)))); + } + std::stringstream sstream; + write_json(sstream, pt); + std::string result = sstream.str(); + return result; +} + +PetApiPetResource::PetApiPetResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/pet/"); this->set_method_handler("POST", - std::bind(&PetApiPetResource::POST_method_handler, this, + std::bind(&PetApiPetResource::handler_POST_internal, this, std::placeholders::_1)); this->set_method_handler("PUT", - std::bind(&PetApiPetResource::PUT_method_handler, this, + std::bind(&PetApiPetResource::handler_PUT_internal, this, std::placeholders::_1)); } @@ -77,108 +102,156 @@ PetApiPetResource::~PetApiPetResource() { } -void PetApiPetResource::set_handler_POST( - std::function( - std::shared_ptr const & - )> handler) { - handler_POST_ = std::move(handler); -} - -void PetApiPetResource::set_handler_PUT( - std::function( - std::shared_ptr const & - )> handler) { - handler_PUT_ = std::move(handler); -} - -void PetApiPetResource::POST_method_handler(const std::shared_ptr session) { - - const auto request = session->get_request(); - // Body params are present, therefore we have to fetch them - int content_length = request->get_header("Content-Length", 0); - session->fetch(content_length, - [ this ]( const std::shared_ptr session, const restbed::Bytes & body ) - { - - const auto request = session->get_request(); - std::string file = restbed::String::format("%.*s\n", ( int ) body.size( ), body.data( )); - /** - * Get body params or form params here from the file string - */ - - - - - // Change the value of this variable to the appropriate response before sending the response - int status_code = 200; - std::string result = "successful operation"; - - if (handler_POST_) - { - std::tie(status_code, result) = handler_POST_( - body - ); - } - - if (status_code == 405) { - session->close(405, result.empty() ? "Invalid input" : std::move(result), { {"Connection", "close"} }); - return; - } - - }); -} - -void PetApiPetResource::PUT_method_handler(const std::shared_ptr session) { - - const auto request = session->get_request(); - // Body params are present, therefore we have to fetch them - int content_length = request->get_header("Content-Length", 0); - session->fetch(content_length, - [ this ]( const std::shared_ptr session, const restbed::Bytes & body ) - { - - const auto request = session->get_request(); - std::string file = restbed::String::format("%.*s\n", ( int ) body.size( ), body.data( )); - - - - - // Change the value of this variable to the appropriate response before sending the response - int status_code = 200; - std::string result = "successful operation"; - - if (handler_PUT_) - { - std::tie(status_code, result) = handler_PUT_( - body - ); - } - - if (status_code == 400) { - session->close(400, result.empty() ? "Invalid ID supplied" : std::move(result), { {"Connection", "close"} }); - return; - } - if (status_code == 404) { - session->close(404, result.empty() ? "Pet not found" : std::move(result), { {"Connection", "close"} }); - return; - } - if (status_code == 405) { - session->close(405, result.empty() ? "Validation exception" : std::move(result), { {"Connection", "close"} }); - return; - } - - }); -} - - -PetApiPetPetIdResource::PetApiPetPetIdResource() +std::pair PetApiPetResource::handlePetApiException(const PetApiException& e) { - this->set_path("/pet/{petId: .*}/"); + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair PetApiPetResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair PetApiPetResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void PetApiPetResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void PetApiPetResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void PetApiPetResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void PetApiPetResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + std::string bodyContent = extractBodyContent(session); + + // Get body params or form params here from the body content string + auto body = extractJsonModelBodyParam(bodyContent); + + + + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_POST(body); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 405) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 405, result.empty() ? "Invalid input" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + +// x-extension +void PetApiPetResource::handler_PUT_internal(const std::shared_ptr session) { + + const auto request = session->get_request(); + std::string bodyContent = extractBodyContent(session); + + // body params or form params here from the body content string + auto body = extractJsonModelBodyParam(bodyContent); + + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_PUT(body); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid ID supplied" : result, contentType); + return; + } + if (status_code == 404) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 404, result.empty() ? "Pet not found" : result, contentType); + return; + } + if (status_code == 405) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 405, result.empty() ? "Validation exception" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + +int PetApiPetResource::handler_POST( + std::shared_ptr const & body) +{ + throw PetApiException(501, "Not implemented"); +} + +int PetApiPetResource::handler_PUT( + std::shared_ptr const & body) +{ + throw PetApiException(501, "Not implemented"); +} + +std::string PetApiPetResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +PetApiPetPetIdResource::PetApiPetPetIdResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/pet/{petId: .*}/"); this->set_method_handler("DELETE", - std::bind(&PetApiPetPetIdResource::DELETE_method_handler, this, + std::bind(&PetApiPetPetIdResource::handler_DELETE_internal, this, + std::placeholders::_1)); + this->set_method_handler("GET", + std::bind(&PetApiPetPetIdResource::handler_GET_internal, this, std::placeholders::_1)); this->set_method_handler("POST", - std::bind(&PetApiPetPetIdResource::POST_method_handler, this, + std::bind(&PetApiPetPetIdResource::handler_POST_internal, this, std::placeholders::_1)); } @@ -186,82 +259,190 @@ PetApiPetPetIdResource::~PetApiPetPetIdResource() { } -void PetApiPetPetIdResource::set_handler_DELETE( - std::function( - int64_t const &, std::string const & - )> handler) { - handler_DELETE_ = std::move(handler); -} - -void PetApiPetPetIdResource::set_handler_POST( - std::function( - int64_t const &, std::string const &, std::string const & - )> handler) { - handler_POST_ = std::move(handler); -} - -void PetApiPetPetIdResource::DELETE_method_handler(const std::shared_ptr session) { - - const auto request = session->get_request(); - - // Getting the path params - const int64_t petId = request->get_path_parameter("petId", 0L); - - - // Getting the headers - const std::string apiKey = request->get_header("apiKey", ""); - - // Change the value of this variable to the appropriate response before sending the response - int status_code = 200; - std::string result = "successful operation"; - - if (handler_DELETE_) - { - std::tie(status_code, result) = handler_DELETE_( - petId, apiKey - ); - } - - if (status_code == 400) { - session->close(400, result.empty() ? "Invalid pet value" : std::move(result), { {"Connection", "close"} }); - return; - } - -} - -void PetApiPetPetIdResource::POST_method_handler(const std::shared_ptr session) { - - const auto request = session->get_request(); - - // Getting the path params - const int64_t petId = request->get_path_parameter("petId", 0L); - - - - // Change the value of this variable to the appropriate response before sending the response - int status_code = 200; - std::string result = "successful operation"; - - if (handler_POST_) - { - std::tie(status_code, result) = handler_POST_( - petId, name, status - ); - } - - if (status_code == 405) { - session->close(405, result.empty() ? "Invalid input" : std::move(result), { {"Connection", "close"} }); - return; - } - -} - - -PetApiPetFindByStatusResource::PetApiPetFindByStatusResource() +std::pair PetApiPetPetIdResource::handlePetApiException(const PetApiException& e) { - this->set_path("/pet/findByStatus/"); + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair PetApiPetPetIdResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair PetApiPetPetIdResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void PetApiPetPetIdResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void PetApiPetPetIdResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void PetApiPetPetIdResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void PetApiPetPetIdResource::handler_DELETE_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + // Getting the path params + const int64_t petId = getPathParam_petId(request); + + + // Getting the headers + const std::string apiKey = getHeader_api_key(request); + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_DELETE(petId, apiKey); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid pet value" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + +// x-extension +void PetApiPetPetIdResource::handler_GET_internal(const std::shared_ptr session) { + + const auto request = session->get_request(); + + // Getting the path params + const int64_t petId = getPathParam_petId_x_extension(request); + + + int status_code = 500; + std::shared_ptr resultObject = std::make_shared(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(petId); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 200) { + result = resultObject->toJsonString(); + + const constexpr auto contentType = "application/json"; + returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); + return; + } + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid ID supplied" : result, contentType); + return; + } + if (status_code == 404) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 404, result.empty() ? "Pet not found" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} +// x-extension +void PetApiPetPetIdResource::handler_POST_internal(const std::shared_ptr session) { + + const auto request = session->get_request(); + + // Getting the path params + const int64_t petId = getPathParam_petId_x_extension(request); + + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_POST(petId, name, status); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 405) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 405, result.empty() ? "Invalid input" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + +int PetApiPetPetIdResource::handler_DELETE( + int64_t const & petId, std::string const & apiKey) +{ + throw PetApiException(501, "Not implemented"); +} + +std::pair> PetApiPetPetIdResource::handler_GET( + int64_t const & petId) +{ + throw PetApiException(501, "Not implemented"); +} +int PetApiPetPetIdResource::handler_POST( + int64_t const & petId, std::string const & name, std::string const & status) +{ + throw PetApiException(501, "Not implemented"); +} + +std::string PetApiPetPetIdResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +PetApiPetFindByStatusResource::PetApiPetFindByStatusResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/pet/findByStatus/"); this->set_method_handler("GET", - std::bind(&PetApiPetFindByStatusResource::GET_method_handler, this, + std::bind(&PetApiPetFindByStatusResource::handler_GET_internal, this, std::placeholders::_1)); } @@ -269,51 +450,102 @@ PetApiPetFindByStatusResource::~PetApiPetFindByStatusResource() { } -void PetApiPetFindByStatusResource::set_handler_GET( - std::function( - std::vector const & - )> handler) { - handler_GET_ = std::move(handler); -} - - -void PetApiPetFindByStatusResource::GET_method_handler(const std::shared_ptr session) { - - const auto request = session->get_request(); - - - // Getting the query params - - - // Change the value of this variable to the appropriate response before sending the response - int status_code = 200; - std::string result = "successful operation"; - - if (handler_GET_) - { - std::tie(status_code, result) = handler_GET_( - status - ); - } - - if (status_code == 200) { - session->close(200, result.empty() ? "successful operation" : std::move(result), { {"Connection", "close"} }); - return; - } - if (status_code == 400) { - session->close(400, result.empty() ? "Invalid status value" : std::move(result), { {"Connection", "close"} }); - return; - } - -} - - - -PetApiPetFindByTagsResource::PetApiPetFindByTagsResource() +std::pair PetApiPetFindByStatusResource::handlePetApiException(const PetApiException& e) { - this->set_path("/pet/findByTags/"); + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair PetApiPetFindByStatusResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair PetApiPetFindByStatusResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void PetApiPetFindByStatusResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void PetApiPetFindByStatusResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void PetApiPetFindByStatusResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void PetApiPetFindByStatusResource::handler_GET_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + + // Getting the query params + + + int status_code = 500; + std::vector> resultObject = std::vector>(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(status); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 200) { + + const constexpr auto contentType = "application/json"; + returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); + return; + } + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid status value" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair>> PetApiPetFindByStatusResource::handler_GET( + std::vector const & status) +{ + throw PetApiException(501, "Not implemented"); +} + + +std::string PetApiPetFindByStatusResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +PetApiPetFindByTagsResource::PetApiPetFindByTagsResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/pet/findByTags/"); this->set_method_handler("GET", - std::bind(&PetApiPetFindByTagsResource::GET_method_handler, this, + std::bind(&PetApiPetFindByTagsResource::handler_GET_internal, this, std::placeholders::_1)); } @@ -321,51 +553,102 @@ PetApiPetFindByTagsResource::~PetApiPetFindByTagsResource() { } -void PetApiPetFindByTagsResource::set_handler_GET( - std::function( - std::vector const & - )> handler) { - handler_GET_ = std::move(handler); -} - - -void PetApiPetFindByTagsResource::GET_method_handler(const std::shared_ptr session) { - - const auto request = session->get_request(); - - - // Getting the query params - - - // Change the value of this variable to the appropriate response before sending the response - int status_code = 200; - std::string result = "successful operation"; - - if (handler_GET_) - { - std::tie(status_code, result) = handler_GET_( - tags - ); - } - - if (status_code == 200) { - session->close(200, result.empty() ? "successful operation" : std::move(result), { {"Connection", "close"} }); - return; - } - if (status_code == 400) { - session->close(400, result.empty() ? "Invalid tag value" : std::move(result), { {"Connection", "close"} }); - return; - } - -} - - - -PetApiPetPetIdUploadImageResource::PetApiPetPetIdUploadImageResource() +std::pair PetApiPetFindByTagsResource::handlePetApiException(const PetApiException& e) { - this->set_path("/pet/{petId: .*}/uploadImage/"); + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair PetApiPetFindByTagsResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair PetApiPetFindByTagsResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void PetApiPetFindByTagsResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void PetApiPetFindByTagsResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void PetApiPetFindByTagsResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void PetApiPetFindByTagsResource::handler_GET_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + + // Getting the query params + + + int status_code = 500; + std::vector> resultObject = std::vector>(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(tags); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 200) { + + const constexpr auto contentType = "application/json"; + returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); + return; + } + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid tag value" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair>> PetApiPetFindByTagsResource::handler_GET( + std::vector const & tags) +{ + throw PetApiException(501, "Not implemented"); +} + + +std::string PetApiPetFindByTagsResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +PetApiPetPetIdUploadImageResource::PetApiPetPetIdUploadImageResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/pet/{petId: .*}/uploadImage/"); this->set_method_handler("POST", - std::bind(&PetApiPetPetIdUploadImageResource::POST_method_handler, this, + std::bind(&PetApiPetPetIdUploadImageResource::handler_POST_internal, this, std::placeholders::_1)); } @@ -373,42 +656,144 @@ PetApiPetPetIdUploadImageResource::~PetApiPetPetIdUploadImageResource() { } -void PetApiPetPetIdUploadImageResource::set_handler_POST( - std::function( - int64_t const &, std::string const &, std::string const & - )> handler) { - handler_POST_ = std::move(handler); +std::pair PetApiPetPetIdUploadImageResource::handlePetApiException(const PetApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair PetApiPetPetIdUploadImageResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair PetApiPetPetIdUploadImageResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void PetApiPetPetIdUploadImageResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void PetApiPetPetIdUploadImageResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void PetApiPetPetIdUploadImageResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void PetApiPetPetIdUploadImageResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + // Getting the path params + const int64_t petId = getPathParam_petId(request); + + + + int status_code = 500; + std::shared_ptr resultObject = std::make_shared(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_POST(petId, additionalMetadata, file); + } + catch(const PetApiException& e) { + std::tie(status_code, result) = handlePetApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 200) { + result = resultObject->toJsonString(); + + const constexpr auto contentType = "application/json"; + returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); } -void PetApiPetPetIdUploadImageResource::POST_method_handler(const std::shared_ptr session) { - - const auto request = session->get_request(); - - // Getting the path params - const int64_t petId = request->get_path_parameter("petId", 0L); - - - - // Change the value of this variable to the appropriate response before sending the response - int status_code = 200; - std::string result = "successful operation"; - - if (handler_POST_) - { - std::tie(status_code, result) = handler_POST_( - petId, additionalMetadata, file - ); - } - - if (status_code == 200) { - session->close(200, result.empty() ? "successful operation" : std::move(result), { {"Connection", "close"} }); - return; - } - +std::pair> PetApiPetPetIdUploadImageResource::handler_POST( + int64_t const & petId, std::string const & additionalMetadata, std::string const & file) +{ + throw PetApiException(501, "Not implemented"); } +std::string PetApiPetPetIdUploadImageResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +PetApi::PetApi(std::shared_ptr const& restbedService) +: m_service(restbedService) +{ +} + +PetApi::~PetApi() {} + +void PetApi::setPetApiPetResource(std::shared_ptr spPetApiPetResource) { + m_spPetApiPetResource = spPetApiPetResource; + m_service->publish(m_spPetApiPetResource); +} +void PetApi::setPetApiPetPetIdResource(std::shared_ptr spPetApiPetPetIdResource) { + m_spPetApiPetPetIdResource = spPetApiPetPetIdResource; + m_service->publish(m_spPetApiPetPetIdResource); +} +void PetApi::setPetApiPetFindByStatusResource(std::shared_ptr spPetApiPetFindByStatusResource) { + m_spPetApiPetFindByStatusResource = spPetApiPetFindByStatusResource; + m_service->publish(m_spPetApiPetFindByStatusResource); +} +void PetApi::setPetApiPetFindByTagsResource(std::shared_ptr spPetApiPetFindByTagsResource) { + m_spPetApiPetFindByTagsResource = spPetApiPetFindByTagsResource; + m_service->publish(m_spPetApiPetFindByTagsResource); +} +void PetApi::setPetApiPetPetIdUploadImageResource(std::shared_ptr spPetApiPetPetIdUploadImageResource) { + m_spPetApiPetPetIdUploadImageResource = spPetApiPetPetIdUploadImageResource; + m_service->publish(m_spPetApiPetPetIdUploadImageResource); +} + + +void PetApi::publishDefaultResources() { + if (!m_spPetApiPetResource) { + setPetApiPetResource(std::make_shared()); + } + if (!m_spPetApiPetPetIdResource) { + setPetApiPetPetIdResource(std::make_shared()); + } + if (!m_spPetApiPetFindByStatusResource) { + setPetApiPetFindByStatusResource(std::make_shared()); + } + if (!m_spPetApiPetFindByTagsResource) { + setPetApiPetFindByTagsResource(std::make_shared()); + } + if (!m_spPetApiPetPetIdUploadImageResource) { + setPetApiPetPetIdUploadImageResource(std::make_shared()); + } +} + +std::shared_ptr PetApi::service() { + return m_service; +} } diff --git a/samples/server/petstore/cpp-restbed/api/PetApi.h b/samples/server/petstore/cpp-restbed/api/PetApi.h index 2512275920d..09a6770a953 100644 --- a/samples/server/petstore/cpp-restbed/api/PetApi.h +++ b/samples/server/petstore/cpp-restbed/api/PetApi.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 5.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator unset. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -22,10 +22,13 @@ #include #include +#include #include #include +#include #include +#include #include "ApiResponse.h" #include "Pet.h" @@ -38,6 +41,22 @@ namespace api { using namespace org::openapitools::server::model; +/// +/// Exception to flag problems in the handlers +/// +class PetApiException: public std::exception +{ +public: + PetApiException(int status_code, std::string what); + + int getStatus() const; + const char* what() const noexcept override; + +private: + int m_status; + std::string m_what; +}; + /// /// Add a new pet to the store /// @@ -47,35 +66,48 @@ using namespace org::openapitools::server::model; class PetApiPetResource: public restbed::Resource { public: - PetApiPetResource(); + PetApiPetResource(const std::string& context = "/v2"); virtual ~PetApiPetResource(); - void POST_method_handler(const std::shared_ptr session); - void PUT_method_handler(const std::shared_ptr session); - void set_handler_POST( - std::function( - std::shared_ptr const & - )> handler - ); +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// - void set_handler_PUT( - std::function( - std::shared_ptr const & - )> handler - ); + virtual int handler_POST( + std::shared_ptr const & body); + + virtual int handler_PUT( + std::shared_ptr const & body); + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + + + virtual std::pair handlePetApiException(const PetApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); private: - std::function( - std::shared_ptr const & - )> handler_POST_; - - std::function( - std::shared_ptr const & - )> handler_PUT_; - - std::shared_ptr body{}; + void handler_POST_internal(const std::shared_ptr session); + void handler_PUT_internal(const std::shared_ptr session); }; + /// /// Deletes a pet /// @@ -85,36 +117,69 @@ private: class PetApiPetPetIdResource: public restbed::Resource { public: - PetApiPetPetIdResource(); + PetApiPetPetIdResource(const std::string& context = "/v2"); virtual ~PetApiPetPetIdResource(); - void DELETE_method_handler(const std::shared_ptr session); - void POST_method_handler(const std::shared_ptr session); - void set_handler_DELETE( - std::function( - int64_t const &, std::string const & - )> handler - ); +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// - void set_handler_POST( - std::function( - int64_t const &, std::string const &, std::string const & - )> handler - ); + virtual int handler_DELETE( + int64_t const & petId, std::string const & apiKey); + + virtual std::pair> handler_GET( + int64_t const & petId); + virtual int handler_POST( + int64_t const & petId, std::string const & name, std::string const & status); + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + virtual int64_t getPathParam_petId(const std::shared_ptr& request) + { + return request->get_path_parameter("petId", 0L); + } + + virtual std::string getHeader_api_key(const std::shared_ptr& request) + { + return request->get_header("api_key", ""); + } + + + virtual int64_t getPathParam_petId_x_extension(const std::shared_ptr& request) + { + return request->get_path_parameter("petId", 0L); + } + virtual int64_t getPathParam_petId_x_extension(const std::shared_ptr& request) + { + return request->get_path_parameter("petId", 0L); + } + + virtual std::pair handlePetApiException(const PetApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); private: - std::function( - int64_t const &, std::string const & - )> handler_DELETE_; - - std::function( - int64_t const &, std::string const &, std::string const & - )> handler_POST_; - - int64_t petId{}; - std::string apiKey{}; + void handler_DELETE_internal(const std::shared_ptr session); + void handler_GET_internal(const std::shared_ptr session); + void handler_POST_internal(const std::shared_ptr session); }; + /// /// Finds Pets by status /// @@ -124,26 +189,45 @@ private: class PetApiPetFindByStatusResource: public restbed::Resource { public: - PetApiPetFindByStatusResource(); + PetApiPetFindByStatusResource(const std::string& context = "/v2"); virtual ~PetApiPetFindByStatusResource(); - void GET_method_handler(const std::shared_ptr session); - void set_handler_GET( - std::function( - std::vector const & - )> handler - ); +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + virtual std::pair>> handler_GET( + std::vector const & status); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + + + virtual std::pair handlePetApiException(const PetApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); private: - std::function( - std::vector const & - )> handler_GET_; - - - std::vector status{}; + void handler_GET_internal(const std::shared_ptr session); }; + /// /// Finds Pets by tags /// @@ -153,26 +237,45 @@ private: class PetApiPetFindByTagsResource: public restbed::Resource { public: - PetApiPetFindByTagsResource(); + PetApiPetFindByTagsResource(const std::string& context = "/v2"); virtual ~PetApiPetFindByTagsResource(); - void GET_method_handler(const std::shared_ptr session); - void set_handler_GET( - std::function( - std::vector const & - )> handler - ); +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + virtual std::pair>> handler_GET( + std::vector const & tags); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + + + virtual std::pair handlePetApiException(const PetApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); private: - std::function( - std::vector const & - )> handler_GET_; - - - std::vector tags{}; + void handler_GET_internal(const std::shared_ptr session); }; + /// /// uploads an image /// @@ -182,46 +285,79 @@ private: class PetApiPetPetIdUploadImageResource: public restbed::Resource { public: - PetApiPetPetIdUploadImageResource(); + PetApiPetPetIdUploadImageResource(const std::string& context = "/v2"); virtual ~PetApiPetPetIdUploadImageResource(); - void POST_method_handler(const std::shared_ptr session); - void set_handler_POST( - std::function( - int64_t const &, std::string const &, std::string const & - )> handler - ); +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + virtual std::pair> handler_POST( + int64_t const & petId, std::string const & additionalMetadata, std::string const & file); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + virtual int64_t getPathParam_petId(const std::shared_ptr& request) + { + return request->get_path_parameter("petId", 0L); + } + + + + virtual std::pair handlePetApiException(const PetApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); private: - std::function( - int64_t const &, std::string const &, std::string const & - )> handler_POST_; - - - int64_t petId{}; - std::string additionalMetadata{}; - std::string file{}; + void handler_POST_internal(const std::shared_ptr session); }; + // // The restbed service to actually implement the REST server // -class PetApi: public restbed::Service +class PetApi { public: - PetApi(); - ~PetApi(); - void startService(int const& port); - void stopService(); - + explicit PetApi(std::shared_ptr const& restbedService); + virtual ~PetApi(); + + virtual void setPetApiPetResource(std::shared_ptr spPetApiPetResource); + virtual void setPetApiPetPetIdResource(std::shared_ptr spPetApiPetPetIdResource); + virtual void setPetApiPetFindByStatusResource(std::shared_ptr spPetApiPetFindByStatusResource); + virtual void setPetApiPetFindByTagsResource(std::shared_ptr spPetApiPetFindByTagsResource); + virtual void setPetApiPetPetIdUploadImageResource(std::shared_ptr spPetApiPetPetIdUploadImageResource); + + virtual void publishDefaultResources(); + + virtual std::shared_ptr service(); + protected: std::shared_ptr m_spPetApiPetResource; std::shared_ptr m_spPetApiPetPetIdResource; std::shared_ptr m_spPetApiPetFindByStatusResource; std::shared_ptr m_spPetApiPetFindByTagsResource; std::shared_ptr m_spPetApiPetPetIdUploadImageResource; + +private: + std::shared_ptr m_service; }; diff --git a/samples/server/petstore/cpp-restbed/api/StoreApi.cpp b/samples/server/petstore/cpp-restbed/api/StoreApi.cpp index 3fb05fb7493..784232c6112 100644 --- a/samples/server/petstore/cpp-restbed/api/StoreApi.cpp +++ b/samples/server/petstore/cpp-restbed/api/StoreApi.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 5.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator unset. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -15,6 +15,11 @@ #include #include #include +#include +#include +#include +#include +#include #include "StoreApi.h" @@ -25,45 +30,71 @@ namespace api { using namespace org::openapitools::server::model; -StoreApi::StoreApi() { -} - -StoreApi::~StoreApi() {} - -void StoreApi::startService(int const& port) { - // A typical pattern is to derive a class from StoreApi and allocate the shared pointers for restbed::Resource objects - // and manipulate them (e.g. binding GET/POST handler functions) before this startService() gets called. - // In such a case we want to use our m_spXXX variables. - // However in case these shared pointers are nullptr, then allocate the restbed::Resources now: - if (!m_spStoreApiStoreOrderOrderIdResource) - m_spStoreApiStoreOrderOrderIdResource = std::make_shared(); - this->publish(m_spStoreApiStoreOrderOrderIdResource); - if (!m_spStoreApiStoreInventoryResource) - m_spStoreApiStoreInventoryResource = std::make_shared(); - this->publish(m_spStoreApiStoreInventoryResource); - if (!m_spStoreApiStoreOrderResource) - m_spStoreApiStoreOrderResource = std::make_shared(); - this->publish(m_spStoreApiStoreOrderResource); - - std::shared_ptr settings = std::make_shared(); - settings->set_port(port); - settings->set_root("/v2"); - - this->start(settings); -} - -void StoreApi::stopService() { - this->stop(); -} - -StoreApiStoreOrderOrderIdResource::StoreApiStoreOrderOrderIdResource() +StoreApiException::StoreApiException(int status_code, std::string what) + : m_status(status_code), + m_what(what) { - this->set_path("/store/order/{orderId: .*}/"); + +} +int StoreApiException::getStatus() const +{ + return m_status; +} +const char* StoreApiException::what() const noexcept +{ + return m_what.c_str(); +} + + +template +std::shared_ptr extractJsonModelBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto model = std::make_shared(pt); + return model; +} + +template +std::vector> extractJsonArrayBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto arrayRet = std::vector>(); + for (const auto& child: pt) { + arrayRet.emplace_back(std::make_shared(child.second)); + } + return arrayRet; +} + +template +std::string convertMapResponse(const std::map& map) +{ + boost::property_tree::ptree pt; + for(const auto &kv: map) { + pt.push_back(boost::property_tree::ptree::value_type( + boost::lexical_cast(kv.first), + boost::property_tree::ptree( + boost::lexical_cast(kv.second)))); + } + std::stringstream sstream; + write_json(sstream, pt); + std::string result = sstream.str(); + return result; +} + +StoreApiStoreOrderOrderIdResource::StoreApiStoreOrderOrderIdResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/store/order/{orderId: .*}/"); this->set_method_handler("DELETE", - std::bind(&StoreApiStoreOrderOrderIdResource::DELETE_method_handler, this, + std::bind(&StoreApiStoreOrderOrderIdResource::handler_DELETE_internal, this, std::placeholders::_1)); this->set_method_handler("GET", - std::bind(&StoreApiStoreOrderOrderIdResource::GET_method_handler, this, + std::bind(&StoreApiStoreOrderOrderIdResource::handler_GET_internal, this, std::placeholders::_1)); } @@ -71,93 +102,155 @@ StoreApiStoreOrderOrderIdResource::~StoreApiStoreOrderOrderIdResource() { } -void StoreApiStoreOrderOrderIdResource::set_handler_DELETE( - std::function( - std::string const & - )> handler) { - handler_DELETE_ = std::move(handler); -} - -void StoreApiStoreOrderOrderIdResource::set_handler_GET( - std::function( - int64_t const & - )> handler) { - handler_GET_ = std::move(handler); -} - -void StoreApiStoreOrderOrderIdResource::DELETE_method_handler(const std::shared_ptr session) { - - const auto request = session->get_request(); - - // Getting the path params - const std::string orderId = request->get_path_parameter("orderId", ""); - - - - // Change the value of this variable to the appropriate response before sending the response - int status_code = 200; - std::string result = "successful operation"; - - if (handler_DELETE_) - { - std::tie(status_code, result) = handler_DELETE_( - orderId - ); - } - - if (status_code == 400) { - session->close(400, result.empty() ? "Invalid ID supplied" : std::move(result), { {"Connection", "close"} }); - return; - } - if (status_code == 404) { - session->close(404, result.empty() ? "Order not found" : std::move(result), { {"Connection", "close"} }); - return; - } - -} - -void StoreApiStoreOrderOrderIdResource::GET_method_handler(const std::shared_ptr session) { - - const auto request = session->get_request(); - - // Getting the path params - const int64_t orderId = request->get_path_parameter("orderId", 0L); - - - - // Change the value of this variable to the appropriate response before sending the response - int status_code = 200; - std::string result = "successful operation"; - - if (handler_GET_) - { - std::tie(status_code, result) = handler_GET_( - orderId - ); - } - - if (status_code == 200) { - std::shared_ptr response = NULL; - session->close(200, result.empty() ? "successful operation" : std::move(result), { {"Connection", "close"} }); - return; - } - if (status_code == 400) { - session->close(400, result.empty() ? "Invalid ID supplied" : std::move(result), { {"Connection", "close"} }); - return; - } - if (status_code == 404) { - session->close(404, result.empty() ? "Order not found" : std::move(result), { {"Connection", "close"} }); - return; - } - -} - - -StoreApiStoreInventoryResource::StoreApiStoreInventoryResource() +std::pair StoreApiStoreOrderOrderIdResource::handleStoreApiException(const StoreApiException& e) { - this->set_path("/store/inventory/"); + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair StoreApiStoreOrderOrderIdResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair StoreApiStoreOrderOrderIdResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void StoreApiStoreOrderOrderIdResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void StoreApiStoreOrderOrderIdResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void StoreApiStoreOrderOrderIdResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void StoreApiStoreOrderOrderIdResource::handler_DELETE_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + // Getting the path params + const std::string orderId = getPathParam_orderId(request); + + + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_DELETE(orderId); + } + catch(const StoreApiException& e) { + std::tie(status_code, result) = handleStoreApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid ID supplied" : result, contentType); + return; + } + if (status_code == 404) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 404, result.empty() ? "Order not found" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + +// x-extension +void StoreApiStoreOrderOrderIdResource::handler_GET_internal(const std::shared_ptr session) { + + const auto request = session->get_request(); + + // Getting the path params + const int64_t orderId = getPathParam_orderId_x_extension(request); + + + int status_code = 500; + std::shared_ptr resultObject = std::make_shared(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(orderId); + } + catch(const StoreApiException& e) { + std::tie(status_code, result) = handleStoreApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 200) { + result = resultObject->toJsonString(); + + const constexpr auto contentType = "application/json"; + returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); + return; + } + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid ID supplied" : result, contentType); + return; + } + if (status_code == 404) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 404, result.empty() ? "Order not found" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + +int StoreApiStoreOrderOrderIdResource::handler_DELETE( + std::string const & orderId) +{ + throw StoreApiException(501, "Not implemented"); +} + +std::pair> StoreApiStoreOrderOrderIdResource::handler_GET( + int64_t const & orderId) +{ + throw StoreApiException(501, "Not implemented"); +} + +std::string StoreApiStoreOrderOrderIdResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +StoreApiStoreInventoryResource::StoreApiStoreInventoryResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/store/inventory/"); this->set_method_handler("GET", - std::bind(&StoreApiStoreInventoryResource::GET_method_handler, this, + std::bind(&StoreApiStoreInventoryResource::handler_GET_internal, this, std::placeholders::_1)); } @@ -165,46 +258,96 @@ StoreApiStoreInventoryResource::~StoreApiStoreInventoryResource() { } -void StoreApiStoreInventoryResource::set_handler_GET( - std::function( - - )> handler) { - handler_GET_ = std::move(handler); -} - - -void StoreApiStoreInventoryResource::GET_method_handler(const std::shared_ptr session) { - - const auto request = session->get_request(); - - - - - // Change the value of this variable to the appropriate response before sending the response - int status_code = 200; - std::string result = "successful operation"; - - if (handler_GET_) - { - std::tie(status_code, result) = handler_GET_( - - ); - } - - if (status_code == 200) { - session->close(200, result.empty() ? "successful operation" : std::move(result), { {"Connection", "close"} }); - return; - } - -} - - - -StoreApiStoreOrderResource::StoreApiStoreOrderResource() +std::pair StoreApiStoreInventoryResource::handleStoreApiException(const StoreApiException& e) { - this->set_path("/store/order/"); + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair StoreApiStoreInventoryResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair StoreApiStoreInventoryResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void StoreApiStoreInventoryResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void StoreApiStoreInventoryResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void StoreApiStoreInventoryResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void StoreApiStoreInventoryResource::handler_GET_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + + + + int status_code = 500; + std::map resultObject = std::map(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(); + } + catch(const StoreApiException& e) { + std::tie(status_code, result) = handleStoreApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 200) { + result = convertMapResponse(resultObject); + + const constexpr auto contentType = "application/json"; + returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair> StoreApiStoreInventoryResource::handler_GET( + ) +{ + throw StoreApiException(501, "Not implemented"); +} + + +std::string StoreApiStoreInventoryResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +StoreApiStoreOrderResource::StoreApiStoreOrderResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/store/order/"); this->set_method_handler("POST", - std::bind(&StoreApiStoreOrderResource::POST_method_handler, this, + std::bind(&StoreApiStoreOrderResource::handler_POST_internal, this, std::placeholders::_1)); } @@ -212,56 +355,138 @@ StoreApiStoreOrderResource::~StoreApiStoreOrderResource() { } -void StoreApiStoreOrderResource::set_handler_POST( - std::function( - std::shared_ptr const & - )> handler) { - handler_POST_ = std::move(handler); +std::pair StoreApiStoreOrderResource::handleStoreApiException(const StoreApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair StoreApiStoreOrderResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair StoreApiStoreOrderResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void StoreApiStoreOrderResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void StoreApiStoreOrderResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void StoreApiStoreOrderResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void StoreApiStoreOrderResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + std::string bodyContent = extractBodyContent(session); + + // Get body params or form params here from the body content string + auto body = extractJsonModelBodyParam(bodyContent); + + + + + int status_code = 500; + std::shared_ptr resultObject = std::make_shared(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_POST(body); + } + catch(const StoreApiException& e) { + std::tie(status_code, result) = handleStoreApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 200) { + result = resultObject->toJsonString(); + + const constexpr auto contentType = "application/json"; + returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); + return; + } + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid Order" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); } -void StoreApiStoreOrderResource::POST_method_handler(const std::shared_ptr session) { - - const auto request = session->get_request(); - // Body params are present, therefore we have to fetch them - int content_length = request->get_header("Content-Length", 0); - session->fetch(content_length, - [ this ]( const std::shared_ptr session, const restbed::Bytes & body ) - { - - const auto request = session->get_request(); - std::string file = restbed::String::format("%.*s\n", ( int ) body.size( ), body.data( )); - /** - * Get body params or form params here from the file string - */ - - - - - // Change the value of this variable to the appropriate response before sending the response - int status_code = 200; - std::string result = "successful operation"; - - if (handler_POST_) - { - std::tie(status_code, result) = handler_POST_( - body - ); - } - - if (status_code == 200) { - session->close(200, result.empty() ? "successful operation" : std::move(result), { {"Connection", "close"} }); - return; - } - if (status_code == 400) { - session->close(400, result.empty() ? "Invalid Order" : std::move(result), { {"Connection", "close"} }); - return; - } - - }); +std::pair> StoreApiStoreOrderResource::handler_POST( + std::shared_ptr const & body) +{ + throw StoreApiException(501, "Not implemented"); } +std::string StoreApiStoreOrderResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +StoreApi::StoreApi(std::shared_ptr const& restbedService) +: m_service(restbedService) +{ +} + +StoreApi::~StoreApi() {} + +void StoreApi::setStoreApiStoreOrderOrderIdResource(std::shared_ptr spStoreApiStoreOrderOrderIdResource) { + m_spStoreApiStoreOrderOrderIdResource = spStoreApiStoreOrderOrderIdResource; + m_service->publish(m_spStoreApiStoreOrderOrderIdResource); +} +void StoreApi::setStoreApiStoreInventoryResource(std::shared_ptr spStoreApiStoreInventoryResource) { + m_spStoreApiStoreInventoryResource = spStoreApiStoreInventoryResource; + m_service->publish(m_spStoreApiStoreInventoryResource); +} +void StoreApi::setStoreApiStoreOrderResource(std::shared_ptr spStoreApiStoreOrderResource) { + m_spStoreApiStoreOrderResource = spStoreApiStoreOrderResource; + m_service->publish(m_spStoreApiStoreOrderResource); +} + + +void StoreApi::publishDefaultResources() { + if (!m_spStoreApiStoreOrderOrderIdResource) { + setStoreApiStoreOrderOrderIdResource(std::make_shared()); + } + if (!m_spStoreApiStoreInventoryResource) { + setStoreApiStoreInventoryResource(std::make_shared()); + } + if (!m_spStoreApiStoreOrderResource) { + setStoreApiStoreOrderResource(std::make_shared()); + } +} + +std::shared_ptr StoreApi::service() { + return m_service; +} } diff --git a/samples/server/petstore/cpp-restbed/api/StoreApi.h b/samples/server/petstore/cpp-restbed/api/StoreApi.h index 7089e9f6bc2..3c14a48c7e9 100644 --- a/samples/server/petstore/cpp-restbed/api/StoreApi.h +++ b/samples/server/petstore/cpp-restbed/api/StoreApi.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 5.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator unset. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -22,10 +22,13 @@ #include #include +#include #include #include +#include #include +#include #include "Order.h" #include @@ -38,6 +41,22 @@ namespace api { using namespace org::openapitools::server::model; +/// +/// Exception to flag problems in the handlers +/// +class StoreApiException: public std::exception +{ +public: + StoreApiException(int status_code, std::string what); + + int getStatus() const; + const char* what() const noexcept override; + +private: + int m_status; + std::string m_what; +}; + /// /// Delete purchase order by ID /// @@ -47,35 +66,57 @@ using namespace org::openapitools::server::model; class StoreApiStoreOrderOrderIdResource: public restbed::Resource { public: - StoreApiStoreOrderOrderIdResource(); + StoreApiStoreOrderOrderIdResource(const std::string& context = "/v2"); virtual ~StoreApiStoreOrderOrderIdResource(); - void DELETE_method_handler(const std::shared_ptr session); - void GET_method_handler(const std::shared_ptr session); - void set_handler_DELETE( - std::function( - std::string const & - )> handler - ); +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// - void set_handler_GET( - std::function( - int64_t const & - )> handler - ); + virtual int handler_DELETE( + std::string const & orderId); + + virtual std::pair> handler_GET( + int64_t const & orderId); + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + virtual std::string getPathParam_orderId(const std::shared_ptr& request) + { + return request->get_path_parameter("orderId", ""); + } + + + virtual int64_t getPathParam_orderId_x_extension(const std::shared_ptr& request) + { + return request->get_path_parameter("orderId", 0L); + } + + virtual std::pair handleStoreApiException(const StoreApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); private: - std::function( - std::string const & - )> handler_DELETE_; - - std::function( - int64_t const & - )> handler_GET_; - - std::string orderId{}; + void handler_DELETE_internal(const std::shared_ptr session); + void handler_GET_internal(const std::shared_ptr session); }; + /// /// Returns pet inventories by status /// @@ -85,25 +126,45 @@ private: class StoreApiStoreInventoryResource: public restbed::Resource { public: - StoreApiStoreInventoryResource(); + StoreApiStoreInventoryResource(const std::string& context = "/v2"); virtual ~StoreApiStoreInventoryResource(); - void GET_method_handler(const std::shared_ptr session); - void set_handler_GET( - std::function( - - )> handler - ); +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + virtual std::pair> handler_GET( + ); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + + + virtual std::pair handleStoreApiException(const StoreApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); private: - std::function( - - )> handler_GET_; - - + void handler_GET_internal(const std::shared_ptr session); }; + /// /// Place an order for a pet /// @@ -113,42 +174,70 @@ private: class StoreApiStoreOrderResource: public restbed::Resource { public: - StoreApiStoreOrderResource(); + StoreApiStoreOrderResource(const std::string& context = "/v2"); virtual ~StoreApiStoreOrderResource(); - void POST_method_handler(const std::shared_ptr session); - void set_handler_POST( - std::function( - std::shared_ptr const & - )> handler - ); +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + virtual std::pair> handler_POST( + std::shared_ptr const & body); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + + + virtual std::pair handleStoreApiException(const StoreApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); private: - std::function( - std::shared_ptr const & - )> handler_POST_; - - - std::shared_ptr body{}; + void handler_POST_internal(const std::shared_ptr session); }; + // // The restbed service to actually implement the REST server // -class StoreApi: public restbed::Service +class StoreApi { public: - StoreApi(); - ~StoreApi(); - void startService(int const& port); - void stopService(); - + explicit StoreApi(std::shared_ptr const& restbedService); + virtual ~StoreApi(); + + virtual void setStoreApiStoreOrderOrderIdResource(std::shared_ptr spStoreApiStoreOrderOrderIdResource); + virtual void setStoreApiStoreInventoryResource(std::shared_ptr spStoreApiStoreInventoryResource); + virtual void setStoreApiStoreOrderResource(std::shared_ptr spStoreApiStoreOrderResource); + + virtual void publishDefaultResources(); + + virtual std::shared_ptr service(); + protected: std::shared_ptr m_spStoreApiStoreOrderOrderIdResource; std::shared_ptr m_spStoreApiStoreInventoryResource; std::shared_ptr m_spStoreApiStoreOrderResource; + +private: + std::shared_ptr m_service; }; diff --git a/samples/server/petstore/cpp-restbed/api/UserApi.cpp b/samples/server/petstore/cpp-restbed/api/UserApi.cpp index a1630121cf5..c6485c6e129 100644 --- a/samples/server/petstore/cpp-restbed/api/UserApi.cpp +++ b/samples/server/petstore/cpp-restbed/api/UserApi.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 5.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator unset. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -15,6 +15,11 @@ #include #include #include +#include +#include +#include +#include +#include #include "UserApi.h" @@ -25,51 +30,68 @@ namespace api { using namespace org::openapitools::server::model; -UserApi::UserApi() { -} - -UserApi::~UserApi() {} - -void UserApi::startService(int const& port) { - // A typical pattern is to derive a class from UserApi and allocate the shared pointers for restbed::Resource objects - // and manipulate them (e.g. binding GET/POST handler functions) before this startService() gets called. - // In such a case we want to use our m_spXXX variables. - // However in case these shared pointers are nullptr, then allocate the restbed::Resources now: - if (!m_spUserApiUserResource) - m_spUserApiUserResource = std::make_shared(); - this->publish(m_spUserApiUserResource); - if (!m_spUserApiUserCreateWithArrayResource) - m_spUserApiUserCreateWithArrayResource = std::make_shared(); - this->publish(m_spUserApiUserCreateWithArrayResource); - if (!m_spUserApiUserCreateWithListResource) - m_spUserApiUserCreateWithListResource = std::make_shared(); - this->publish(m_spUserApiUserCreateWithListResource); - if (!m_spUserApiUserUsernameResource) - m_spUserApiUserUsernameResource = std::make_shared(); - this->publish(m_spUserApiUserUsernameResource); - if (!m_spUserApiUserLoginResource) - m_spUserApiUserLoginResource = std::make_shared(); - this->publish(m_spUserApiUserLoginResource); - if (!m_spUserApiUserLogoutResource) - m_spUserApiUserLogoutResource = std::make_shared(); - this->publish(m_spUserApiUserLogoutResource); - - std::shared_ptr settings = std::make_shared(); - settings->set_port(port); - settings->set_root("/v2"); - - this->start(settings); -} - -void UserApi::stopService() { - this->stop(); -} - -UserApiUserResource::UserApiUserResource() +UserApiException::UserApiException(int status_code, std::string what) + : m_status(status_code), + m_what(what) { - this->set_path("/user/"); + +} +int UserApiException::getStatus() const +{ + return m_status; +} +const char* UserApiException::what() const noexcept +{ + return m_what.c_str(); +} + + +template +std::shared_ptr extractJsonModelBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto model = std::make_shared(pt); + return model; +} + +template +std::vector> extractJsonArrayBodyParam(const std::string& bodyContent) +{ + std::stringstream sstream(bodyContent); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream, pt); + + auto arrayRet = std::vector>(); + for (const auto& child: pt) { + arrayRet.emplace_back(std::make_shared(child.second)); + } + return arrayRet; +} + +template +std::string convertMapResponse(const std::map& map) +{ + boost::property_tree::ptree pt; + for(const auto &kv: map) { + pt.push_back(boost::property_tree::ptree::value_type( + boost::lexical_cast(kv.first), + boost::property_tree::ptree( + boost::lexical_cast(kv.second)))); + } + std::stringstream sstream; + write_json(sstream, pt); + std::string result = sstream.str(); + return result; +} + +UserApiUserResource::UserApiUserResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/user/"); this->set_method_handler("POST", - std::bind(&UserApiUserResource::POST_method_handler, this, + std::bind(&UserApiUserResource::handler_POST_internal, this, std::placeholders::_1)); } @@ -77,58 +99,98 @@ UserApiUserResource::~UserApiUserResource() { } -void UserApiUserResource::set_handler_POST( - std::function( - std::shared_ptr const & - )> handler) { - handler_POST_ = std::move(handler); -} - - -void UserApiUserResource::POST_method_handler(const std::shared_ptr session) { - - const auto request = session->get_request(); - // Body params are present, therefore we have to fetch them - int content_length = request->get_header("Content-Length", 0); - session->fetch(content_length, - [ this ]( const std::shared_ptr session, const restbed::Bytes & body ) - { - - const auto request = session->get_request(); - std::string file = restbed::String::format("%.*s\n", ( int ) body.size( ), body.data( )); - /** - * Get body params or form params here from the file string - */ - - - - - // Change the value of this variable to the appropriate response before sending the response - int status_code = 200; - std::string result = "successful operation"; - - if (handler_POST_) - { - std::tie(status_code, result) = handler_POST_( - body - ); - } - - if (status_code == 0) { - session->close(0, result.empty() ? "successful operation" : std::move(result), { {"Connection", "close"} }); - return; - } - - }); -} - - - -UserApiUserCreateWithArrayResource::UserApiUserCreateWithArrayResource() +std::pair UserApiUserResource::handleUserApiException(const UserApiException& e) { - this->set_path("/user/createWithArray/"); + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair UserApiUserResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair UserApiUserResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void UserApiUserResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void UserApiUserResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void UserApiUserResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void UserApiUserResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + std::string bodyContent = extractBodyContent(session); + + // Get body params or form params here from the body content string + auto body = extractJsonModelBodyParam(bodyContent); + + + + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_POST(body); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 0) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 0, result.empty() ? "successful operation" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + + +int UserApiUserResource::handler_POST( + std::shared_ptr const & body) +{ + throw UserApiException(501, "Not implemented"); +} + + +std::string UserApiUserResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +UserApiUserCreateWithArrayResource::UserApiUserCreateWithArrayResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/user/createWithArray/"); this->set_method_handler("POST", - std::bind(&UserApiUserCreateWithArrayResource::POST_method_handler, this, + std::bind(&UserApiUserCreateWithArrayResource::handler_POST_internal, this, std::placeholders::_1)); } @@ -136,58 +198,98 @@ UserApiUserCreateWithArrayResource::~UserApiUserCreateWithArrayResource() { } -void UserApiUserCreateWithArrayResource::set_handler_POST( - std::function( - std::vector> const & - )> handler) { - handler_POST_ = std::move(handler); -} - - -void UserApiUserCreateWithArrayResource::POST_method_handler(const std::shared_ptr session) { - - const auto request = session->get_request(); - // Body params are present, therefore we have to fetch them - int content_length = request->get_header("Content-Length", 0); - session->fetch(content_length, - [ this ]( const std::shared_ptr session, const restbed::Bytes & body ) - { - - const auto request = session->get_request(); - std::string file = restbed::String::format("%.*s\n", ( int ) body.size( ), body.data( )); - /** - * Get body params or form params here from the file string - */ - - - - - // Change the value of this variable to the appropriate response before sending the response - int status_code = 200; - std::string result = "successful operation"; - - if (handler_POST_) - { - std::tie(status_code, result) = handler_POST_( - body - ); - } - - if (status_code == 0) { - session->close(0, result.empty() ? "successful operation" : std::move(result), { {"Connection", "close"} }); - return; - } - - }); -} - - - -UserApiUserCreateWithListResource::UserApiUserCreateWithListResource() +std::pair UserApiUserCreateWithArrayResource::handleUserApiException(const UserApiException& e) { - this->set_path("/user/createWithList/"); + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair UserApiUserCreateWithArrayResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair UserApiUserCreateWithArrayResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void UserApiUserCreateWithArrayResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void UserApiUserCreateWithArrayResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void UserApiUserCreateWithArrayResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void UserApiUserCreateWithArrayResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + std::string bodyContent = extractBodyContent(session); + + // Get body params or form params here from the body content string + auto body = extractJsonArrayBodyParam(bodyContent); + + + + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_POST(body); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 0) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 0, result.empty() ? "successful operation" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + + +int UserApiUserCreateWithArrayResource::handler_POST( + std::vector> const & body) +{ + throw UserApiException(501, "Not implemented"); +} + + +std::string UserApiUserCreateWithArrayResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +UserApiUserCreateWithListResource::UserApiUserCreateWithListResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/user/createWithList/"); this->set_method_handler("POST", - std::bind(&UserApiUserCreateWithListResource::POST_method_handler, this, + std::bind(&UserApiUserCreateWithListResource::handler_POST_internal, this, std::placeholders::_1)); } @@ -195,61 +297,104 @@ UserApiUserCreateWithListResource::~UserApiUserCreateWithListResource() { } -void UserApiUserCreateWithListResource::set_handler_POST( - std::function( - std::vector> const & - )> handler) { - handler_POST_ = std::move(handler); -} - - -void UserApiUserCreateWithListResource::POST_method_handler(const std::shared_ptr session) { - - const auto request = session->get_request(); - // Body params are present, therefore we have to fetch them - int content_length = request->get_header("Content-Length", 0); - session->fetch(content_length, - [ this ]( const std::shared_ptr session, const restbed::Bytes & body ) - { - - const auto request = session->get_request(); - std::string file = restbed::String::format("%.*s\n", ( int ) body.size( ), body.data( )); - /** - * Get body params or form params here from the file string - */ - - - - - // Change the value of this variable to the appropriate response before sending the response - int status_code = 200; - std::string result = "successful operation"; - - if (handler_POST_) - { - std::tie(status_code, result) = handler_POST_( - body - ); - } - - if (status_code == 0) { - session->close(0, result.empty() ? "successful operation" : std::move(result), { {"Connection", "close"} }); - return; - } - - }); -} - - - -UserApiUserUsernameResource::UserApiUserUsernameResource() +std::pair UserApiUserCreateWithListResource::handleUserApiException(const UserApiException& e) { - this->set_path("/user/{username: .*}/"); + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair UserApiUserCreateWithListResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair UserApiUserCreateWithListResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void UserApiUserCreateWithListResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void UserApiUserCreateWithListResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void UserApiUserCreateWithListResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void UserApiUserCreateWithListResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + std::string bodyContent = extractBodyContent(session); + + // Get body params or form params here from the body content string + auto body = extractJsonArrayBodyParam(bodyContent); + + + + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_POST(body); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 0) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 0, result.empty() ? "successful operation" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + + +int UserApiUserCreateWithListResource::handler_POST( + std::vector> const & body) +{ + throw UserApiException(501, "Not implemented"); +} + + +std::string UserApiUserCreateWithListResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +UserApiUserUsernameResource::UserApiUserUsernameResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/user/{username: .*}/"); this->set_method_handler("DELETE", - std::bind(&UserApiUserUsernameResource::DELETE_method_handler, this, + std::bind(&UserApiUserUsernameResource::handler_DELETE_internal, this, + std::placeholders::_1)); + this->set_method_handler("GET", + std::bind(&UserApiUserUsernameResource::handler_GET_internal, this, std::placeholders::_1)); this->set_method_handler("PUT", - std::bind(&UserApiUserUsernameResource::PUT_method_handler, this, + std::bind(&UserApiUserUsernameResource::handler_PUT_internal, this, std::placeholders::_1)); } @@ -257,97 +402,205 @@ UserApiUserUsernameResource::~UserApiUserUsernameResource() { } -void UserApiUserUsernameResource::set_handler_DELETE( - std::function( - std::string const & - )> handler) { - handler_DELETE_ = std::move(handler); -} - -void UserApiUserUsernameResource::set_handler_PUT( - std::function( - std::string const &, std::shared_ptr const & - )> handler) { - handler_PUT_ = std::move(handler); -} - -void UserApiUserUsernameResource::DELETE_method_handler(const std::shared_ptr session) { - - const auto request = session->get_request(); - - // Getting the path params - const std::string username = request->get_path_parameter("username", ""); - - - - // Change the value of this variable to the appropriate response before sending the response - int status_code = 200; - std::string result = "successful operation"; - - if (handler_DELETE_) - { - std::tie(status_code, result) = handler_DELETE_( - username - ); - } - - if (status_code == 400) { - session->close(400, result.empty() ? "Invalid username supplied" : std::move(result), { {"Connection", "close"} }); - return; - } - if (status_code == 404) { - session->close(404, result.empty() ? "User not found" : std::move(result), { {"Connection", "close"} }); - return; - } - -} - -void UserApiUserUsernameResource::PUT_method_handler(const std::shared_ptr session) { - - const auto request = session->get_request(); - // Body params are present, therefore we have to fetch them - int content_length = request->get_header("Content-Length", 0); - session->fetch(content_length, - [ this ]( const std::shared_ptr session, const restbed::Bytes & body ) - { - - const auto request = session->get_request(); - std::string file = restbed::String::format("%.*s\n", ( int ) body.size( ), body.data( )); - - // Getting the path params - const std::string username = request->get_path_parameter("username", ""); - - - - // Change the value of this variable to the appropriate response before sending the response - int status_code = 200; - std::string result = "successful operation"; - - if (handler_PUT_) - { - std::tie(status_code, result) = handler_PUT_( - username, body - ); - } - - if (status_code == 400) { - session->close(400, result.empty() ? "Invalid user supplied" : std::move(result), { {"Connection", "close"} }); - return; - } - if (status_code == 404) { - session->close(404, result.empty() ? "User not found" : std::move(result), { {"Connection", "close"} }); - return; - } - - }); -} - - -UserApiUserLoginResource::UserApiUserLoginResource() +std::pair UserApiUserUsernameResource::handleUserApiException(const UserApiException& e) { - this->set_path("/user/login/"); + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair UserApiUserUsernameResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair UserApiUserUsernameResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void UserApiUserUsernameResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void UserApiUserUsernameResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void UserApiUserUsernameResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void UserApiUserUsernameResource::handler_DELETE_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + // Getting the path params + const std::string username = getPathParam_username(request); + + + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_DELETE(username); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid username supplied" : result, contentType); + return; + } + if (status_code == 404) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 404, result.empty() ? "User not found" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + +// x-extension +void UserApiUserUsernameResource::handler_GET_internal(const std::shared_ptr session) { + + const auto request = session->get_request(); + + // Getting the path params + const std::string username = getPathParam_username_x_extension(request); + + + int status_code = 500; + std::shared_ptr resultObject = std::make_shared(); + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(username); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 200) { + result = resultObject->toJsonString(); + + const constexpr auto contentType = "application/json"; + returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); + return; + } + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid username supplied" : result, contentType); + return; + } + if (status_code == 404) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 404, result.empty() ? "User not found" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} +// x-extension +void UserApiUserUsernameResource::handler_PUT_internal(const std::shared_ptr session) { + + const auto request = session->get_request(); + std::string bodyContent = extractBodyContent(session); + + // body params or form params here from the body content string + auto username = std::make_shared<>(bodyContent); + auto body = extractJsonModelBodyParam(bodyContent); + + // Getting the path params + const std::string username = getPathParam_username_x_extension(request); + + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_PUT(username, body); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid user supplied" : result, contentType); + return; + } + if (status_code == 404) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 404, result.empty() ? "User not found" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + +int UserApiUserUsernameResource::handler_DELETE( + std::string const & username) +{ + throw UserApiException(501, "Not implemented"); +} + +std::pair> UserApiUserUsernameResource::handler_GET( + std::string const & username) +{ + throw UserApiException(501, "Not implemented"); +} +int UserApiUserUsernameResource::handler_PUT( + std::string const & username, std::shared_ptr const & body) +{ + throw UserApiException(501, "Not implemented"); +} + +std::string UserApiUserUsernameResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +UserApiUserLoginResource::UserApiUserLoginResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/user/login/"); this->set_method_handler("GET", - std::bind(&UserApiUserLoginResource::GET_method_handler, this, + std::bind(&UserApiUserLoginResource::handler_GET_internal, this, std::placeholders::_1)); } @@ -355,57 +608,109 @@ UserApiUserLoginResource::~UserApiUserLoginResource() { } -void UserApiUserLoginResource::set_handler_GET( - std::function( - std::string const &, std::string const & - )> handler) { - handler_GET_ = std::move(handler); -} - - -void UserApiUserLoginResource::GET_method_handler(const std::shared_ptr session) { - - const auto request = session->get_request(); - - - // Getting the query params - const std::string username = request->get_query_parameter("username", ""); - const std::string password = request->get_query_parameter("password", ""); - - - // Change the value of this variable to the appropriate response before sending the response - int status_code = 200; - std::string result = "successful operation"; - - if (handler_GET_) - { - std::tie(status_code, result) = handler_GET_( - username, password - ); - } - - if (status_code == 200) { - // Description: calls per hour allowed by the user - session->set_header("X-Rate-Limit", ""); // Change second param to your header value - // Description: date in UTC when toekn expires - session->set_header("X-Expires-After", ""); // Change second param to your header value - session->close(200, result.empty() ? "successful operation" : std::move(result), { {"Connection", "close"} }); - return; - } - if (status_code == 400) { - session->close(400, result.empty() ? "Invalid username/password supplied" : std::move(result), { {"Connection", "close"} }); - return; - } - -} - - - -UserApiUserLogoutResource::UserApiUserLogoutResource() +std::pair UserApiUserLoginResource::handleUserApiException(const UserApiException& e) { - this->set_path("/user/logout/"); + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair UserApiUserLoginResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair UserApiUserLoginResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void UserApiUserLoginResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void UserApiUserLoginResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void UserApiUserLoginResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void UserApiUserLoginResource::handler_GET_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + + // Getting the query params + const std::string username = getQueryParam_username(request); + const std::string password = getQueryParam_password(request); + + + int status_code = 500; + std::string resultObject = ""; + std::string result = ""; + + try { + std::tie(status_code, resultObject) = + handler_GET(username, password); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 200) { + result = resultObject; + // Description: calls per hour allowed by the user + setResponseHeader(session, "X-Rate-Limit"); + // Description: date in UTC when toekn expires + setResponseHeader(session, "X-Expires-After"); + + const constexpr auto contentType = "application/json"; + returnResponse(session, 200, result.empty() ? "successful operation" : result, contentType); + return; + } + if (status_code == 400) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 400, result.empty() ? "Invalid username/password supplied" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); +} + + +std::pair UserApiUserLoginResource::handler_GET( + std::string const & username, std::string const & password) +{ + throw UserApiException(501, "Not implemented"); +} + + +std::string UserApiUserLoginResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} +UserApiUserLogoutResource::UserApiUserLogoutResource(const std::string& context /* = "/v2" */) +{ + this->set_path(context + "/user/logout/"); this->set_method_handler("GET", - std::bind(&UserApiUserLogoutResource::GET_method_handler, this, + std::bind(&UserApiUserLogoutResource::handler_GET_internal, this, std::placeholders::_1)); } @@ -413,40 +718,147 @@ UserApiUserLogoutResource::~UserApiUserLogoutResource() { } -void UserApiUserLogoutResource::set_handler_GET( - std::function( - - )> handler) { - handler_GET_ = std::move(handler); +std::pair UserApiUserLogoutResource::handleUserApiException(const UserApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair UserApiUserLogoutResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair UserApiUserLogoutResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void UserApiUserLogoutResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void UserApiUserLogoutResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, const std::string& contentType) +{ + session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} }); +} + +void UserApiUserLogoutResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void UserApiUserLogoutResource::handler_GET_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + + + + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_GET(); + } + catch(const UserApiException& e) { + std::tie(status_code, result) = handleUserApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + if (status_code == 0) { + + const constexpr auto contentType = "text/plain"; + returnResponse(session, 0, result.empty() ? "successful operation" : result, contentType); + return; + } + defaultSessionClose(session, status_code, result); } -void UserApiUserLogoutResource::GET_method_handler(const std::shared_ptr session) { - - const auto request = session->get_request(); - - - - - // Change the value of this variable to the appropriate response before sending the response - int status_code = 200; - std::string result = "successful operation"; - - if (handler_GET_) - { - std::tie(status_code, result) = handler_GET_( - - ); - } - - if (status_code == 0) { - session->close(0, result.empty() ? "successful operation" : std::move(result), { {"Connection", "close"} }); - return; - } - +int UserApiUserLogoutResource::handler_GET( + ) +{ + throw UserApiException(501, "Not implemented"); } +std::string UserApiUserLogoutResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +UserApi::UserApi(std::shared_ptr const& restbedService) +: m_service(restbedService) +{ +} + +UserApi::~UserApi() {} + +void UserApi::setUserApiUserResource(std::shared_ptr spUserApiUserResource) { + m_spUserApiUserResource = spUserApiUserResource; + m_service->publish(m_spUserApiUserResource); +} +void UserApi::setUserApiUserCreateWithArrayResource(std::shared_ptr spUserApiUserCreateWithArrayResource) { + m_spUserApiUserCreateWithArrayResource = spUserApiUserCreateWithArrayResource; + m_service->publish(m_spUserApiUserCreateWithArrayResource); +} +void UserApi::setUserApiUserCreateWithListResource(std::shared_ptr spUserApiUserCreateWithListResource) { + m_spUserApiUserCreateWithListResource = spUserApiUserCreateWithListResource; + m_service->publish(m_spUserApiUserCreateWithListResource); +} +void UserApi::setUserApiUserUsernameResource(std::shared_ptr spUserApiUserUsernameResource) { + m_spUserApiUserUsernameResource = spUserApiUserUsernameResource; + m_service->publish(m_spUserApiUserUsernameResource); +} +void UserApi::setUserApiUserLoginResource(std::shared_ptr spUserApiUserLoginResource) { + m_spUserApiUserLoginResource = spUserApiUserLoginResource; + m_service->publish(m_spUserApiUserLoginResource); +} +void UserApi::setUserApiUserLogoutResource(std::shared_ptr spUserApiUserLogoutResource) { + m_spUserApiUserLogoutResource = spUserApiUserLogoutResource; + m_service->publish(m_spUserApiUserLogoutResource); +} + + +void UserApi::publishDefaultResources() { + if (!m_spUserApiUserResource) { + setUserApiUserResource(std::make_shared()); + } + if (!m_spUserApiUserCreateWithArrayResource) { + setUserApiUserCreateWithArrayResource(std::make_shared()); + } + if (!m_spUserApiUserCreateWithListResource) { + setUserApiUserCreateWithListResource(std::make_shared()); + } + if (!m_spUserApiUserUsernameResource) { + setUserApiUserUsernameResource(std::make_shared()); + } + if (!m_spUserApiUserLoginResource) { + setUserApiUserLoginResource(std::make_shared()); + } + if (!m_spUserApiUserLogoutResource) { + setUserApiUserLogoutResource(std::make_shared()); + } +} + +std::shared_ptr UserApi::service() { + return m_service; +} } diff --git a/samples/server/petstore/cpp-restbed/api/UserApi.h b/samples/server/petstore/cpp-restbed/api/UserApi.h index 9c4f4af73ee..ce692f0ea7f 100644 --- a/samples/server/petstore/cpp-restbed/api/UserApi.h +++ b/samples/server/petstore/cpp-restbed/api/UserApi.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 5.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator unset. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -22,10 +22,13 @@ #include #include +#include #include #include +#include #include +#include #include "User.h" #include @@ -38,6 +41,22 @@ namespace api { using namespace org::openapitools::server::model; +/// +/// Exception to flag problems in the handlers +/// +class UserApiException: public std::exception +{ +public: + UserApiException(int status_code, std::string what); + + int getStatus() const; + const char* what() const noexcept override; + +private: + int m_status; + std::string m_what; +}; + /// /// Create user /// @@ -47,26 +66,45 @@ using namespace org::openapitools::server::model; class UserApiUserResource: public restbed::Resource { public: - UserApiUserResource(); + UserApiUserResource(const std::string& context = "/v2"); virtual ~UserApiUserResource(); - void POST_method_handler(const std::shared_ptr session); - void set_handler_POST( - std::function( - std::shared_ptr const & - )> handler - ); +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + virtual int handler_POST( + std::shared_ptr const & body); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + + + virtual std::pair handleUserApiException(const UserApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); private: - std::function( - std::shared_ptr const & - )> handler_POST_; - - - std::shared_ptr body{}; + void handler_POST_internal(const std::shared_ptr session); }; + /// /// Creates list of users with given input array /// @@ -76,26 +114,45 @@ private: class UserApiUserCreateWithArrayResource: public restbed::Resource { public: - UserApiUserCreateWithArrayResource(); + UserApiUserCreateWithArrayResource(const std::string& context = "/v2"); virtual ~UserApiUserCreateWithArrayResource(); - void POST_method_handler(const std::shared_ptr session); - void set_handler_POST( - std::function( - std::vector> const & - )> handler - ); +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + virtual int handler_POST( + std::vector> const & body); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + + + virtual std::pair handleUserApiException(const UserApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); private: - std::function( - std::vector> const & - )> handler_POST_; - - - std::vector> body{}; + void handler_POST_internal(const std::shared_ptr session); }; + /// /// Creates list of users with given input array /// @@ -105,26 +162,45 @@ private: class UserApiUserCreateWithListResource: public restbed::Resource { public: - UserApiUserCreateWithListResource(); + UserApiUserCreateWithListResource(const std::string& context = "/v2"); virtual ~UserApiUserCreateWithListResource(); - void POST_method_handler(const std::shared_ptr session); - void set_handler_POST( - std::function( - std::vector> const & - )> handler - ); +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + virtual int handler_POST( + std::vector> const & body); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + + + virtual std::pair handleUserApiException(const UserApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); private: - std::function( - std::vector> const & - )> handler_POST_; - - - std::vector> body{}; + void handler_POST_internal(const std::shared_ptr session); }; + /// /// Delete user /// @@ -134,35 +210,64 @@ private: class UserApiUserUsernameResource: public restbed::Resource { public: - UserApiUserUsernameResource(); + UserApiUserUsernameResource(const std::string& context = "/v2"); virtual ~UserApiUserUsernameResource(); - void DELETE_method_handler(const std::shared_ptr session); - void PUT_method_handler(const std::shared_ptr session); - void set_handler_DELETE( - std::function( - std::string const & - )> handler - ); +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// - void set_handler_PUT( - std::function( - std::string const &, std::shared_ptr const & - )> handler - ); + virtual int handler_DELETE( + std::string const & username); + + virtual std::pair> handler_GET( + std::string const & username); + virtual int handler_PUT( + std::string const & username, std::shared_ptr const & body); + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + virtual std::string getPathParam_username(const std::shared_ptr& request) + { + return request->get_path_parameter("username", ""); + } + + + virtual std::string getPathParam_username_x_extension(const std::shared_ptr& request) + { + return request->get_path_parameter("username", ""); + } + virtual std::string getPathParam_username_x_extension(const std::shared_ptr& request) + { + return request->get_path_parameter("username", ""); + } + + virtual std::pair handleUserApiException(const UserApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); private: - std::function( - std::string const & - )> handler_DELETE_; - - std::function( - std::string const &, std::shared_ptr const & - )> handler_PUT_; - - std::string username{}; + void handler_DELETE_internal(const std::shared_ptr session); + void handler_GET_internal(const std::shared_ptr session); + void handler_PUT_internal(const std::shared_ptr session); }; + /// /// Logs user into the system /// @@ -172,27 +277,55 @@ private: class UserApiUserLoginResource: public restbed::Resource { public: - UserApiUserLoginResource(); + UserApiUserLoginResource(const std::string& context = "/v2"); virtual ~UserApiUserLoginResource(); - void GET_method_handler(const std::shared_ptr session); - void set_handler_GET( - std::function( - std::string const &, std::string const & - )> handler - ); +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + virtual std::pair handler_GET( + std::string const & username, std::string const & password); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + virtual std::string getQueryParam_username(const std::shared_ptr& request) + { + return request->get_query_parameter("username", ""); + } + + virtual std::string getQueryParam_password(const std::shared_ptr& request) + { + return request->get_query_parameter("password", ""); + } + + + + virtual std::pair handleUserApiException(const UserApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); private: - std::function( - std::string const &, std::string const & - )> handler_GET_; - - - std::string username{}; - std::string password{}; + void handler_GET_internal(const std::shared_ptr session); }; + /// /// Logs out current logged in user session /// @@ -202,37 +335,66 @@ private: class UserApiUserLogoutResource: public restbed::Resource { public: - UserApiUserLogoutResource(); + UserApiUserLogoutResource(const std::string& context = "/v2"); virtual ~UserApiUserLogoutResource(); - void GET_method_handler(const std::shared_ptr session); - void set_handler_GET( - std::function( - - )> handler - ); +protected: + ////////////////////////////////////////////////////////// + // Override these to implement the server functionality // + ////////////////////////////////////////////////////////// + virtual int handler_GET( + ); + + +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + + + + virtual std::pair handleUserApiException(const UserApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, const std::string& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); private: - std::function( - - )> handler_GET_; - - + void handler_GET_internal(const std::shared_ptr session); }; + // // The restbed service to actually implement the REST server // -class UserApi: public restbed::Service +class UserApi { public: - UserApi(); - ~UserApi(); - void startService(int const& port); - void stopService(); - + explicit UserApi(std::shared_ptr const& restbedService); + virtual ~UserApi(); + + virtual void setUserApiUserResource(std::shared_ptr spUserApiUserResource); + virtual void setUserApiUserCreateWithArrayResource(std::shared_ptr spUserApiUserCreateWithArrayResource); + virtual void setUserApiUserCreateWithListResource(std::shared_ptr spUserApiUserCreateWithListResource); + virtual void setUserApiUserUsernameResource(std::shared_ptr spUserApiUserUsernameResource); + virtual void setUserApiUserLoginResource(std::shared_ptr spUserApiUserLoginResource); + virtual void setUserApiUserLogoutResource(std::shared_ptr spUserApiUserLogoutResource); + + virtual void publishDefaultResources(); + + virtual std::shared_ptr service(); + protected: std::shared_ptr m_spUserApiUserResource; std::shared_ptr m_spUserApiUserCreateWithArrayResource; @@ -240,6 +402,9 @@ protected: std::shared_ptr m_spUserApiUserUsernameResource; std::shared_ptr m_spUserApiUserLoginResource; std::shared_ptr m_spUserApiUserLogoutResource; + +private: + std::shared_ptr m_service; }; diff --git a/samples/server/petstore/cpp-restbed/model/ApiResponse.cpp b/samples/server/petstore/cpp-restbed/model/ApiResponse.cpp index 9ebf3e6784d..502b298003e 100644 --- a/samples/server/petstore/cpp-restbed/model/ApiResponse.cpp +++ b/samples/server/petstore/cpp-restbed/model/ApiResponse.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 5.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator unset. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -15,7 +15,9 @@ #include "ApiResponse.h" #include +#include #include +#include #include #include @@ -28,25 +30,39 @@ namespace openapitools { namespace server { namespace model { -ApiResponse::ApiResponse() +ApiResponse::ApiResponse(boost::property_tree::ptree const& pt) { - m_Code = 0; - m_Type = ""; - m_Message = ""; + fromPropertyTree(pt); } -ApiResponse::~ApiResponse() +std::string ApiResponse::toJsonString(bool prettyJson /* = false */) { + return toJsonString_internal(prettyJson); } -std::string ApiResponse::toJsonString(bool prettyJson) +void ApiResponse::fromJsonString(std::string const& jsonString) +{ + fromJsonString_internal(jsonString); +} + +boost::property_tree::ptree ApiResponse::toPropertyTree() +{ + return toPropertyTree_internal(); +} + +void ApiResponse::fromPropertyTree(boost::property_tree::ptree const& pt) +{ + fromPropertyTree_internal(pt); +} + +std::string ApiResponse::toJsonString_internal(bool prettyJson) { std::stringstream ss; write_json(ss, this->toPropertyTree(), prettyJson); return ss.str(); } -void ApiResponse::fromJsonString(std::string const& jsonString) +void ApiResponse::fromJsonString_internal(std::string const& jsonString) { std::stringstream ss(jsonString); ptree pt; @@ -54,7 +70,7 @@ void ApiResponse::fromJsonString(std::string const& jsonString) this->fromPropertyTree(pt); } -ptree ApiResponse::toPropertyTree() +ptree ApiResponse::toPropertyTree_internal() { ptree pt; ptree tmp_node; @@ -64,7 +80,7 @@ ptree ApiResponse::toPropertyTree() return pt; } -void ApiResponse::fromPropertyTree(ptree const &pt) +void ApiResponse::fromPropertyTree_internal(ptree const &pt) { ptree tmp_node; m_Code = pt.get("code", 0); @@ -76,6 +92,7 @@ int32_t ApiResponse::getCode() const { return m_Code; } + void ApiResponse::setCode(int32_t value) { m_Code = value; @@ -84,6 +101,7 @@ std::string ApiResponse::getType() const { return m_Type; } + void ApiResponse::setType(std::string value) { m_Type = value; @@ -92,11 +110,26 @@ std::string ApiResponse::getMessage() const { return m_Message; } + void ApiResponse::setMessage(std::string value) { m_Message = value; } +std::vector createApiResponseVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(ApiResponse(child.second)); + } + + return vec; +} + } } } diff --git a/samples/server/petstore/cpp-restbed/model/ApiResponse.h b/samples/server/petstore/cpp-restbed/model/ApiResponse.h index 0f90e52c313..b67b10af78d 100644 --- a/samples/server/petstore/cpp-restbed/model/ApiResponse.h +++ b/samples/server/petstore/cpp-restbed/model/ApiResponse.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 5.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator unset. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -23,6 +23,7 @@ #include #include +#include #include namespace org { @@ -36,8 +37,9 @@ namespace model { class ApiResponse { public: - ApiResponse(); - virtual ~ApiResponse(); + ApiResponse() = default; + explicit ApiResponse(boost::property_tree::ptree const& pt); + virtual ~ApiResponse() = default; std::string toJsonString(bool prettyJson = false); void fromJsonString(std::string const& jsonString); @@ -64,12 +66,26 @@ public: /// std::string getMessage() const; void setMessage(std::string value); + protected: - int32_t m_Code; - std::string m_Type; - std::string m_Message; + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string toJsonString_internal(bool prettyJson = false); + virtual void fromJsonString_internal(std::string const& jsonString); + virtual boost::property_tree::ptree toPropertyTree_internal(); + virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); + + +protected: + int32_t m_Code = 0; + std::string m_Type = ""; + std::string m_Message = ""; }; +std::vector createApiResponseVectorFromJsonString(const std::string& json); + } } } diff --git a/samples/server/petstore/cpp-restbed/model/Category.cpp b/samples/server/petstore/cpp-restbed/model/Category.cpp index 253eeceeaf8..d5bf918f62d 100644 --- a/samples/server/petstore/cpp-restbed/model/Category.cpp +++ b/samples/server/petstore/cpp-restbed/model/Category.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 5.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator unset. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -15,7 +15,9 @@ #include "Category.h" #include +#include #include +#include #include #include @@ -28,24 +30,39 @@ namespace openapitools { namespace server { namespace model { -Category::Category() +Category::Category(boost::property_tree::ptree const& pt) { - m_Id = 0L; - m_Name = ""; + fromPropertyTree(pt); } -Category::~Category() +std::string Category::toJsonString(bool prettyJson /* = false */) { + return toJsonString_internal(prettyJson); } -std::string Category::toJsonString(bool prettyJson) +void Category::fromJsonString(std::string const& jsonString) +{ + fromJsonString_internal(jsonString); +} + +boost::property_tree::ptree Category::toPropertyTree() +{ + return toPropertyTree_internal(); +} + +void Category::fromPropertyTree(boost::property_tree::ptree const& pt) +{ + fromPropertyTree_internal(pt); +} + +std::string Category::toJsonString_internal(bool prettyJson) { std::stringstream ss; write_json(ss, this->toPropertyTree(), prettyJson); return ss.str(); } -void Category::fromJsonString(std::string const& jsonString) +void Category::fromJsonString_internal(std::string const& jsonString) { std::stringstream ss(jsonString); ptree pt; @@ -53,7 +70,7 @@ void Category::fromJsonString(std::string const& jsonString) this->fromPropertyTree(pt); } -ptree Category::toPropertyTree() +ptree Category::toPropertyTree_internal() { ptree pt; ptree tmp_node; @@ -62,7 +79,7 @@ ptree Category::toPropertyTree() return pt; } -void Category::fromPropertyTree(ptree const &pt) +void Category::fromPropertyTree_internal(ptree const &pt) { ptree tmp_node; m_Id = pt.get("id", 0L); @@ -73,6 +90,7 @@ int64_t Category::getId() const { return m_Id; } + void Category::setId(int64_t value) { m_Id = value; @@ -81,11 +99,26 @@ std::string Category::getName() const { return m_Name; } + void Category::setName(std::string value) { m_Name = value; } +std::vector createCategoryVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(Category(child.second)); + } + + return vec; +} + } } } diff --git a/samples/server/petstore/cpp-restbed/model/Category.h b/samples/server/petstore/cpp-restbed/model/Category.h index 13cd4416ce1..949677e8bf7 100644 --- a/samples/server/petstore/cpp-restbed/model/Category.h +++ b/samples/server/petstore/cpp-restbed/model/Category.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 5.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator unset. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -23,6 +23,7 @@ #include #include +#include #include namespace org { @@ -36,8 +37,9 @@ namespace model { class Category { public: - Category(); - virtual ~Category(); + Category() = default; + explicit Category(boost::property_tree::ptree const& pt); + virtual ~Category() = default; std::string toJsonString(bool prettyJson = false); void fromJsonString(std::string const& jsonString); @@ -58,11 +60,25 @@ public: /// std::string getName() const; void setName(std::string value); + protected: - int64_t m_Id; - std::string m_Name; + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string toJsonString_internal(bool prettyJson = false); + virtual void fromJsonString_internal(std::string const& jsonString); + virtual boost::property_tree::ptree toPropertyTree_internal(); + virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); + + +protected: + int64_t m_Id = 0L; + std::string m_Name = ""; }; +std::vector createCategoryVectorFromJsonString(const std::string& json); + } } } diff --git a/samples/server/petstore/cpp-restbed/model/Order.cpp b/samples/server/petstore/cpp-restbed/model/Order.cpp index 19e539ce226..b0e1db2687e 100644 --- a/samples/server/petstore/cpp-restbed/model/Order.cpp +++ b/samples/server/petstore/cpp-restbed/model/Order.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 5.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator unset. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -15,7 +15,9 @@ #include "Order.h" #include +#include #include +#include #include #include #include @@ -29,29 +31,39 @@ namespace openapitools { namespace server { namespace model { -Order::Order() +Order::Order(boost::property_tree::ptree const& pt) { - m_Id = 0L; - m_PetId = 0L; - m_Quantity = 0; - m_ShipDate = ""; - m_Status = ""; - m_StatusEnum = { "placed", "approved", "delivered" }; - m_Complete = false; + fromPropertyTree(pt); } -Order::~Order() +std::string Order::toJsonString(bool prettyJson /* = false */) { + return toJsonString_internal(prettyJson); } -std::string Order::toJsonString(bool prettyJson) +void Order::fromJsonString(std::string const& jsonString) +{ + fromJsonString_internal(jsonString); +} + +boost::property_tree::ptree Order::toPropertyTree() +{ + return toPropertyTree_internal(); +} + +void Order::fromPropertyTree(boost::property_tree::ptree const& pt) +{ + fromPropertyTree_internal(pt); +} + +std::string Order::toJsonString_internal(bool prettyJson) { std::stringstream ss; write_json(ss, this->toPropertyTree(), prettyJson); return ss.str(); } -void Order::fromJsonString(std::string const& jsonString) +void Order::fromJsonString_internal(std::string const& jsonString) { std::stringstream ss(jsonString); ptree pt; @@ -59,7 +71,7 @@ void Order::fromJsonString(std::string const& jsonString) this->fromPropertyTree(pt); } -ptree Order::toPropertyTree() +ptree Order::toPropertyTree_internal() { ptree pt; ptree tmp_node; @@ -72,7 +84,7 @@ ptree Order::toPropertyTree() return pt; } -void Order::fromPropertyTree(ptree const &pt) +void Order::fromPropertyTree_internal(ptree const &pt) { ptree tmp_node; m_Id = pt.get("id", 0L); @@ -87,6 +99,7 @@ int64_t Order::getId() const { return m_Id; } + void Order::setId(int64_t value) { m_Id = value; @@ -95,6 +108,7 @@ int64_t Order::getPetId() const { return m_PetId; } + void Order::setPetId(int64_t value) { m_PetId = value; @@ -103,6 +117,7 @@ int32_t Order::getQuantity() const { return m_Quantity; } + void Order::setQuantity(int32_t value) { m_Quantity = value; @@ -111,6 +126,7 @@ std::string Order::getShipDate() const { return m_ShipDate; } + void Order::setShipDate(std::string value) { m_ShipDate = value; @@ -119,6 +135,7 @@ std::string Order::getStatus() const { return m_Status; } + void Order::setStatus(std::string value) { if (std::find(m_StatusEnum.begin(), m_StatusEnum.end(), value) != m_StatusEnum.end()) { @@ -131,11 +148,26 @@ bool Order::isComplete() const { return m_Complete; } + void Order::setComplete(bool value) { m_Complete = value; } +std::vector createOrderVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(Order(child.second)); + } + + return vec; +} + } } } diff --git a/samples/server/petstore/cpp-restbed/model/Order.h b/samples/server/petstore/cpp-restbed/model/Order.h index 8e916ba2683..b10f2daf3ac 100644 --- a/samples/server/petstore/cpp-restbed/model/Order.h +++ b/samples/server/petstore/cpp-restbed/model/Order.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 5.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator unset. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -24,6 +24,8 @@ #include #include #include +#include +#include #include namespace org { @@ -37,8 +39,9 @@ namespace model { class Order { public: - Order(); - virtual ~Order(); + Order() = default; + explicit Order(boost::property_tree::ptree const& pt); + virtual ~Order() = default; std::string toJsonString(bool prettyJson = false); void fromJsonString(std::string const& jsonString); @@ -83,16 +86,33 @@ public: /// bool isComplete() const; void setComplete(bool value); + protected: - int64_t m_Id; - int64_t m_PetId; - int32_t m_Quantity; - std::string m_ShipDate; - std::string m_Status; - bool m_Complete; - std::vector m_StatusEnum; + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string toJsonString_internal(bool prettyJson = false); + virtual void fromJsonString_internal(std::string const& jsonString); + virtual boost::property_tree::ptree toPropertyTree_internal(); + virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); + + +protected: + int64_t m_Id = 0L; + int64_t m_PetId = 0L; + int32_t m_Quantity = 0; + std::string m_ShipDate = ""; + std::string m_Status = ""; + bool m_Complete = false; + const std::array m_StatusEnum = { + "placed","approved","delivered" + }; + }; +std::vector createOrderVectorFromJsonString(const std::string& json); + } } } diff --git a/samples/server/petstore/cpp-restbed/model/Pet.cpp b/samples/server/petstore/cpp-restbed/model/Pet.cpp index 3e0d909847d..b9392b60f53 100644 --- a/samples/server/petstore/cpp-restbed/model/Pet.cpp +++ b/samples/server/petstore/cpp-restbed/model/Pet.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 5.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator unset. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -15,7 +15,9 @@ #include "Pet.h" #include +#include #include +#include #include #include #include @@ -29,26 +31,39 @@ namespace openapitools { namespace server { namespace model { -Pet::Pet() +Pet::Pet(boost::property_tree::ptree const& pt) { - m_Id = 0L; - m_Name = ""; - m_Status = ""; - m_StatusEnum = { "available", "pending", "sold" }; + fromPropertyTree(pt); } -Pet::~Pet() +std::string Pet::toJsonString(bool prettyJson /* = false */) { + return toJsonString_internal(prettyJson); } -std::string Pet::toJsonString(bool prettyJson) +void Pet::fromJsonString(std::string const& jsonString) +{ + fromJsonString_internal(jsonString); +} + +boost::property_tree::ptree Pet::toPropertyTree() +{ + return toPropertyTree_internal(); +} + +void Pet::fromPropertyTree(boost::property_tree::ptree const& pt) +{ + fromPropertyTree_internal(pt); +} + +std::string Pet::toJsonString_internal(bool prettyJson) { std::stringstream ss; write_json(ss, this->toPropertyTree(), prettyJson); return ss.str(); } -void Pet::fromJsonString(std::string const& jsonString) +void Pet::fromJsonString_internal(std::string const& jsonString) { std::stringstream ss(jsonString); ptree pt; @@ -56,7 +71,7 @@ void Pet::fromJsonString(std::string const& jsonString) this->fromPropertyTree(pt); } -ptree Pet::toPropertyTree() +ptree Pet::toPropertyTree_internal() { ptree pt; ptree tmp_node; @@ -68,9 +83,9 @@ ptree Pet::toPropertyTree() // generate tree for PhotoUrls if (!m_PhotoUrls.empty()) { for (const auto &childEntry : m_PhotoUrls) { - ptree PhotoUrls_node; - PhotoUrls_node.put("", childEntry); - tmp_node.push_back(std::make_pair("", PhotoUrls_node)); + ptree PhotoUrls_node; + PhotoUrls_node.put("", childEntry); + tmp_node.push_back(std::make_pair("", PhotoUrls_node)); } pt.add_child("photoUrls", tmp_node); tmp_node.clear(); @@ -78,9 +93,7 @@ ptree Pet::toPropertyTree() // generate tree for Tags if (!m_Tags.empty()) { for (const auto &childEntry : m_Tags) { - ptree Tags_node; - Tags_node.put("", childEntry); - tmp_node.push_back(std::make_pair("", Tags_node)); + tmp_node.push_back(std::make_pair("", childEntry->toPropertyTree())); } pt.add_child("tags", tmp_node); tmp_node.clear(); @@ -89,7 +102,7 @@ ptree Pet::toPropertyTree() return pt; } -void Pet::fromPropertyTree(ptree const &pt) +void Pet::fromPropertyTree_internal(ptree const &pt) { ptree tmp_node; m_Id = pt.get("id", 0L); @@ -101,13 +114,17 @@ void Pet::fromPropertyTree(ptree const &pt) // push all items of PhotoUrls into member vector if (pt.get_child_optional("photoUrls")) { for (const auto &childTree : pt.get_child("photoUrls")) { - m_PhotoUrls.emplace_back(childTree.second.data()); + std::string val = + childTree.second.data(); + m_PhotoUrls.emplace_back(std::move(val)); } } // push all items of Tags into member vector if (pt.get_child_optional("tags")) { for (const auto &childTree : pt.get_child("tags")) { - m_Tags.emplace_back(childTree.second.data()); + std::shared_ptr val = + std::make_shared(childTree.second); + m_Tags.emplace_back(std::move(val)); } } setStatus(pt.get("status", "")); @@ -117,6 +134,7 @@ int64_t Pet::getId() const { return m_Id; } + void Pet::setId(int64_t value) { m_Id = value; @@ -125,6 +143,7 @@ std::shared_ptr Pet::getCategory() const { return m_Category; } + void Pet::setCategory(std::shared_ptr value) { m_Category = value; @@ -133,6 +152,7 @@ std::string Pet::getName() const { return m_Name; } + void Pet::setName(std::string value) { m_Name = value; @@ -141,6 +161,7 @@ std::vector Pet::getPhotoUrls() const { return m_PhotoUrls; } + void Pet::setPhotoUrls(std::vector value) { m_PhotoUrls = value; @@ -149,6 +170,7 @@ std::vector> Pet::getTags() const { return m_Tags; } + void Pet::setTags(std::vector> value) { m_Tags = value; @@ -157,6 +179,7 @@ std::string Pet::getStatus() const { return m_Status; } + void Pet::setStatus(std::string value) { if (std::find(m_StatusEnum.begin(), m_StatusEnum.end(), value) != m_StatusEnum.end()) { @@ -166,6 +189,20 @@ void Pet::setStatus(std::string value) } } +std::vector createPetVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(Pet(child.second)); + } + + return vec; +} + } } } diff --git a/samples/server/petstore/cpp-restbed/model/Pet.h b/samples/server/petstore/cpp-restbed/model/Pet.h index b7a59c60851..43bd89e15be 100644 --- a/samples/server/petstore/cpp-restbed/model/Pet.h +++ b/samples/server/petstore/cpp-restbed/model/Pet.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 5.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator unset. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -26,6 +26,8 @@ #include "Category.h" #include #include +#include +#include #include namespace org { @@ -39,8 +41,9 @@ namespace model { class Pet { public: - Pet(); - virtual ~Pet(); + Pet() = default; + explicit Pet(boost::property_tree::ptree const& pt); + virtual ~Pet() = default; std::string toJsonString(bool prettyJson = false); void fromJsonString(std::string const& jsonString); @@ -85,16 +88,33 @@ public: /// std::string getStatus() const; void setStatus(std::string value); + protected: - int64_t m_Id; + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string toJsonString_internal(bool prettyJson = false); + virtual void fromJsonString_internal(std::string const& jsonString); + virtual boost::property_tree::ptree toPropertyTree_internal(); + virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); + + +protected: + int64_t m_Id = 0L; std::shared_ptr m_Category; - std::string m_Name; + std::string m_Name = ""; std::vector m_PhotoUrls; std::vector> m_Tags; - std::string m_Status; - std::vector m_StatusEnum; + std::string m_Status = ""; + const std::array m_StatusEnum = { + "available","pending","sold" + }; + }; +std::vector createPetVectorFromJsonString(const std::string& json); + } } } diff --git a/samples/server/petstore/cpp-restbed/model/Tag.cpp b/samples/server/petstore/cpp-restbed/model/Tag.cpp index f4784b44059..3d191b7f3d3 100644 --- a/samples/server/petstore/cpp-restbed/model/Tag.cpp +++ b/samples/server/petstore/cpp-restbed/model/Tag.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 5.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator unset. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -15,7 +15,9 @@ #include "Tag.h" #include +#include #include +#include #include #include @@ -28,24 +30,39 @@ namespace openapitools { namespace server { namespace model { -Tag::Tag() +Tag::Tag(boost::property_tree::ptree const& pt) { - m_Id = 0L; - m_Name = ""; + fromPropertyTree(pt); } -Tag::~Tag() +std::string Tag::toJsonString(bool prettyJson /* = false */) { + return toJsonString_internal(prettyJson); } -std::string Tag::toJsonString(bool prettyJson) +void Tag::fromJsonString(std::string const& jsonString) +{ + fromJsonString_internal(jsonString); +} + +boost::property_tree::ptree Tag::toPropertyTree() +{ + return toPropertyTree_internal(); +} + +void Tag::fromPropertyTree(boost::property_tree::ptree const& pt) +{ + fromPropertyTree_internal(pt); +} + +std::string Tag::toJsonString_internal(bool prettyJson) { std::stringstream ss; write_json(ss, this->toPropertyTree(), prettyJson); return ss.str(); } -void Tag::fromJsonString(std::string const& jsonString) +void Tag::fromJsonString_internal(std::string const& jsonString) { std::stringstream ss(jsonString); ptree pt; @@ -53,7 +70,7 @@ void Tag::fromJsonString(std::string const& jsonString) this->fromPropertyTree(pt); } -ptree Tag::toPropertyTree() +ptree Tag::toPropertyTree_internal() { ptree pt; ptree tmp_node; @@ -62,7 +79,7 @@ ptree Tag::toPropertyTree() return pt; } -void Tag::fromPropertyTree(ptree const &pt) +void Tag::fromPropertyTree_internal(ptree const &pt) { ptree tmp_node; m_Id = pt.get("id", 0L); @@ -73,6 +90,7 @@ int64_t Tag::getId() const { return m_Id; } + void Tag::setId(int64_t value) { m_Id = value; @@ -81,11 +99,26 @@ std::string Tag::getName() const { return m_Name; } + void Tag::setName(std::string value) { m_Name = value; } +std::vector createTagVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(Tag(child.second)); + } + + return vec; +} + } } } diff --git a/samples/server/petstore/cpp-restbed/model/Tag.h b/samples/server/petstore/cpp-restbed/model/Tag.h index b40aa2c7e15..82de314f729 100644 --- a/samples/server/petstore/cpp-restbed/model/Tag.h +++ b/samples/server/petstore/cpp-restbed/model/Tag.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 5.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator unset. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -23,6 +23,7 @@ #include #include +#include #include namespace org { @@ -36,8 +37,9 @@ namespace model { class Tag { public: - Tag(); - virtual ~Tag(); + Tag() = default; + explicit Tag(boost::property_tree::ptree const& pt); + virtual ~Tag() = default; std::string toJsonString(bool prettyJson = false); void fromJsonString(std::string const& jsonString); @@ -58,11 +60,25 @@ public: /// std::string getName() const; void setName(std::string value); + protected: - int64_t m_Id; - std::string m_Name; + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string toJsonString_internal(bool prettyJson = false); + virtual void fromJsonString_internal(std::string const& jsonString); + virtual boost::property_tree::ptree toPropertyTree_internal(); + virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); + + +protected: + int64_t m_Id = 0L; + std::string m_Name = ""; }; +std::vector createTagVectorFromJsonString(const std::string& json); + } } } diff --git a/samples/server/petstore/cpp-restbed/model/User.cpp b/samples/server/petstore/cpp-restbed/model/User.cpp index 65161d2fb27..bf913818196 100644 --- a/samples/server/petstore/cpp-restbed/model/User.cpp +++ b/samples/server/petstore/cpp-restbed/model/User.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 5.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator unset. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -15,7 +15,9 @@ #include "User.h" #include +#include #include +#include #include #include @@ -28,30 +30,39 @@ namespace openapitools { namespace server { namespace model { -User::User() +User::User(boost::property_tree::ptree const& pt) { - m_Id = 0L; - m_Username = ""; - m_FirstName = ""; - m_LastName = ""; - m_Email = ""; - m_Password = ""; - m_Phone = ""; - m_UserStatus = 0; + fromPropertyTree(pt); } -User::~User() +std::string User::toJsonString(bool prettyJson /* = false */) { + return toJsonString_internal(prettyJson); } -std::string User::toJsonString(bool prettyJson) +void User::fromJsonString(std::string const& jsonString) +{ + fromJsonString_internal(jsonString); +} + +boost::property_tree::ptree User::toPropertyTree() +{ + return toPropertyTree_internal(); +} + +void User::fromPropertyTree(boost::property_tree::ptree const& pt) +{ + fromPropertyTree_internal(pt); +} + +std::string User::toJsonString_internal(bool prettyJson) { std::stringstream ss; write_json(ss, this->toPropertyTree(), prettyJson); return ss.str(); } -void User::fromJsonString(std::string const& jsonString) +void User::fromJsonString_internal(std::string const& jsonString) { std::stringstream ss(jsonString); ptree pt; @@ -59,7 +70,7 @@ void User::fromJsonString(std::string const& jsonString) this->fromPropertyTree(pt); } -ptree User::toPropertyTree() +ptree User::toPropertyTree_internal() { ptree pt; ptree tmp_node; @@ -74,7 +85,7 @@ ptree User::toPropertyTree() return pt; } -void User::fromPropertyTree(ptree const &pt) +void User::fromPropertyTree_internal(ptree const &pt) { ptree tmp_node; m_Id = pt.get("id", 0L); @@ -91,6 +102,7 @@ int64_t User::getId() const { return m_Id; } + void User::setId(int64_t value) { m_Id = value; @@ -99,6 +111,7 @@ std::string User::getUsername() const { return m_Username; } + void User::setUsername(std::string value) { m_Username = value; @@ -107,6 +120,7 @@ std::string User::getFirstName() const { return m_FirstName; } + void User::setFirstName(std::string value) { m_FirstName = value; @@ -115,6 +129,7 @@ std::string User::getLastName() const { return m_LastName; } + void User::setLastName(std::string value) { m_LastName = value; @@ -123,6 +138,7 @@ std::string User::getEmail() const { return m_Email; } + void User::setEmail(std::string value) { m_Email = value; @@ -131,6 +147,7 @@ std::string User::getPassword() const { return m_Password; } + void User::setPassword(std::string value) { m_Password = value; @@ -139,6 +156,7 @@ std::string User::getPhone() const { return m_Phone; } + void User::setPhone(std::string value) { m_Phone = value; @@ -147,11 +165,26 @@ int32_t User::getUserStatus() const { return m_UserStatus; } + void User::setUserStatus(int32_t value) { m_UserStatus = value; } +std::vector createUserVectorFromJsonString(const std::string& json) +{ + std::stringstream sstream(json); + boost::property_tree::ptree pt; + boost::property_tree::json_parser::read_json(sstream,pt); + + auto vec = std::vector(); + for (const auto& child: pt) { + vec.emplace_back(User(child.second)); + } + + return vec; +} + } } } diff --git a/samples/server/petstore/cpp-restbed/model/User.h b/samples/server/petstore/cpp-restbed/model/User.h index c785184e706..dcc3902dad0 100644 --- a/samples/server/petstore/cpp-restbed/model/User.h +++ b/samples/server/petstore/cpp-restbed/model/User.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 5.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator unset. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -23,6 +23,7 @@ #include #include +#include #include namespace org { @@ -36,8 +37,9 @@ namespace model { class User { public: - User(); - virtual ~User(); + User() = default; + explicit User(boost::property_tree::ptree const& pt); + virtual ~User() = default; std::string toJsonString(bool prettyJson = false); void fromJsonString(std::string const& jsonString); @@ -94,17 +96,31 @@ public: /// int32_t getUserStatus() const; void setUserStatus(int32_t value); + protected: - int64_t m_Id; - std::string m_Username; - std::string m_FirstName; - std::string m_LastName; - std::string m_Email; - std::string m_Password; - std::string m_Phone; - int32_t m_UserStatus; + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string toJsonString_internal(bool prettyJson = false); + virtual void fromJsonString_internal(std::string const& jsonString); + virtual boost::property_tree::ptree toPropertyTree_internal(); + virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt); + + +protected: + int64_t m_Id = 0L; + std::string m_Username = ""; + std::string m_FirstName = ""; + std::string m_LastName = ""; + std::string m_Email = ""; + std::string m_Password = ""; + std::string m_Phone = ""; + int32_t m_UserStatus = 0; }; +std::vector createUserVectorFromJsonString(const std::string& json); + } } }