code
stringlengths
1
1.05M
repo_name
stringlengths
7
65
path
stringlengths
2
255
language
stringclasses
236 values
license
stringclasses
24 values
size
int64
1
1.05M
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "StreamingBody.hpp" namespace oatpp { namespace web { namespace protocol { namespace http { namespace outgoing { StreamingBody::StreamingBody(const std::shared_ptr<data::stream::ReadCallback>& readCallback) : m_readCallback(readCallback) {} v_io_size StreamingBody::read(void *buffer, v_buff_size count, async::Action& action) { return m_readCallback->read(buffer, count, action); } void StreamingBody::declareHeaders(Headers& headers) { (void) headers; // DO NOTHING } p_char8 StreamingBody::getKnownData() { return nullptr; } v_int64 StreamingBody::getKnownSize() { return -1; } }}}}}
vincent-in-black-sesame/oat
src/oatpp/web/protocol/http/outgoing/StreamingBody.cpp
C++
apache-2.0
1,612
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_web_protocol_http_outgoing_StreamingBody_hpp #define oatpp_web_protocol_http_outgoing_StreamingBody_hpp #include "./Body.hpp" namespace oatpp { namespace web { namespace protocol { namespace http { namespace outgoing { /** * Abstract body for streaming data. */ class StreamingBody : public Body { private: std::shared_ptr<data::stream::ReadCallback> m_readCallback; public: /** * Constructor. * @param readCallback */ StreamingBody(const std::shared_ptr<data::stream::ReadCallback>& readCallback); /** * Proxy method to readCallback::read(). * @param buffer - pointer to buffer. * @param count - size of the buffer in bytes. * @param action - async specific action. If action is NOT &id:oatpp::async::Action::TYPE_NONE;, then * caller MUST return this action on coroutine iteration. * @return - actual number of bytes written to buffer. 0 - to indicate end-of-file. */ v_io_size read(void *buffer, v_buff_size count, async::Action& action) override; /** * Override this method to declare additional headers. * @param headers - &id:oatpp::web::protocol::http::Headers;. */ void declareHeaders(Headers& headers) override; /** * Pointer to the body known data. * @return - `nullptr`. */ p_char8 getKnownData() override; /** * Return known size of the body. * @return - `-1`. */ v_int64 getKnownSize() override; }; }}}}} #endif // oatpp_web_protocol_http_outgoing_StreamingBody_hpp
vincent-in-black-sesame/oat
src/oatpp/web/protocol/http/outgoing/StreamingBody.hpp
C++
apache-2.0
2,481
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "CommunicationUtils.hpp" namespace oatpp { namespace web { namespace protocol { namespace http { namespace utils { void CommunicationUtils::considerConnectionState(const std::shared_ptr<protocol::http::incoming::Request>& request, const std::shared_ptr<protocol::http::outgoing::Response>& response, ConnectionState& connectionState) { if(connectionState != ConnectionState::ALIVE) { return; } auto outState = response->getHeaders().getAsMemoryLabel<oatpp::data::share::StringKeyLabelCI>(Header::CONNECTION); if(outState && outState == Header::Value::CONNECTION_UPGRADE) { connectionState = ConnectionState::DELEGATED; return; } if(request) { /* If the connection header is present in the request and its value isn't keep-alive, then close */ auto connection = request->getHeaders().getAsMemoryLabel<oatpp::data::share::StringKeyLabelCI>(Header::CONNECTION); if(connection) { if(connection != Header::Value::CONNECTION_KEEP_ALIVE) { connectionState = ConnectionState::CLOSING; } return; } /* If protocol == HTTP/1.1 */ /* Set HTTP/1.1 default Connection header value (Keep-Alive), if no Connection header present in response. */ /* Set keep-alive to value specified in response otherwise */ auto& protocol = request->getStartingLine().protocol; if(protocol && oatpp::utils::String::compareCI_ASCII(protocol.getData(), protocol.getSize(), "HTTP/1.1", 8) == 0) { if(outState && outState != Header::Value::CONNECTION_KEEP_ALIVE) { connectionState = ConnectionState::CLOSING; } return; } } /* If protocol != HTTP/1.1 */ /* Set default Connection header value (Close), if no Connection header present in response. */ /* Set keep-alive to value specified in response otherwise */ if(!outState || outState != Header::Value::CONNECTION_KEEP_ALIVE) { connectionState = ConnectionState::CLOSING; } return; } std::shared_ptr<encoding::EncoderProvider> CommunicationUtils::selectEncoder(const std::shared_ptr<http::incoming::Request>& request, const std::shared_ptr<http::encoding::ProviderCollection>& providers) { if(providers && request) { auto suggested = request->getHeaders().getAsMemoryLabel<oatpp::data::share::StringKeyLabel>(Header::ACCEPT_ENCODING); if(suggested) { http::HeaderValueData valueData; http::Parser::parseHeaderValueData(valueData, suggested, ','); return providers->get(valueData.tokens); } } return nullptr; } }}}}}
vincent-in-black-sesame/oat
src/oatpp/web/protocol/http/utils/CommunicationUtils.cpp
C++
apache-2.0
3,671
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_web_protocol_http_utils_CommunicationUtils_hpp #define oatpp_web_protocol_http_utils_CommunicationUtils_hpp #include "oatpp/web/protocol/http/incoming/Request.hpp" #include "oatpp/web/protocol/http/outgoing/Response.hpp" #include "oatpp/web/protocol/http/encoding/ProviderCollection.hpp" namespace oatpp { namespace web { namespace protocol { namespace http { namespace utils { /** * Helper class for communication utils. */ class CommunicationUtils { public: enum class ConnectionState : int { ALIVE = 0, // Continue processing connection. DELEGATED = 1, // Stop current connection processing as connection was delegated to other processor. CLOSING = 2, // Move connection to "closing" pool. DEAD = 3 // Drop immediately }; public: /** * Consider keep connection alive taking into account request headers, response headers and protocol version.<br> * Corresponding header will be set to response if not existed before. <br> * @param request - `std::shared_ptr` to &id:oatpp::web::protocol::http::incoming::Request; * @param response - `std::shared_ptr` to &id:oatpp::web::protocol::http::outgoing::Response; * @param connectionState */ static void considerConnectionState(const std::shared_ptr<protocol::http::incoming::Request>& request, const std::shared_ptr<protocol::http::outgoing::Response>& response, ConnectionState& connectionState); static std::shared_ptr<encoding::EncoderProvider> selectEncoder(const std::shared_ptr<http::incoming::Request>& request, const std::shared_ptr<http::encoding::ProviderCollection>& providers); }; }}}}} #endif /* oatpp_web_protocol_http_utils_CommunicationUtils_hpp */
vincent-in-black-sesame/oat
src/oatpp/web/protocol/http/utils/CommunicationUtils.hpp
C++
apache-2.0
2,823
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "./AsyncHttpConnectionHandler.hpp" namespace oatpp { namespace web { namespace server { void AsyncHttpConnectionHandler::onTaskStart(const provider::ResourceHandle<data::stream::IOStream>& connection) { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_connectionsLock); m_connections.insert({(v_uint64) connection.object.get(), connection}); if(!m_continue.load()) { connection.invalidator->invalidate(connection.object); } } void AsyncHttpConnectionHandler::onTaskEnd(const provider::ResourceHandle<data::stream::IOStream>& connection) { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_connectionsLock); m_connections.erase((v_uint64) connection.object.get()); } void AsyncHttpConnectionHandler::invalidateAllConnections() { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_connectionsLock); for(auto& c : m_connections) { const auto& handle = c.second; handle.invalidator->invalidate(handle.object); } } v_uint64 AsyncHttpConnectionHandler::getConnectionsCount() { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_connectionsLock); return m_connections.size(); } AsyncHttpConnectionHandler::AsyncHttpConnectionHandler(const std::shared_ptr<HttpProcessor::Components>& components, v_int32 threadCount) : m_executor(std::make_shared<oatpp::async::Executor>(threadCount)) , m_components(components) , m_continue(true) { m_executor->detach(); } AsyncHttpConnectionHandler::AsyncHttpConnectionHandler(const std::shared_ptr<HttpProcessor::Components>& components, const std::shared_ptr<oatpp::async::Executor>& executor) : m_executor(executor) , m_components(components) , m_continue(true) {} std::shared_ptr<AsyncHttpConnectionHandler> AsyncHttpConnectionHandler::createShared(const std::shared_ptr<HttpRouter>& router, v_int32 threadCount){ return std::make_shared<AsyncHttpConnectionHandler>(router, threadCount); } std::shared_ptr<AsyncHttpConnectionHandler> AsyncHttpConnectionHandler::createShared(const std::shared_ptr<HttpRouter>& router, const std::shared_ptr<oatpp::async::Executor>& executor){ return std::make_shared<AsyncHttpConnectionHandler>(router, executor); } void AsyncHttpConnectionHandler::setErrorHandler(const std::shared_ptr<handler::ErrorHandler>& errorHandler){ m_components->errorHandler = errorHandler; if(!m_components->errorHandler) { m_components->errorHandler = handler::DefaultErrorHandler::createShared(); } } void AsyncHttpConnectionHandler::addRequestInterceptor(const std::shared_ptr<interceptor::RequestInterceptor>& interceptor) { m_components->requestInterceptors.push_back(interceptor); } void AsyncHttpConnectionHandler::addResponseInterceptor(const std::shared_ptr<interceptor::ResponseInterceptor>& interceptor) { m_components->responseInterceptors.push_back(interceptor); } void AsyncHttpConnectionHandler::handleConnection(const provider::ResourceHandle<IOStream>& connection, const std::shared_ptr<const ParameterMap>& params) { (void)params; if (m_continue.load()) { connection.object->setOutputStreamIOMode(oatpp::data::stream::IOMode::ASYNCHRONOUS); connection.object->setInputStreamIOMode(oatpp::data::stream::IOMode::ASYNCHRONOUS); m_executor->execute<HttpProcessor::Coroutine>(m_components, connection, this); } } void AsyncHttpConnectionHandler::stop() { m_continue.store(false); /* invalidate all connections */ invalidateAllConnections(); /* Wait until all connection-threads are done */ while(getConnectionsCount() > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } }}}
vincent-in-black-sesame/oat
src/oatpp/web/server/AsyncHttpConnectionHandler.cpp
C++
apache-2.0
4,756
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_web_server_AsyncHttpConnectionHandler_hpp #define oatpp_web_server_AsyncHttpConnectionHandler_hpp #include "oatpp/web/server/HttpProcessor.hpp" #include "oatpp/network/ConnectionHandler.hpp" #include "oatpp/core/async/Executor.hpp" #include "oatpp/core/concurrency/SpinLock.hpp" #include <unordered_map> namespace oatpp { namespace web { namespace server { /** * Asynchronous &id:oatpp::network::ConnectionHandler; for handling http communication. */ class AsyncHttpConnectionHandler : public base::Countable, public network::ConnectionHandler, public HttpProcessor::TaskProcessingListener { protected: void onTaskStart(const provider::ResourceHandle<data::stream::IOStream>& connection) override; void onTaskEnd(const provider::ResourceHandle<data::stream::IOStream>& connection) override; void invalidateAllConnections(); private: std::shared_ptr<oatpp::async::Executor> m_executor; std::shared_ptr<HttpProcessor::Components> m_components; std::atomic_bool m_continue; std::unordered_map<v_uint64, provider::ResourceHandle<data::stream::IOStream>> m_connections; oatpp::concurrency::SpinLock m_connectionsLock; public: /** * Constructor. * @param components - &id:oatpp::web::server::HttpProcessor::Components;. * @param threadCount - number of threads. */ AsyncHttpConnectionHandler(const std::shared_ptr<HttpProcessor::Components>& components, v_int32 threadCount = oatpp::async::Executor::VALUE_SUGGESTED); /** * Constructor. * @param components - &id:oatpp::web::server::HttpProcessor::Components;. * @param executor - &id:oatpp::async::Executor;. */ AsyncHttpConnectionHandler(const std::shared_ptr<HttpProcessor::Components>& components, const std::shared_ptr<oatpp::async::Executor>& executor); /** * Constructor. * @param router - &id:oatpp::web::server::HttpRouter; to route incoming requests. * @param threadCount - number of threads. */ AsyncHttpConnectionHandler(const std::shared_ptr<HttpRouter>& router, v_int32 threadCount = oatpp::async::Executor::VALUE_SUGGESTED) : AsyncHttpConnectionHandler(std::make_shared<HttpProcessor::Components>(router), threadCount) {} /** * Constructor. * @param router - &id:oatpp::web::server::HttpRouter; to route incoming requests. * @param executor - &id:oatpp::async::Executor;. */ AsyncHttpConnectionHandler(const std::shared_ptr<HttpRouter>& router, const std::shared_ptr<oatpp::async::Executor>& executor) : AsyncHttpConnectionHandler(std::make_shared<HttpProcessor::Components>(router), executor) {} /** * Constructor. * @param router - &id:oatpp::web::server::HttpRouter; to route incoming requests. * @param config - &id:oatpp::web::server::HttpProcessor::Config;. * @param threadCount - number of threads. */ AsyncHttpConnectionHandler(const std::shared_ptr<HttpRouter>& router, const std::shared_ptr<HttpProcessor::Config>& config, v_int32 threadCount = oatpp::async::Executor::VALUE_SUGGESTED) : AsyncHttpConnectionHandler(std::make_shared<HttpProcessor::Components>(router, config), threadCount) {} /** * Constructor. * @param router - &id:oatpp::web::server::HttpRouter; to route incoming requests. * @param config - &id:oatpp::web::server::HttpProcessor::Config;. * @param executor - &id:oatpp::async::Executor;. */ AsyncHttpConnectionHandler(const std::shared_ptr<HttpRouter>& router, const std::shared_ptr<HttpProcessor::Config>& config, const std::shared_ptr<oatpp::async::Executor>& executor) : AsyncHttpConnectionHandler(std::make_shared<HttpProcessor::Components>(router, config), executor) {} public: static std::shared_ptr<AsyncHttpConnectionHandler> createShared(const std::shared_ptr<HttpRouter>& router, v_int32 threadCount = oatpp::async::Executor::VALUE_SUGGESTED); static std::shared_ptr<AsyncHttpConnectionHandler> createShared(const std::shared_ptr<HttpRouter>& router, const std::shared_ptr<oatpp::async::Executor>& executor); void setErrorHandler(const std::shared_ptr<handler::ErrorHandler>& errorHandler); /** * Add request interceptor. Request interceptors are called before routing happens. * If multiple interceptors set then the order of interception is the same as the order of calls to `addRequestInterceptor`. * @param interceptor - &id:oatpp::web::server::interceptor::RequestInterceptor;. */ void addRequestInterceptor(const std::shared_ptr<interceptor::RequestInterceptor>& interceptor); /** * Add response interceptor. * If multiple interceptors set then the order of interception is the same as the order of calls to `addResponseInterceptor`. * @param interceptor - &id:oatpp::web::server::interceptor::RequestInterceptor;. */ void addResponseInterceptor(const std::shared_ptr<interceptor::ResponseInterceptor>& interceptor); void handleConnection(const provider::ResourceHandle<IOStream>& connection, const std::shared_ptr<const ParameterMap>& params) override; /** * Will call m_executor.stop() */ void stop() override; /** * Get connections count. * @return */ v_uint64 getConnectionsCount(); }; }}} #endif /* oatpp_web_server_AsyncHttpConnectionHandler_hpp */
vincent-in-black-sesame/oat
src/oatpp/web/server/AsyncHttpConnectionHandler.hpp
C++
apache-2.0
6,488
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "./HttpConnectionHandler.hpp" #include "oatpp/web/protocol/http/incoming/Request.hpp" #include "oatpp/web/protocol/http/Http.hpp" #include "oatpp/core/concurrency/Thread.hpp" #include "oatpp/core/data/buffer/IOBuffer.hpp" #include "oatpp/core/data/stream/BufferStream.hpp" #include "oatpp/core/data/stream/StreamBufferedProxy.hpp" namespace oatpp { namespace web { namespace server { void HttpConnectionHandler::onTaskStart(const provider::ResourceHandle<data::stream::IOStream>& connection) { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_connectionsLock); m_connections.insert({(v_uint64) connection.object.get(), connection}); if(!m_continue.load()) { connection.invalidator->invalidate(connection.object); } } void HttpConnectionHandler::onTaskEnd(const provider::ResourceHandle<data::stream::IOStream>& connection) { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_connectionsLock); m_connections.erase((v_uint64) connection.object.get()); } void HttpConnectionHandler::invalidateAllConnections() { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_connectionsLock); for(auto& c : m_connections) { const auto& handle = c.second; handle.invalidator->invalidate(handle.object); } } v_uint64 HttpConnectionHandler::getConnectionsCount() { std::lock_guard<oatpp::concurrency::SpinLock> lock(m_connectionsLock); return m_connections.size(); } HttpConnectionHandler::HttpConnectionHandler(const std::shared_ptr<HttpProcessor::Components>& components) : m_components(components) , m_continue(true) {} std::shared_ptr<HttpConnectionHandler> HttpConnectionHandler::createShared(const std::shared_ptr<HttpRouter>& router){ return std::make_shared<HttpConnectionHandler>(router); } void HttpConnectionHandler::setErrorHandler(const std::shared_ptr<handler::ErrorHandler>& errorHandler){ m_components->errorHandler = errorHandler; if(!m_components->errorHandler) { m_components->errorHandler = handler::DefaultErrorHandler::createShared(); } } void HttpConnectionHandler::addRequestInterceptor(const std::shared_ptr<interceptor::RequestInterceptor>& interceptor) { m_components->requestInterceptors.push_back(interceptor); } void HttpConnectionHandler::addResponseInterceptor(const std::shared_ptr<interceptor::ResponseInterceptor>& interceptor) { m_components->responseInterceptors.push_back(interceptor); } void HttpConnectionHandler::handleConnection(const provider::ResourceHandle<data::stream::IOStream>& connection, const std::shared_ptr<const ParameterMap>& params) { (void)params; if (m_continue.load()) { connection.object->setOutputStreamIOMode(oatpp::data::stream::IOMode::BLOCKING); connection.object->setInputStreamIOMode(oatpp::data::stream::IOMode::BLOCKING); /* Create working thread */ std::thread thread(&HttpProcessor::Task::run, std::move(HttpProcessor::Task(m_components, connection, this))); /* Get hardware concurrency -1 in order to have 1cpu free of workers. */ v_int32 concurrency = oatpp::concurrency::getHardwareConcurrency(); if (concurrency > 1) { concurrency -= 1; } /* Set thread affinity group CPUs [0..cpu_count - 1]. Leave one cpu free of workers */ oatpp::concurrency::setThreadAffinityToCpuRange(thread.native_handle(), 0, concurrency - 1 /* -1 because 0-based index */); thread.detach(); } } void HttpConnectionHandler::stop() { m_continue.store(false); /* invalidate all connections */ invalidateAllConnections(); /* Wait until all connection-threads are done */ while(getConnectionsCount() > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } }}}
vincent-in-black-sesame/oat
src/oatpp/web/server/HttpConnectionHandler.cpp
C++
apache-2.0
4,827
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_web_server_HttpConnectionHandler_hpp #define oatpp_web_server_HttpConnectionHandler_hpp #include "oatpp/web/server/HttpProcessor.hpp" #include "oatpp/network/ConnectionHandler.hpp" #include "oatpp/core/concurrency/SpinLock.hpp" #include <unordered_map> namespace oatpp { namespace web { namespace server { /** * Simple ConnectionHandler (&id:oatpp::network::ConnectionHandler;) for handling HTTP communication. <br> * Will create one thread per each connection to handle communication. */ class HttpConnectionHandler : public base::Countable, public network::ConnectionHandler, public HttpProcessor::TaskProcessingListener { protected: void onTaskStart(const provider::ResourceHandle<data::stream::IOStream>& connection) override; void onTaskEnd(const provider::ResourceHandle<data::stream::IOStream>& connection) override; void invalidateAllConnections(); private: std::shared_ptr<HttpProcessor::Components> m_components; std::atomic_bool m_continue; std::unordered_map<v_uint64, provider::ResourceHandle<data::stream::IOStream>> m_connections; oatpp::concurrency::SpinLock m_connectionsLock; public: /** * Constructor. * @param components - &id:oatpp::web::server::HttpProcessor::Components;. */ HttpConnectionHandler(const std::shared_ptr<HttpProcessor::Components>& components); /** * Constructor. * @param router - &id:oatpp::web::server::HttpRouter; to route incoming requests. */ HttpConnectionHandler(const std::shared_ptr<HttpRouter>& router) : HttpConnectionHandler(std::make_shared<HttpProcessor::Components>(router)) {} /** * Constructor. * @param router - &id:oatpp::web::server::HttpRouter; to route incoming requests. * @param config - &id:oatpp::web::server::HttpProcessor::Config;. */ HttpConnectionHandler(const std::shared_ptr<HttpRouter>& router, const std::shared_ptr<HttpProcessor::Config>& config) : HttpConnectionHandler(std::make_shared<HttpProcessor::Components>(router, config)) {} public: /** * Create shared HttpConnectionHandler. * @param router - &id:oatpp::web::server::HttpRouter; to route incoming requests. * @return - `std::shared_ptr` to HttpConnectionHandler. */ static std::shared_ptr<HttpConnectionHandler> createShared(const std::shared_ptr<HttpRouter>& router); /** * Set root error handler for all requests coming through this Connection Handler. * All unhandled errors will be handled by this error handler. * @param errorHandler - &id:oatpp::web::server::handler::ErrorHandler;. */ void setErrorHandler(const std::shared_ptr<handler::ErrorHandler>& errorHandler); /** * Add request interceptor. Request interceptors are called before routing happens. * If multiple interceptors set then the order of interception is the same as the order of calls to `addRequestInterceptor`. * @param interceptor - &id:oatpp::web::server::interceptor::RequestInterceptor;. */ void addRequestInterceptor(const std::shared_ptr<interceptor::RequestInterceptor>& interceptor); /** * Add response interceptor. * If multiple interceptors set then the order of interception is the same as the order of calls to `addResponseInterceptor`. * @param interceptor - &id:oatpp::web::server::interceptor::RequestInterceptor;. */ void addResponseInterceptor(const std::shared_ptr<interceptor::ResponseInterceptor>& interceptor); /** * Implementation of &id:oatpp::network::ConnectionHandler::handleConnection;. * @param connection - &id:oatpp::data::stream::IOStream; representing connection. */ void handleConnection(const provider::ResourceHandle<IOStream>& connection, const std::shared_ptr<const ParameterMap>& params) override; /** * Tell all worker threads to exit when done. */ void stop() override; /** * Get connections count. * @return */ v_uint64 getConnectionsCount(); }; }}} #endif /* oatpp_web_server_HttpConnectionHandler_hpp */
vincent-in-black-sesame/oat
src/oatpp/web/server/HttpConnectionHandler.hpp
C++
apache-2.0
5,010
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "HttpProcessor.hpp" #include "oatpp/web/protocol/http/incoming/SimpleBodyDecoder.hpp" #include "oatpp/core/data/stream/BufferStream.hpp" namespace oatpp { namespace web { namespace server { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Components HttpProcessor::Components::Components(const std::shared_ptr<HttpRouter>& pRouter, const std::shared_ptr<protocol::http::encoding::ProviderCollection>& pContentEncodingProviders, const std::shared_ptr<const oatpp::web::protocol::http::incoming::BodyDecoder>& pBodyDecoder, const std::shared_ptr<handler::ErrorHandler>& pErrorHandler, const RequestInterceptors& pRequestInterceptors, const ResponseInterceptors& pResponseInterceptors, const std::shared_ptr<Config>& pConfig) : router(pRouter) , contentEncodingProviders(pContentEncodingProviders) , bodyDecoder(pBodyDecoder) , errorHandler(pErrorHandler) , requestInterceptors(pRequestInterceptors) , responseInterceptors(pResponseInterceptors) , config(pConfig) {} HttpProcessor::Components::Components(const std::shared_ptr<HttpRouter>& pRouter) : Components(pRouter, nullptr, std::make_shared<oatpp::web::protocol::http::incoming::SimpleBodyDecoder>(), handler::DefaultErrorHandler::createShared(), {}, {}, std::make_shared<Config>()) {} HttpProcessor::Components::Components(const std::shared_ptr<HttpRouter>& pRouter, const std::shared_ptr<Config>& pConfig) : Components(pRouter, nullptr, std::make_shared<oatpp::web::protocol::http::incoming::SimpleBodyDecoder>(), handler::DefaultErrorHandler::createShared(), {}, {}, pConfig) {} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Other HttpProcessor::ProcessingResources::ProcessingResources(const std::shared_ptr<Components>& pComponents, const provider::ResourceHandle<oatpp::data::stream::IOStream>& pConnection) : components(pComponents) , connection(pConnection) , headersInBuffer(components->config->headersInBufferInitial) , headersOutBuffer(components->config->headersOutBufferInitial) , headersReader(&headersInBuffer, components->config->headersReaderChunkSize, components->config->headersReaderMaxSize) , inStream(data::stream::InputStreamBufferedProxy::createShared(connection.object, std::make_shared<std::string>(data::buffer::IOBuffer::BUFFER_SIZE, 0))) {} std::shared_ptr<protocol::http::outgoing::Response> HttpProcessor::processNextRequest(ProcessingResources& resources, const std::shared_ptr<protocol::http::incoming::Request>& request, ConnectionState& connectionState) { std::shared_ptr<protocol::http::outgoing::Response> response; try{ for(auto& interceptor : resources.components->requestInterceptors) { response = interceptor->intercept(request); if(response) { return response; } } auto route = resources.components->router->getRoute(request->getStartingLine().method, request->getStartingLine().path); if(!route) { data::stream::BufferOutputStream ss; ss << "No mapping for HTTP-method: '" << request->getStartingLine().method.toString() << "', URL: '" << request->getStartingLine().path.toString() << "'"; connectionState = ConnectionState::CLOSING; oatpp::web::protocol::http::HttpError error(protocol::http::Status::CODE_404, ss.toString()); auto ptr = std::make_exception_ptr(error); return resources.components->errorHandler->handleError(ptr); } request->setPathVariables(route.getMatchMap()); return route.getEndpoint()->handle(request); } catch (...) { response = resources.components->errorHandler->handleError(std::current_exception()); connectionState = ConnectionState::CLOSING; } return response; } HttpProcessor::ConnectionState HttpProcessor::processNextRequest(ProcessingResources& resources) { oatpp::web::protocol::http::HttpError::Info error; auto headersReadResult = resources.headersReader.readHeaders(resources.inStream.get(), error); if(error.ioStatus <= 0) { return ConnectionState::DEAD; } ConnectionState connectionState = ConnectionState::ALIVE; std::shared_ptr<protocol::http::incoming::Request> request; std::shared_ptr<protocol::http::outgoing::Response> response; if(error.status.code != 0) { oatpp::web::protocol::http::HttpError httpError(error.status, "Invalid Request Headers"); auto eptr = std::make_exception_ptr(httpError); response = resources.components->errorHandler->handleError(eptr); connectionState = ConnectionState::CLOSING; } else { request = protocol::http::incoming::Request::createShared(resources.connection.object, headersReadResult.startingLine, headersReadResult.headers, resources.inStream, resources.components->bodyDecoder); response = processNextRequest(resources, request, connectionState); try { for (auto& interceptor : resources.components->responseInterceptors) { response = interceptor->intercept(request, response); if (!response) { oatpp::web::protocol::http::HttpError httpError(protocol::http::Status::CODE_500, "Response Interceptor returned an Invalid Response - 'null'"); auto eptr = std::make_exception_ptr(httpError); response = resources.components->errorHandler->handleError(eptr); connectionState = ConnectionState::CLOSING; } } } catch (...) { response = resources.components->errorHandler->handleError(std::current_exception()); connectionState = ConnectionState::CLOSING; } response->putHeaderIfNotExists(protocol::http::Header::SERVER, protocol::http::Header::Value::SERVER); protocol::http::utils::CommunicationUtils::considerConnectionState(request, response, connectionState); switch(connectionState) { case ConnectionState::ALIVE : response->putHeaderIfNotExists(protocol::http::Header::CONNECTION, protocol::http::Header::Value::CONNECTION_KEEP_ALIVE); break; case ConnectionState::CLOSING: case ConnectionState::DEAD: response->putHeaderIfNotExists(protocol::http::Header::CONNECTION, protocol::http::Header::Value::CONNECTION_CLOSE); break; default: break; } } auto contentEncoderProvider = protocol::http::utils::CommunicationUtils::selectEncoder(request, resources.components->contentEncodingProviders); response->send(resources.connection.object.get(), &resources.headersOutBuffer, contentEncoderProvider.get()); /* Delegate connection handling to another handler only after the response is sent to the client */ if(connectionState == ConnectionState::DELEGATED) { auto handler = response->getConnectionUpgradeHandler(); if(handler) { handler->handleConnection(resources.connection, response->getConnectionUpgradeParameters()); connectionState = ConnectionState::DELEGATED; } else { OATPP_LOGW("[oatpp::web::server::HttpProcessor::processNextRequest()]", "Warning. ConnectionUpgradeHandler not set!"); connectionState = ConnectionState::CLOSING; } } return connectionState; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Task HttpProcessor::Task::Task(const std::shared_ptr<Components>& components, const provider::ResourceHandle<oatpp::data::stream::IOStream>& connection, TaskProcessingListener* taskListener) : m_components(components) , m_connection(connection) , m_taskListener(taskListener) { m_taskListener->onTaskStart(m_connection); } HttpProcessor::Task::Task(HttpProcessor::Task &&other) : m_components(std::move(other.m_components)) , m_connection(std::move(other.m_connection)) , m_taskListener(other.m_taskListener) { other.m_taskListener = nullptr; } HttpProcessor::Task::~Task() { if (m_taskListener != nullptr) { m_taskListener->onTaskEnd(m_connection); } } HttpProcessor::Task &HttpProcessor::Task::operator=(HttpProcessor::Task &&other) { m_components = std::move(other.m_components); m_connection = std::move(other.m_connection); m_taskListener = other.m_taskListener; other.m_taskListener = nullptr; return *this; } void HttpProcessor::Task::run(){ m_connection.object->initContexts(); ProcessingResources resources(m_components, m_connection); ConnectionState connectionState; try { do { connectionState = HttpProcessor::processNextRequest(resources); } while (connectionState == ConnectionState::ALIVE); } catch (...) { // DO NOTHING } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // HttpProcessor::Coroutine HttpProcessor::Coroutine::Coroutine(const std::shared_ptr<Components>& components, const provider::ResourceHandle<oatpp::data::stream::IOStream>& connection, TaskProcessingListener* taskListener) : m_components(components) , m_connection(connection) , m_headersInBuffer(components->config->headersInBufferInitial) , m_headersReader(&m_headersInBuffer, components->config->headersReaderChunkSize, components->config->headersReaderMaxSize) , m_headersOutBuffer(std::make_shared<oatpp::data::stream::BufferOutputStream>(components->config->headersOutBufferInitial)) , m_inStream(data::stream::InputStreamBufferedProxy::createShared(m_connection.object, std::make_shared<std::string>(data::buffer::IOBuffer::BUFFER_SIZE, 0))) , m_connectionState(ConnectionState::ALIVE) , m_taskListener(taskListener) { m_taskListener->onTaskStart(m_connection); } HttpProcessor::Coroutine::~Coroutine() { m_taskListener->onTaskEnd(m_connection); } HttpProcessor::Coroutine::Action HttpProcessor::Coroutine::act() { return m_connection.object->initContextsAsync().next(yieldTo(&HttpProcessor::Coroutine::parseHeaders)); } HttpProcessor::Coroutine::Action HttpProcessor::Coroutine::parseHeaders() { return m_headersReader.readHeadersAsync(m_inStream).callbackTo(&HttpProcessor::Coroutine::onHeadersParsed); } oatpp::async::Action HttpProcessor::Coroutine::onHeadersParsed(const RequestHeadersReader::Result& headersReadResult) { m_currentRequest = protocol::http::incoming::Request::createShared(m_connection.object, headersReadResult.startingLine, headersReadResult.headers, m_inStream, m_components->bodyDecoder); for(auto& interceptor : m_components->requestInterceptors) { m_currentResponse = interceptor->intercept(m_currentRequest); if(m_currentResponse) { return yieldTo(&HttpProcessor::Coroutine::onResponseFormed); } } m_currentRoute = m_components->router->getRoute(headersReadResult.startingLine.method.toString(), headersReadResult.startingLine.path.toString()); if(!m_currentRoute) { data::stream::BufferOutputStream ss; ss << "No mapping for HTTP-method: '" << headersReadResult.startingLine.method.toString() << "', URL: '" << headersReadResult.startingLine.path.toString() << "'"; oatpp::web::protocol::http::HttpError error(protocol::http::Status::CODE_404, ss.toString()); auto eptr = std::make_exception_ptr(error); m_currentResponse = m_components->errorHandler->handleError(eptr); m_connectionState = ConnectionState::CLOSING; return yieldTo(&HttpProcessor::Coroutine::onResponseFormed); } m_currentRequest->setPathVariables(m_currentRoute.getMatchMap()); return yieldTo(&HttpProcessor::Coroutine::onRequestFormed); } HttpProcessor::Coroutine::Action HttpProcessor::Coroutine::onRequestFormed() { return m_currentRoute.getEndpoint()->handleAsync(m_currentRequest).callbackTo(&HttpProcessor::Coroutine::onResponse); } HttpProcessor::Coroutine::Action HttpProcessor::Coroutine::onResponse(const std::shared_ptr<protocol::http::outgoing::Response>& response) { m_currentResponse = response; return yieldTo(&HttpProcessor::Coroutine::onResponseFormed); } HttpProcessor::Coroutine::Action HttpProcessor::Coroutine::onResponseFormed() { for(auto& interceptor : m_components->responseInterceptors) { m_currentResponse = interceptor->intercept(m_currentRequest, m_currentResponse); if(!m_currentResponse) { oatpp::web::protocol::http::HttpError error(protocol::http::Status::CODE_500, "Response Interceptor returned an Invalid Response - 'null'"); auto eptr = std::make_exception_ptr(error); m_currentResponse = m_components->errorHandler->handleError(eptr); } } m_currentResponse->putHeaderIfNotExists(protocol::http::Header::SERVER, protocol::http::Header::Value::SERVER); oatpp::web::protocol::http::utils::CommunicationUtils::considerConnectionState(m_currentRequest, m_currentResponse, m_connectionState); switch(m_connectionState) { case ConnectionState::ALIVE : m_currentResponse->putHeaderIfNotExists(protocol::http::Header::CONNECTION, protocol::http::Header::Value::CONNECTION_KEEP_ALIVE); break; case ConnectionState::CLOSING: case ConnectionState::DEAD: m_currentResponse->putHeaderIfNotExists(protocol::http::Header::CONNECTION, protocol::http::Header::Value::CONNECTION_CLOSE); break; default: break; } auto contentEncoderProvider = protocol::http::utils::CommunicationUtils::selectEncoder(m_currentRequest, m_components->contentEncodingProviders); return protocol::http::outgoing::Response::sendAsync(m_currentResponse, m_connection.object, m_headersOutBuffer, contentEncoderProvider) .next(yieldTo(&HttpProcessor::Coroutine::onRequestDone)); } HttpProcessor::Coroutine::Action HttpProcessor::Coroutine::onRequestDone() { switch (m_connectionState) { case ConnectionState::ALIVE: return yieldTo(&HttpProcessor::Coroutine::parseHeaders); /* Delegate connection handling to another handler only after the response is sent to the client */ case ConnectionState::DELEGATED: { auto handler = m_currentResponse->getConnectionUpgradeHandler(); if(handler) { handler->handleConnection(m_connection, m_currentResponse->getConnectionUpgradeParameters()); m_connectionState = ConnectionState::DELEGATED; } else { OATPP_LOGW("[oatpp::web::server::HttpProcessor::Coroutine::onResponseFormed()]", "Warning. ConnectionUpgradeHandler not set!"); m_connectionState = ConnectionState::CLOSING; } break; } default: break; } return finish(); } HttpProcessor::Coroutine::Action HttpProcessor::Coroutine::handleError(Error* error) { if(error) { if(error->is<oatpp::AsyncIOError>()) { auto aioe = static_cast<oatpp::AsyncIOError*>(error); if(aioe->getCode() == oatpp::IOError::BROKEN_PIPE) { return aioe; // do not report BROKEN_PIPE error } } if(m_currentResponse) { //OATPP_LOGE("[oatpp::web::server::HttpProcessor::Coroutine::handleError()]", "Unhandled error. '%s'. Dropping connection", error->what()); return error; } oatpp::web::protocol::http::HttpError httpError(protocol::http::Status::CODE_500, error->what()); auto eptr = std::make_exception_ptr(httpError); m_currentResponse = m_components->errorHandler->handleError(eptr); return yieldTo(&HttpProcessor::Coroutine::onResponseFormed); } return error; } }}}
vincent-in-black-sesame/oat
src/oatpp/web/server/HttpProcessor.cpp
C++
apache-2.0
17,482
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_web_server_HttpProcessor_hpp #define oatpp_web_server_HttpProcessor_hpp #include "./HttpRouter.hpp" #include "./interceptor/RequestInterceptor.hpp" #include "./interceptor/ResponseInterceptor.hpp" #include "./handler/ErrorHandler.hpp" #include "oatpp/web/protocol/http/encoding/ProviderCollection.hpp" #include "oatpp/web/protocol/http/incoming/RequestHeadersReader.hpp" #include "oatpp/web/protocol/http/incoming/Request.hpp" #include "oatpp/web/protocol/http/outgoing/Response.hpp" #include "oatpp/web/protocol/http/utils/CommunicationUtils.hpp" #include "oatpp/core/data/stream/StreamBufferedProxy.hpp" #include "oatpp/core/async/Processor.hpp" namespace oatpp { namespace web { namespace server { /** * HttpProcessor. Helper class to handle HTTP processing. */ class HttpProcessor { public: typedef std::list<std::shared_ptr<web::server::interceptor::RequestInterceptor>> RequestInterceptors; typedef std::list<std::shared_ptr<web::server::interceptor::ResponseInterceptor>> ResponseInterceptors; typedef web::protocol::http::incoming::RequestHeadersReader RequestHeadersReader; typedef protocol::http::utils::CommunicationUtils::ConnectionState ConnectionState; public: /** * Resource config per connection. */ struct Config { /** * Buffer used to read headers in request. Initial size of the buffer. */ v_buff_size headersInBufferInitial = 2048; /** * Buffer used to write headers in response. Initial size of the buffer. */ v_buff_size headersOutBufferInitial = 2048; /** * Size of the chunk used for iterative-read of headers. */ v_buff_size headersReaderChunkSize = 2048; /** * Maximum allowed size of requests headers. The overall size of all headers in the request. */ v_buff_size headersReaderMaxSize = 4096; }; public: /** * Collection of components needed to serve http-connection. */ struct Components { /** * Constructor. * @param pRouter * @param pContentEncodingProviders * @param pBodyDecoder * @param pErrorHandler * @param pRequestInterceptors * @param pConfig */ Components(const std::shared_ptr<HttpRouter>& pRouter, const std::shared_ptr<protocol::http::encoding::ProviderCollection>& pContentEncodingProviders, const std::shared_ptr<const oatpp::web::protocol::http::incoming::BodyDecoder>& pBodyDecoder, const std::shared_ptr<handler::ErrorHandler>& pErrorHandler, const RequestInterceptors& pRequestInterceptors, const ResponseInterceptors& pResponseInterceptors, const std::shared_ptr<Config>& pConfig); /** * Constructor. * @param pRouter */ Components(const std::shared_ptr<HttpRouter>& pRouter); /** * Constructor. * @param pRouter * @param pConfig */ Components(const std::shared_ptr<HttpRouter>& pRouter, const std::shared_ptr<Config>& pConfig); /** * Router to route incoming requests. &id:oatpp::web::server::HttpRouter;. */ std::shared_ptr<HttpRouter> router; /** * Content-encoding providers. &id:oatpp::web::protocol::encoding::ProviderCollection;. */ std::shared_ptr<protocol::http::encoding::ProviderCollection> contentEncodingProviders; /** * Body decoder. &id:oatpp::web::protocol::http::incoming::BodyDecoder;. */ std::shared_ptr<const oatpp::web::protocol::http::incoming::BodyDecoder> bodyDecoder; /** * Error handler. &id:oatpp::web::server::handler::ErrorHandler;. */ std::shared_ptr<handler::ErrorHandler> errorHandler; /** * Collection of request interceptors. &id:oatpp::web::server::interceptor::RequestInterceptor;. */ RequestInterceptors requestInterceptors; /** * Collection of request interceptors. &id:oatpp::web::server::interceptor::ResponseInterceptor;. */ ResponseInterceptors responseInterceptors; /** * Resource allocation config. &l:HttpProcessor::Config;. */ std::shared_ptr<Config> config; }; private: struct ProcessingResources { ProcessingResources(const std::shared_ptr<Components>& pComponents, const provider::ResourceHandle<oatpp::data::stream::IOStream>& pConnection); std::shared_ptr<Components> components; provider::ResourceHandle<oatpp::data::stream::IOStream> connection; oatpp::data::stream::BufferOutputStream headersInBuffer; oatpp::data::stream::BufferOutputStream headersOutBuffer; RequestHeadersReader headersReader; std::shared_ptr<oatpp::data::stream::InputStreamBufferedProxy> inStream; }; static std::shared_ptr<protocol::http::outgoing::Response> processNextRequest(ProcessingResources& resources, const std::shared_ptr<protocol::http::incoming::Request>& request, ConnectionState& connectionState); static ConnectionState processNextRequest(ProcessingResources& resources); public: /** * Listener of the connection processing task. */ class TaskProcessingListener { public: virtual void onTaskStart(const provider::ResourceHandle<data::stream::IOStream>& connection) = 0; virtual void onTaskEnd(const provider::ResourceHandle<data::stream::IOStream>& connection) = 0; }; public: /** * Connection serving task. <br> * Usege example: <br> * `std::thread thread(&HttpProcessor::Task::run, HttpProcessor::Task(components, connection));` */ class Task : public base::Countable { private: std::shared_ptr<Components> m_components; provider::ResourceHandle<oatpp::data::stream::IOStream> m_connection; TaskProcessingListener* m_taskListener; public: /** * Constructor. * @param components - &l:HttpProcessor::Components;. * @param connection - &id:oatpp::data::stream::IOStream;. */ Task(const std::shared_ptr<Components>& components, const provider::ResourceHandle<oatpp::data::stream::IOStream>& connection, TaskProcessingListener* taskListener); Task(const Task&) = delete; Task &operator=(const Task&) = delete; /** * Move-Constructor to correclty count tasks; */ Task(Task &&other); /** * Move-Assignment to correctly count tasks. * @param t * @return */ Task &operator=(Task &&other); /** * Destructor, needed for counting. */ ~Task() override; public: /** * Run loop. */ void run(); }; public: /** * Connection serving coroutiner - &id:oatpp::async::Coroutine;. */ class Coroutine : public oatpp::async::Coroutine<HttpProcessor::Coroutine> { private: std::shared_ptr<Components> m_components; provider::ResourceHandle<oatpp::data::stream::IOStream> m_connection; oatpp::data::stream::BufferOutputStream m_headersInBuffer; RequestHeadersReader m_headersReader; std::shared_ptr<oatpp::data::stream::BufferOutputStream> m_headersOutBuffer; std::shared_ptr<oatpp::data::stream::InputStreamBufferedProxy> m_inStream; ConnectionState m_connectionState; private: oatpp::web::server::HttpRouter::BranchRouter::Route m_currentRoute; std::shared_ptr<protocol::http::incoming::Request> m_currentRequest; std::shared_ptr<protocol::http::outgoing::Response> m_currentResponse; TaskProcessingListener* m_taskListener; public: /** * Constructor. * @param components - &l:HttpProcessor::Components;. * @param connection - &id:oatpp::data::stream::IOStream;. */ Coroutine(const std::shared_ptr<Components>& components, const provider::ResourceHandle<oatpp::data::stream::IOStream>& connection, TaskProcessingListener* taskListener); ~Coroutine() override; Action act() override; Action parseHeaders(); Action onHeadersParsed(const RequestHeadersReader::Result& headersReadResult); Action onRequestFormed(); Action onResponse(const std::shared_ptr<protocol::http::outgoing::Response>& response); Action onResponseFormed(); Action onRequestDone(); Action handleError(Error* error) override; }; }; }}} #endif /* oatpp_web_server_HttpProcessor_hpp */
vincent-in-black-sesame/oat
src/oatpp/web/server/HttpProcessor.hpp
C++
apache-2.0
9,290
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_web_server_HttpRequestHandler_hpp #define oatpp_web_server_HttpRequestHandler_hpp #include "oatpp/web/protocol/http/outgoing/ResponseFactory.hpp" #include "oatpp/web/protocol/http/outgoing/Response.hpp" #include "oatpp/web/protocol/http/incoming/Request.hpp" namespace oatpp { namespace web { namespace server { /** * HTTP request handler. */ class HttpRequestHandler { public: /** * Convenience typedef for &id:oatpp::web::protocol::http::Status;. */ typedef oatpp::web::protocol::http::Status Status; /** * Convenience typedef for &id:oatpp::web::protocol::http::Header;. */ typedef oatpp::web::protocol::http::Header Header; /** * Convenience typedef for &id:oatpp::web::protocol::http::Headers;. */ typedef oatpp::web::protocol::http::Headers Headers; /** * Convenience typedef for &id:oatpp::web::protocol::http::QueryParams;. */ typedef oatpp::web::protocol::http::QueryParams QueryParams; /** * Convenience typedef for &id:oatpp::web::protocol::http::incoming::Request;. */ typedef oatpp::web::protocol::http::incoming::Request IncomingRequest; /** * Convenience typedef for &id:oatpp::web::protocol::http::outgoing::Response;. */ typedef oatpp::web::protocol::http::outgoing::Response OutgoingResponse; /** * Convenience typedef for &id:oatpp::web::protocol::http::outgoing::ResponseFactory;. */ typedef oatpp::web::protocol::http::outgoing::ResponseFactory ResponseFactory; /** * Convenience typedef for &id:oatpp::web::protocol::http::HttpError;. */ typedef oatpp::web::protocol::http::HttpError HttpError; public: /** * Handle incoming http request. <br> * *Implement this method.* * @param request - incoming http request. &id:oatpp::web::protocol::http::incoming::Request;. * @return - outgoing http response. &id:oatpp::web::protocol::http::outgoing::Response;. */ virtual std::shared_ptr<OutgoingResponse> handle(const std::shared_ptr<IncomingRequest>& request) { (void)request; throw HttpError(Status::CODE_501, "Endpoint not implemented."); } /** * Handle incoming http request in Asynchronous manner. <br> * *Implement this method.* * @param request - &id:oatpp::web::protocol::http::incoming::Request;. * @return - &id:oatpp::async::CoroutineStarterForResult; of &id:oatpp::web::protocol::http::outgoing::Response;. */ virtual oatpp::async::CoroutineStarterForResult<const std::shared_ptr<OutgoingResponse>&> handleAsync(const std::shared_ptr<IncomingRequest>& request) { (void)request; throw HttpError(Status::CODE_501, "Asynchronous endpoint not implemented."); } /** * You have to provide a definition for destructors, otherwise its undefined behaviour. */ virtual ~HttpRequestHandler() = default; }; }}} #endif // oatpp_web_server_HttpRequestHandler_hpp
vincent-in-black-sesame/oat
src/oatpp/web/server/HttpRequestHandler.hpp
C++
apache-2.0
3,856
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "HttpRouter.hpp" namespace oatpp { namespace web { namespace server { std::shared_ptr<HttpRouter> HttpRouter::createShared() { return std::make_shared<HttpRouter>(); } void HttpRouter::route(const std::shared_ptr<server::api::Endpoint>& endpoint) { route(endpoint->info()->method, endpoint->info()->path, endpoint->handler); } void HttpRouter::route(const server::api::Endpoints& endpoints) { for(auto& e : endpoints.list) { route(e); } } std::shared_ptr<server::api::ApiController> HttpRouter::addController(const std::shared_ptr<server::api::ApiController>& controller) { m_controllers.push_back(controller); route(controller->getEndpoints()); return controller; } }}}
vincent-in-black-sesame/oat
src/oatpp/web/server/HttpRouter.cpp
C++
apache-2.0
1,700
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_web_server_HttpRouter_hpp #define oatpp_web_server_HttpRouter_hpp #include "./HttpRequestHandler.hpp" #include "oatpp/web/server/api/ApiController.hpp" #include "oatpp/web/server/api/Endpoint.hpp" #include "oatpp/web/url/mapping/Router.hpp" namespace oatpp { namespace web { namespace server { /** * HttpRouter is responsible for routing http requests by method and path-pattern. */ template<typename RouterEndpoint> class HttpRouterTemplate : public oatpp::base::Countable { private: /** * Convenience typedef for &id:oatpp::data::share::StringKeyLabel;. */ typedef data::share::StringKeyLabel StringKeyLabel; public: /** * &id:oatpp::web::url::mapping::Router; */ typedef web::url::mapping::Router<RouterEndpoint> BranchRouter; /** * Http method to &l:HttpRouter::BranchRouter; map. * Meaning that for each http method like ["GET", "POST", ...] there is a separate &l:HttpRouter::BranchRouter;. */ typedef std::unordered_map<StringKeyLabel, std::shared_ptr<BranchRouter>> BranchMap; protected: BranchMap m_branchMap; protected: const std::shared_ptr<BranchRouter>& getBranch(const StringKeyLabel& name){ auto it = m_branchMap.find(name); if(it == m_branchMap.end()){ m_branchMap[name] = BranchRouter::createShared(); } return m_branchMap[name]; } public: /** * Default Constructor. */ HttpRouterTemplate() = default; /** * Create shared HttpRouter. * @return - `std::shared_ptr` to HttpRouter. */ static std::shared_ptr<HttpRouterTemplate> createShared() { return std::make_shared<HttpRouterTemplate>(); } /** * Route URL to Endpoint by method, and pathPattern. * @param method - http method like ["GET", "POST", etc.]. * @param pathPattern - url path pattern. ex.: `"/path/to/resource/with/{param1}/{param2}"`. * @param endpoint - router endpoint. */ void route(const oatpp::String& method, const oatpp::String& pathPattern, const RouterEndpoint& endpoint) { getBranch(method)->route(pathPattern, endpoint); } /** * Resolve http method and path to &id:oatpp::web::url::mapping::Router::Route; * @param method - http method like ["GET", "POST", etc.]. * @param url - url path. "Path" part of url only. * @return - &id:oatpp::web::url::mapping::Router::Route;. */ typename BranchRouter::Route getRoute(const StringKeyLabel& method, const StringKeyLabel& path){ auto it = m_branchMap.find(method); if(it != m_branchMap.end()) { return m_branchMap[method]->getRoute(path); } return typename BranchRouter::Route(); } /** * Print out all router mapping. */ void logRouterMappings() { for(auto it : m_branchMap) { it.second->logRouterMappings(it.first); } } }; /** * Default HttpRouter. */ class HttpRouter : public HttpRouterTemplate<std::shared_ptr<HttpRequestHandler>> { private: std::list<std::shared_ptr<server::api::ApiController>> m_controllers; public: /** * Create shared HttpRouter. * @return */ static std::shared_ptr<HttpRouter> createShared(); using HttpRouterTemplate::route; void route(const std::shared_ptr<server::api::Endpoint>& endpoint); void route(const server::api::Endpoints& endpoints); /** * Add controller and route its' endpoints. * @param controller * @return - `std::shared_ptr` to the controller added. */ std::shared_ptr<server::api::ApiController> addController(const std::shared_ptr<server::api::ApiController>& controller); }; }}} #endif /* oatpp_web_server_HttpRouter_hpp */
vincent-in-black-sesame/oat
src/oatpp/web/server/HttpRouter.hpp
C++
apache-2.0
4,566
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "ApiController.hpp" #include "oatpp/web/server/handler/ErrorHandler.hpp" namespace oatpp { namespace web { namespace server { namespace api { const Endpoints& ApiController::getEndpoints() { return m_endpoints; } void ApiController::setEndpointInfo(const std::string& endpointName, const std::shared_ptr<Endpoint::Info>& info){ m_endpointInfo[endpointName] = info; } std::shared_ptr<Endpoint::Info> ApiController::getEndpointInfo(const std::string& endpointName) { return m_endpointInfo[endpointName]; } void ApiController::setEndpointHandler(const std::string& endpointName, const std::shared_ptr<RequestHandler>& handler) { m_endpointHandlers[endpointName] = handler; } std::shared_ptr<ApiController::RequestHandler> ApiController::getEndpointHandler(const std::string& endpointName) { return m_endpointHandlers[endpointName]; } void ApiController::setErrorHandler(const std::shared_ptr<handler::ErrorHandler>& errorHandler){ m_errorHandler = errorHandler; if(!m_errorHandler) { m_errorHandler = handler::DefaultErrorHandler::createShared(); } } std::shared_ptr<ApiController::OutgoingResponse> ApiController::handleError(const std::exception_ptr& exceptionPtr) const { if(m_errorHandler) { return m_errorHandler->handleError(exceptionPtr); } return nullptr; } void ApiController::setDefaultAuthorizationHandler(const std::shared_ptr<handler::AuthorizationHandler>& authorizationHandler){ m_defaultAuthorizationHandler = authorizationHandler; } std::shared_ptr<handler::AuthorizationHandler> ApiController::getDefaultAuthorizationHandler() { return m_defaultAuthorizationHandler; } std::shared_ptr<handler::AuthorizationObject> ApiController::handleDefaultAuthorization(const String &authHeader) const { if(m_defaultAuthorizationHandler) { return m_defaultAuthorizationHandler->handleAuthorization(authHeader); } // If Authorization is not setup on the server then it's 500 throw oatpp::web::protocol::http::HttpError(Status::CODE_500, "Authorization is not setup."); } const std::shared_ptr<oatpp::data::mapping::ObjectMapper>& ApiController::getDefaultObjectMapper() const { return m_defaultObjectMapper; } // Helper methods std::shared_ptr<ApiController::OutgoingResponse> ApiController::createResponse(const Status& status, const oatpp::String& str) const { return ResponseFactory::createResponse(status, str); } std::shared_ptr<ApiController::OutgoingResponse> ApiController::createResponse(const ApiController::Status &status) const { return ResponseFactory::createResponse(status); } std::shared_ptr<ApiController::OutgoingResponse> ApiController::createDtoResponse(const Status& status, const oatpp::Void& dto, const std::shared_ptr<oatpp::data::mapping::ObjectMapper>& objectMapper) const { return ResponseFactory::createResponse(status, dto, objectMapper); } std::shared_ptr<ApiController::OutgoingResponse> ApiController::createDtoResponse(const Status& status, const oatpp::Void& dto) const { return ResponseFactory::createResponse(status, dto, m_defaultObjectMapper); } }}}}
vincent-in-black-sesame/oat
src/oatpp/web/server/api/ApiController.cpp
C++
apache-2.0
4,396
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_web_server_api_Controller_hpp #define oatpp_web_server_api_Controller_hpp #include "./Endpoint.hpp" #include "oatpp/web/server/handler/AuthorizationHandler.hpp" #include "oatpp/web/server/handler/ErrorHandler.hpp" #include "oatpp/web/server/handler/AuthorizationHandler.hpp" #include "oatpp/web/protocol/http/incoming/Response.hpp" #include "oatpp/web/protocol/http/outgoing/Request.hpp" #include "oatpp/web/protocol/http/outgoing/ResponseFactory.hpp" #include "oatpp/core/utils/ConversionUtils.hpp" #include <list> #include <unordered_map> namespace oatpp { namespace web { namespace server { namespace api { /** * Class responsible for implementation and management of endpoints.<br> * For details see [ApiController](https://oatpp.io/docs/components/api-controller/). */ class ApiController : public oatpp::base::Countable { protected: typedef ApiController __ControllerType; public: /** * Convenience typedef for &id:oatpp::web::protocol::http::outgoing::ResponseFactory;. */ typedef oatpp::web::protocol::http::outgoing::ResponseFactory ResponseFactory; /** * Convenience typedef for &id:oatpp::web::protocol::http::incoming::Request;. */ typedef oatpp::web::protocol::http::incoming::Request IncomingRequest; /** * Convenience typedef for &id:oatpp::web::protocol::http::outgoing::Request;. */ typedef oatpp::web::protocol::http::outgoing::Request OutgoingRequest; /** * Convenience typedef for &id:oatpp::web::protocol::http::incoming::Response;. */ typedef oatpp::web::protocol::http::incoming::Response IncomingResponse; /** * Convenience typedef for &id:oatpp::web::protocol::http::outgoing::Response;. */ typedef oatpp::web::protocol::http::outgoing::Response OutgoingResponse; /** * Convenience typedef for &id:oatpp::web::protocol::http::Status;. */ typedef oatpp::web::protocol::http::Status Status; /** * Convenience typedef for &id:oatpp::web::protocol::http::Header;. */ typedef oatpp::web::protocol::http::Header Header; /** * Convenience typedef for &id:oatpp::web::protocol::http::QueryParams;. */ typedef oatpp::web::protocol::http::QueryParams QueryParams; /** * Convenience typedef for &id:oatpp::web::server::HttpRequestHandler;. */ typedef oatpp::web::server::HttpRequestHandler RequestHandler; /** * Convenience typedef for &id:oatpp::web::server::handler::AuthorizationHandler;. */ typedef oatpp::web::server::handler::AuthorizationHandler AuthorizationHandler; public: /** * Convenience typedef for &id:oatpp::data::mapping::ObjectMapper;. */ typedef oatpp::data::mapping::ObjectMapper ObjectMapper; /** * Convenience typedef for &id:oatpp::data::mapping::type::String;. */ typedef oatpp::String String; /** * Convenience typedef for &id:oatpp::data::mapping::type::Int8;. */ typedef oatpp::Int8 Int8; /** * Convenience typedef for &id:oatpp::data::mapping::type::UInt8;. */ typedef oatpp::UInt8 UInt8; /** * Convenience typedef for &id:oatpp::data::mapping::type::Int16;. */ typedef oatpp::Int16 Int16; /** * Convenience typedef for &id:oatpp::data::mapping::type::UInt16;. */ typedef oatpp::UInt16 UInt16; /** * Convenience typedef for &id:oatpp::data::mapping::type::Int32;. */ typedef oatpp::Int32 Int32; /** * Convenience typedef for &id:oatpp::data::mapping::type::UInt32;. */ typedef oatpp::UInt32 UInt32; /** * Convenience typedef for &id:oatpp::data::mapping::type::Int64;. */ typedef oatpp::Int64 Int64; /** * Convenience typedef for &id:oatpp::data::mapping::type::UInt64;. */ typedef oatpp::UInt64 UInt64; /** * Convenience typedef for &id:oatpp::data::mapping::type::Float32;. */ typedef oatpp::Float32 Float32; /** * Convenience typedef for &id:atpp::data::mapping::type::Float64;. */ typedef oatpp::Float64 Float64; /** * Convenience typedef for &id:oatpp::data::mapping::type::Boolean;. */ typedef oatpp::Boolean Boolean; /* * Convenience typedef for std::function<std::shared_ptr<Endpoint::Info>()>. */ typedef std::function<std::shared_ptr<Endpoint::Info>()> EndpointInfoBuilder; template <class T> using Object = oatpp::Object<T>; template <class T> using List = oatpp::List<T>; template <class Value> using Fields = oatpp::Fields<Value>; template <class T> using Enum = oatpp::data::mapping::type::Enum<T>; protected: /* * Endpoint Coroutine base class */ template<class CoroutineT, class ControllerT> class HandlerCoroutine : public oatpp::async::CoroutineWithResult<CoroutineT, const std::shared_ptr<OutgoingResponse>&> { public: HandlerCoroutine(ControllerT* pController, const std::shared_ptr<IncomingRequest>& pRequest) : controller(pController) , request(pRequest) {} ControllerT* const controller; std::shared_ptr<IncomingRequest> request; }; /* * Handler which subscribes to specific URL in Router and delegates calls endpoints */ template<class T> class Handler : public RequestHandler { public: typedef std::shared_ptr<OutgoingResponse> (T::*Method)(const std::shared_ptr<IncomingRequest>&); typedef oatpp::async::CoroutineStarterForResult<const std::shared_ptr<OutgoingResponse>&> (T::*MethodAsync)(const std::shared_ptr<IncomingRequest>&); private: class ErrorHandlingCoroutine : public oatpp::async::CoroutineWithResult<ErrorHandlingCoroutine, const std::shared_ptr<OutgoingResponse>&> { private: Handler* m_handler; std::shared_ptr<IncomingRequest> m_request; public: ErrorHandlingCoroutine(Handler* handler, const std::shared_ptr<IncomingRequest>& request) : m_handler(handler) , m_request(request) {} async::Action act() override { return (m_handler->m_controller->*m_handler->m_methodAsync)(m_request) .callbackTo(&ErrorHandlingCoroutine::onResponse); } async::Action onResponse(const std::shared_ptr<OutgoingResponse>& response) { return this->_return(response); } async::Action handleError(async::Error* error) override { auto eptr = std::make_exception_ptr(*error); auto response = m_handler->m_controller->m_errorHandler->handleError(eptr); return this->_return(response); } }; private: T* m_controller; Method m_method; MethodAsync m_methodAsync; public: Handler(T* controller, Method method, MethodAsync methodAsync) : m_controller(controller) , m_method(method) , m_methodAsync(methodAsync) {} public: static std::shared_ptr<Handler> createShared(T* controller, Method method, MethodAsync methodAsync){ return std::make_shared<Handler>(controller, method, methodAsync); } std::shared_ptr<OutgoingResponse> handle(const std::shared_ptr<IncomingRequest>& request) override { if(m_method == nullptr) { if(m_methodAsync == nullptr) { throw protocol::http::HttpError(Status::CODE_500, "[ApiController]: Error. Handler method is nullptr.");; } throw protocol::http::HttpError(Status::CODE_500, "[ApiController]: Error. Non-async call to async endpoint.");; } try { return (m_controller->*m_method)(request); } catch (...) { auto response = m_controller->handleError(std::current_exception()); if(response != nullptr) { return response; } throw; } } oatpp::async::CoroutineStarterForResult<const std::shared_ptr<OutgoingResponse>&> handleAsync(const std::shared_ptr<protocol::http::incoming::Request>& request) override { if(m_methodAsync == nullptr) { if(m_method == nullptr) { throw oatpp::web::protocol::http::HttpError(Status::CODE_500, "[ApiController]: Error. Handler method is nullptr."); } throw oatpp::web::protocol::http::HttpError(Status::CODE_500, "[ApiController]: Error. Async call to non-async endpoint."); } if(m_controller->m_errorHandler) { return ErrorHandlingCoroutine::startForResult(this, request); } return (m_controller->*m_methodAsync)(request); } Method setMethod(Method method) { auto prev = m_method; m_method = method; return prev; } Method getMethod() { return m_method; } MethodAsync setMethodAsync(MethodAsync methodAsync) { auto prev = m_methodAsync; m_methodAsync = methodAsync; return prev; } MethodAsync getMethodAsync() { return m_methodAsync; } }; protected: /* * Set endpoint info by endpoint name. (Endpoint name is the 'NAME' parameter of the ENDPOINT macro) * Info should be set before call to addEndpointsToRouter(); */ void setEndpointInfo(const std::string& endpointName, const std::shared_ptr<Endpoint::Info>& info); /* * Get endpoint info by endpoint name. (Endpoint name is the 'NAME' parameter of the ENDPOINT macro) */ std::shared_ptr<Endpoint::Info> getEndpointInfo(const std::string& endpointName); /* * Set endpoint Request handler. * @param endpointName * @param handler */ void setEndpointHandler(const std::string& endpointName, const std::shared_ptr<RequestHandler>& handler); /* * Get endpoint Request handler. * @param endpointName * @return */ std::shared_ptr<RequestHandler> getEndpointHandler(const std::string& endpointName); protected: Endpoints m_endpoints; std::shared_ptr<handler::ErrorHandler> m_errorHandler; std::shared_ptr<handler::AuthorizationHandler> m_defaultAuthorizationHandler; std::shared_ptr<oatpp::data::mapping::ObjectMapper> m_defaultObjectMapper; std::unordered_map<std::string, std::shared_ptr<Endpoint::Info>> m_endpointInfo; std::unordered_map<std::string, std::shared_ptr<RequestHandler>> m_endpointHandlers; const oatpp::String m_routerPrefix; public: ApiController(const std::shared_ptr<oatpp::data::mapping::ObjectMapper>& defaultObjectMapper, const oatpp::String &routerPrefix = nullptr) : m_defaultObjectMapper(defaultObjectMapper) , m_routerPrefix(routerPrefix) {} public: template<class T> static std::shared_ptr<Endpoint> createEndpoint(Endpoints& endpoints, const std::shared_ptr<Handler<T>>& handler, const EndpointInfoBuilder& infoBuilder) { auto endpoint = Endpoint::createShared(handler, infoBuilder); endpoints.append(endpoint); return endpoint; } /** * Get list of Endpoints created via ENDPOINT macro */ const Endpoints& getEndpoints(); /** * Set error handler to handle errors that occur during the endpoint's execution */ void setErrorHandler(const std::shared_ptr<handler::ErrorHandler>& errorHandler); /** * Handle the exception using the registered ErrorHandler or if no handler has been set, uses the DefaultErrorHandler::handleError * @note Does not rethrow an exception anymore, OutgoingResponse has to be returned by the caller! * @note If this handler fails to handle the exception, it will be handled by the connection handlers ErrorHandler. */ std::shared_ptr<OutgoingResponse> handleError(const std::exception_ptr& exceptionPtr) const; /** * [under discussion] * Set authorization handler to handle calls to handleAuthorization. * Must be called before controller is added to a router or swagger-doc if an endpoint uses the AUTHORIZATION macro */ void setDefaultAuthorizationHandler(const std::shared_ptr<handler::AuthorizationHandler>& authorizationHandler); /** * Get authorization handler. * @return */ std::shared_ptr<handler::AuthorizationHandler> getDefaultAuthorizationHandler(); /** * [under discussion] * Do not use it directly. This method is under discussion. * Currently returns AuthorizationObject created by AuthorizationHandler or return DefaultAuthorizationObject by DefaultAuthorizationHandler if AuthorizationHandler is null */ std::shared_ptr<handler::AuthorizationObject> handleDefaultAuthorization(const String &authHeader) const; const std::shared_ptr<oatpp::data::mapping::ObjectMapper>& getDefaultObjectMapper() const; // Helper methods std::shared_ptr<OutgoingResponse> createResponse(const Status& status, const oatpp::String& str) const; std::shared_ptr<OutgoingResponse> createResponse(const Status& status) const; std::shared_ptr<OutgoingResponse> createDtoResponse(const Status& status, const oatpp::Void& dto, const std::shared_ptr<oatpp::data::mapping::ObjectMapper>& objectMapper) const; std::shared_ptr<OutgoingResponse> createDtoResponse(const Status& status, const oatpp::Void& dto) const; public: template<typename T> struct TypeInterpretation { static T fromString(const oatpp::String& typeName, const oatpp::String& text, bool& success) { (void) text; success = false; OATPP_LOGE("[oatpp::web::server::api::ApiController::TypeInterpretation::fromString()]", "Error. No conversion from '%s' to '%s' is defined.", "oatpp::String", typeName->c_str()); throw std::runtime_error("[oatpp::web::server::api::ApiController::TypeInterpretation::fromString()]: Error. " "No conversion from 'oatpp::String' to '" + *typeName + "' is defined. " "Please define type conversion."); } }; }; template<> struct ApiController::TypeInterpretation <oatpp::String> { static oatpp::String fromString(const oatpp::String& typeName, const oatpp::String& text, bool& success) { (void) typeName; success = true; return text; } }; template<> struct ApiController::TypeInterpretation <oatpp::Int8> { static oatpp::Int8 fromString(const oatpp::String& typeName, const oatpp::String& text, bool& success) { (void) typeName; //TODO: check the range and perhaps throw an exception if the variable doesn't fit return static_cast<Int8::UnderlyingType>(utils::conversion::strToInt32(text, success)); } }; template<> struct ApiController::TypeInterpretation <oatpp::UInt8> { static oatpp::UInt8 fromString(const oatpp::String& typeName, const oatpp::String& text, bool& success) { (void) typeName; //TODO: check the range and perhaps throw an exception if the variable doesn't fit return static_cast<UInt8::UnderlyingType>(utils::conversion::strToUInt32(text, success)); } }; template<> struct ApiController::TypeInterpretation <oatpp::Int16> { static oatpp::Int16 fromString(const oatpp::String& typeName, const oatpp::String& text, bool& success) { (void) typeName; //TODO: check the range and perhaps throw an exception if the variable doesn't fit return static_cast<Int16::UnderlyingType>(utils::conversion::strToInt32(text, success)); } }; template<> struct ApiController::TypeInterpretation <oatpp::UInt16> { static oatpp::UInt16 fromString(const oatpp::String& typeName, const oatpp::String& text, bool& success) { (void) typeName; //TODO: check the range and perhaps throw an exception if the variable doesn't fit return static_cast<UInt16::UnderlyingType>(utils::conversion::strToUInt32(text, success)); } }; template<> struct ApiController::TypeInterpretation <oatpp::Int32> { static oatpp::Int32 fromString(const oatpp::String& typeName, const oatpp::String& text, bool& success) { (void) typeName; return utils::conversion::strToInt32(text, success); } }; template<> struct ApiController::TypeInterpretation <oatpp::UInt32> { static oatpp::UInt32 fromString(const oatpp::String& typeName, const oatpp::String& text, bool& success) { (void) typeName; return utils::conversion::strToUInt32(text, success); } }; template<> struct ApiController::TypeInterpretation <oatpp::Int64> { static oatpp::Int64 fromString(const oatpp::String& typeName, const oatpp::String& text, bool& success) { (void) typeName; return utils::conversion::strToInt64(text, success); } }; template<> struct ApiController::TypeInterpretation <oatpp::UInt64> { static oatpp::UInt64 fromString(const oatpp::String& typeName, const oatpp::String& text, bool& success) { (void) typeName; return utils::conversion::strToUInt64(text, success); } }; template<> struct ApiController::TypeInterpretation <oatpp::Float32> { static oatpp::Float32 fromString(const oatpp::String& typeName, const oatpp::String& text, bool& success) { (void) typeName; return utils::conversion::strToFloat32(text, success); } }; template<> struct ApiController::TypeInterpretation <oatpp::Float64> { static oatpp::Float64 fromString(const oatpp::String& typeName, const oatpp::String& text, bool& success) { (void) typeName; return utils::conversion::strToFloat64(text, success); } }; template<> struct ApiController::TypeInterpretation <oatpp::Boolean> { static oatpp::Boolean fromString(const oatpp::String& typeName, const oatpp::String& text, bool& success) { (void) typeName; return utils::conversion::strToBool(text, success); } }; template<class T, class I> struct ApiController::TypeInterpretation <data::mapping::type::EnumObjectWrapper<T, I>> { typedef data::mapping::type::EnumObjectWrapper<T, I> EnumOW; typedef typename I::UnderlyingTypeObjectWrapper UTOW; static EnumOW fromString(const oatpp::String& typeName, const oatpp::String& text, bool& success) { const auto& parsedValue = ApiController::TypeInterpretation<UTOW>::fromString(typeName, text, success); if(success) { data::mapping::type::EnumInterpreterError error = data::mapping::type::EnumInterpreterError::OK; const auto& result = I::fromInterpretation(parsedValue, error); if(error == data::mapping::type::EnumInterpreterError::OK) { return result.template cast<EnumOW>(); } success = false; } return nullptr; } }; }}}} #endif /* oatpp_web_server_api_Controller_hpp */
vincent-in-black-sesame/oat
src/oatpp/web/server/api/ApiController.hpp
C++
apache-2.0
19,334
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "Endpoint.hpp" namespace oatpp { namespace web { namespace server { namespace api { Endpoint::Info::Param::Param() : name(nullptr) , type(nullptr) {} Endpoint::Info::Param::Param(const oatpp::String& pName, oatpp::data::mapping::type::Type* pType) : name(pName) , type(pType) {} const std::list<oatpp::String>& Endpoint::Info::Params::getOrder() const { return m_order; } Endpoint::Info::Param& Endpoint::Info::Params::add(const oatpp::String& name, oatpp::data::mapping::type::Type* type) { m_order.push_back(name); Endpoint::Info::Param& param = operator [](name); param.name = name; param.type = type; return param; } Endpoint::Info::Param& Endpoint::Info::Params::operator [](const oatpp::String& name) { return m_params[name]; } Endpoint::Info::Info() : hide(false) {} std::shared_ptr<Endpoint::Info> Endpoint::Info::createShared(){ return std::make_shared<Info>(); } oatpp::String Endpoint::Info::toString() { oatpp::data::stream::BufferOutputStream stream; stream << "\nEndpoint\n"; if(name) { stream << "name: '" << name << "'\n"; } if(path){ stream << "path: '" << path << "'\n"; } if(method){ stream << "method: '" << method << "'\n"; } if(body.name != nullptr){ stream << "body: '" << body.name << "', type: '" << body.type->classId.name << "'\n"; } auto headerIt = headers.getOrder().begin(); while (headerIt != headers.getOrder().end()) { auto header = headers[*headerIt++]; stream << "header: '" << header.name << "', type: '" << header.type->classId.name << "'\n"; } auto pathIt = pathParams.getOrder().begin(); while (pathIt != pathParams.getOrder().end()) { auto param = pathParams[*pathIt++]; stream << "pathParam: '" << param.name << "', type: '" << param.type->classId.name << "'\n"; } return stream.toString(); } Endpoint::Endpoint(const std::shared_ptr<RequestHandler>& pHandler, const std::function<std::shared_ptr<Endpoint::Info>()>& infoBuilder) : handler(pHandler) , m_infoBuilder(infoBuilder) {} std::shared_ptr<Endpoint> Endpoint::createShared(const std::shared_ptr<RequestHandler>& handler, const std::function<std::shared_ptr<Endpoint::Info>()>& infoBuilder){ return std::make_shared<Endpoint>(handler, infoBuilder); } std::shared_ptr<Endpoint::Info> Endpoint::info() { if (m_info == nullptr) { m_info = m_infoBuilder(); } return m_info; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Endpoints::append(const std::list<std::shared_ptr<Endpoint>>& endpoints) { list.insert(list.end(), endpoints.begin(), endpoints.end()); } void Endpoints::append(const Endpoints& endpoints) { append(endpoints.list); } void Endpoints::append(const std::shared_ptr<Endpoint>& endpoint) { list.push_back(endpoint); } }}}}
vincent-in-black-sesame/oat
src/oatpp/web/server/api/Endpoint.cpp
C++
apache-2.0
3,969
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_web_server_api_Endpoint_hpp #define oatpp_web_server_api_Endpoint_hpp #include "oatpp/web/server/HttpRequestHandler.hpp" #include <list> #include <unordered_map> #include <functional> namespace oatpp { namespace web { namespace server { namespace api { /** * Endpoint - class which holds information about endpoint. * It holds API documentation info, and pointer to RequestHandler */ class Endpoint : public oatpp::base::Countable { public: /** * Convenience typedef for &id:oatpp::web::server::HttpRequestHandler;. */ typedef oatpp::web::server::HttpRequestHandler RequestHandler; public: /** * Info holds API documentation information about endpoint */ class Info : public oatpp::base::Countable { public: /** * Param holds info about parameter */ struct Param { Param(); Param(const oatpp::String& pName, oatpp::data::mapping::type::Type* pType); oatpp::String name; oatpp::data::mapping::type::Type* type; oatpp::String description; oatpp::Boolean required = true; oatpp::Boolean deprecated = false; oatpp::Boolean allowEmptyValue; std::list<std::pair<oatpp::String, oatpp::Any>> examples; Param& addExample(const oatpp::String& title, const oatpp::Any& example) { examples.push_back({title, example}); return *this; } }; /** * Parameters container */ class Params { private: std::list<oatpp::String> m_order; std::unordered_map<oatpp::String, Param> m_params; public: const std::list<oatpp::String>& getOrder() const; /** * Add parameter name to list order * @param name * @return new or existing parameter */ Param& add(const oatpp::String& name, oatpp::data::mapping::type::Type* type); /** * Add parameter name to list order * @tparam T * @param name * @return new or existing parameter */ template<class T> Param& add(const oatpp::String& name) { return add(name, T::Class::getType()); } /** * Get or add param by name * @param name * @return */ Param& operator [](const oatpp::String& name); }; /** * Hints about the response (content-type, schema, description, ...) */ struct ContentHints { oatpp::String contentType; oatpp::data::mapping::type::Type* schema; oatpp::String description; std::list<std::pair<oatpp::String, oatpp::Any>> examples; ContentHints& addExample(const oatpp::String& title, const oatpp::Any& example) { examples.push_back({title, example}); return *this; } }; public: /** * Constructor; */ Info(); /** * Create shared Info. * @return */ static std::shared_ptr<Info> createShared(); /** * Endpoint name. */ oatpp::String name; /** * Endpoint summary. */ oatpp::String summary; /** * Endpoint description. */ oatpp::String description; /** * Endpoint path. */ oatpp::String path; /** * HTTP method. */ oatpp::String method; /** * Authorization. */ oatpp::String authorization; /** * Hide endpoint from the documentation. */ oatpp::Boolean hide; /** * Tags to group endpoints in the documentation. */ std::list<oatpp::String> tags; /** * Body info. */ Param body; /** * Body content type. */ oatpp::String bodyContentType; /** * Consumes. */ std::list<ContentHints> consumes; /** * Security Requirements */ std::unordered_map<oatpp::String, std::shared_ptr<std::list<oatpp::String>>> securityRequirements; /** * Headers. */ Params headers; /** * Path variables. */ Params pathParams; /** * Query params. */ Params queryParams; /** * ResponseCode to {ContentType, Type} mapping. * Example responses[Status::CODE_200] = {"application/json", MyDto::ObjectWrapper::Class::getType()}; */ std::unordered_map<oatpp::web::protocol::http::Status, ContentHints> responses; oatpp::String toString(); /** * Add "consumes" info to endpoint. * @tparam T * @param contentType */ template<class Wrapper> ContentHints& addConsumes(const oatpp::String& contentType, const oatpp::String& description = oatpp::String()) { consumes.push_back({contentType, Wrapper::Class::getType(), description}); return consumes.back(); } /** * Add response info to endpoint * @tparam Wrapper * @param status * @param contentType * @param responseDescription */ template<class Wrapper> ContentHints& addResponse(const oatpp::web::protocol::http::Status& status, const oatpp::String& contentType, const oatpp::String& responseDescription = oatpp::String()) { auto& hint = responses[status]; hint.contentType = contentType; hint.description = responseDescription.get() == nullptr ? status.description : responseDescription; hint.schema = Wrapper::Class::getType(); return hint; } /** * Add response info with no message-body to endpoint * @param status * @param responseDescription */ ContentHints& addResponse(const oatpp::web::protocol::http::Status& status, const oatpp::String& responseDescription = oatpp::String()) { auto& hint = responses[status]; hint.description = responseDescription.get() == nullptr ? status.description : responseDescription; return hint; } /** * Add security requirement. * @param requirement * @param scopes */ void addSecurityRequirement(const oatpp::String &requirement, const std::shared_ptr<std::list<oatpp::String>> &scopes = nullptr) { securityRequirements[requirement] = scopes; } /** * Add tag. * @param tag */ void addTag(const oatpp::String& tag) { tags.push_back(tag); } }; public: Endpoint(const std::shared_ptr<RequestHandler>& pHandler, const std::function<std::shared_ptr<Endpoint::Info>()>& infoBuilder); static std::shared_ptr<Endpoint> createShared(const std::shared_ptr<RequestHandler>& handler, const std::function<std::shared_ptr<Endpoint::Info>()>& infoBuilder); const std::shared_ptr<RequestHandler> handler; std::shared_ptr<Info> info(); private: std::shared_ptr<Info> m_info; std::function<std::shared_ptr<Endpoint::Info>()> m_infoBuilder; }; /** * Collection of endpoints. */ struct Endpoints { std::list<std::shared_ptr<Endpoint>> list; void append(const std::list<std::shared_ptr<Endpoint>>& endpoints); void append(const Endpoints& endpoints); void append(const std::shared_ptr<Endpoint>& endpoint); }; }}}} #endif /* oatpp_web_server_api_Endpoint_hpp */
vincent-in-black-sesame/oat
src/oatpp/web/server/api/Endpoint.hpp
C++
apache-2.0
8,060
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * Benedikt-Alexander Mokroß <bam@icognize.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "AuthorizationHandler.hpp" #include "oatpp/encoding/Base64.hpp" #include "oatpp/core/parser/Caret.hpp" namespace oatpp { namespace web { namespace server { namespace handler { AuthorizationHandler::AuthorizationHandler(const oatpp::String& scheme, const oatpp::String& realm) : m_scheme(scheme) , m_realm(realm) {} void AuthorizationHandler::renderAuthenticateHeaderValue(BufferOutputStream& stream) { stream << m_scheme << " " << "realm=\"" << m_realm << "\""; } void AuthorizationHandler::addErrorResponseHeaders(Headers& headers) { BufferOutputStream stream; renderAuthenticateHeaderValue(stream); headers.put_LockFree(protocol::http::Header::WWW_AUTHENTICATE, stream.toString()); } oatpp::String AuthorizationHandler::getScheme() { return m_scheme; } oatpp::String AuthorizationHandler::getRealm() { return m_realm; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // BasicAuthorizationHandler BasicAuthorizationHandler::BasicAuthorizationHandler(const oatpp::String& realm) : AuthorizationHandler("Basic", realm) {} std::shared_ptr<handler::AuthorizationObject> BasicAuthorizationHandler::handleAuthorization(const oatpp::String &header) { if(header && header->size() > 6 && utils::String::compare(header->data(), 6, "Basic ", 6) == 0) { oatpp::String auth = oatpp::encoding::Base64::decode(header->c_str() + 6, header->size() - 6); parser::Caret caret(auth); if (caret.findChar(':')) { oatpp::String userId((const char *) &caret.getData()[0], caret.getPosition()); oatpp::String password((const char *) &caret.getData()[caret.getPosition() + 1], caret.getDataSize() - caret.getPosition() - 1); auto authResult = authorize(userId, password); if(authResult) { return authResult; } Headers responseHeaders; addErrorResponseHeaders(responseHeaders); throw protocol::http::HttpError(protocol::http::Status::CODE_401, "Unauthorized", responseHeaders); } } Headers responseHeaders; addErrorResponseHeaders(responseHeaders); throw protocol::http::HttpError(protocol::http::Status::CODE_401, "Authorization Required", responseHeaders); } std::shared_ptr<AuthorizationObject> BasicAuthorizationHandler::authorize(const oatpp::String &userId, const oatpp::String &password) { auto authorizationObject = std::make_shared<DefaultBasicAuthorizationObject>(); authorizationObject->userId = userId; authorizationObject->password = password; return authorizationObject; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // BearerAuthorizationHandler BearerAuthorizationHandler::BearerAuthorizationHandler(const oatpp::String& realm) : AuthorizationHandler("Bearer", realm) {} std::shared_ptr<AuthorizationObject> BearerAuthorizationHandler::handleAuthorization(const oatpp::String &header) { if(header && header->size() > 7 && utils::String::compare(header->data(), 7, "Bearer ", 7) == 0) { oatpp::String token = oatpp::String(header->c_str() + 7, header->size() - 7); auto authResult = authorize(token); if(authResult) { return authResult; } Headers responseHeaders; addErrorResponseHeaders(responseHeaders); throw protocol::http::HttpError(protocol::http::Status::CODE_401, "Unauthorized", responseHeaders); } Headers responseHeaders; addErrorResponseHeaders(responseHeaders); throw protocol::http::HttpError(protocol::http::Status::CODE_401, "Authorization Required", responseHeaders); } std::shared_ptr<AuthorizationObject> BearerAuthorizationHandler::authorize(const oatpp::String& token) { auto authObject = std::make_shared<DefaultBearerAuthorizationObject>(); authObject->token = token; return authObject; } }}}}
vincent-in-black-sesame/oat
src/oatpp/web/server/handler/AuthorizationHandler.cpp
C++
apache-2.0
5,027
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * Benedikt-Alexander Mokroß <bam@icognize.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_web_server_handler_AuthorizationHandler_hpp #define oatpp_web_server_handler_AuthorizationHandler_hpp #include <oatpp/web/protocol/http/incoming/Request.hpp> #include "oatpp/web/protocol/http/Http.hpp" #include "oatpp/core/macro/codegen.hpp" #include "oatpp/core/data/mapping/type/Type.hpp" namespace oatpp { namespace web { namespace server { namespace handler { /** * The AuthorizationObject superclass, all AuthorizationObjects have to extend this class. */ class AuthorizationObject : public oatpp::base::Countable { protected: AuthorizationObject() = default; }; /** * Abstract Authorization Handler. */ class AuthorizationHandler { public: /** * Convenience typedef for &l:AuthorizationObject;. */ typedef oatpp::web::server::handler::AuthorizationObject AuthorizationObject; /** * Convenience typedef for &id:oatpp::data::stream::BufferOutputStream;. */ typedef oatpp::data::stream::BufferOutputStream BufferOutputStream; /** * Convenience typedef for &id:oatpp::web::protocol::http::Headers;. */ typedef oatpp::web::protocol::http::Headers Headers; private: oatpp::String m_scheme; oatpp::String m_realm; public: /** * Constructor. * @param scheme - authorization type scheme. &id:oatpp::String;. * @param realm - realm. &id:oatpp::String;. */ AuthorizationHandler(const oatpp::String& scheme, const oatpp::String& realm); /** * Default virtual destructor. */ virtual ~AuthorizationHandler() = default; /** * Implement this method! Return nullptr if authorization should be denied. * @param header - `Authorization` header. &id:oatpp::String;. * @return - `std::shared_ptr` to &id:oatpp::web::server::handler::AuthorizationObject;. */ virtual std::shared_ptr<AuthorizationObject> handleAuthorization(const oatpp::String& authorizationHeader) = 0; /** * Render WWW-Authenicate header value. <br> * Custom Authorization handlers may override this method in order to provide additional information. * @param stream - &id:oatpp::data::stream::BufferOutputStream;. */ virtual void renderAuthenticateHeaderValue(BufferOutputStream& stream); /** * Add authorization error headers to the headers map. <br> * @param headers - &id:oatpp::web::protocol::http::Headers;. */ virtual void addErrorResponseHeaders(Headers& headers); /** * Get authorization scheme. * @return */ oatpp::String getScheme(); /** * Get authorization realm. * @return */ oatpp::String getRealm(); }; /** * Default Basic AuthorizationObject - Convenience object to enable Basic-Authorization without the need to implement anything. */ class DefaultBasicAuthorizationObject : public AuthorizationObject { public: /** * User-Id. &id:oatpp::String;. */ oatpp::String userId; /** * Password. &id:oatpp::String;. */ oatpp::String password; }; /** * AuthorizationHandler for Authorization Type `Basic`. <br> * See [RFC 7617](https://tools.ietf.org/html/rfc7617). <br> * Extend this class to implement Custom Basic Authorization. */ class BasicAuthorizationHandler : public AuthorizationHandler { public: /** * Constructor. * @param realm */ BasicAuthorizationHandler(const oatpp::String& realm = "API"); /** * Implementation of &l:AuthorizationHandler::handleAuthorization (); * @param header - &id:oatpp::String;. * @return - std::shared_ptr to &id:oatpp::web::server::handler::AuthorizationObject;. */ std::shared_ptr<AuthorizationObject> handleAuthorization(const oatpp::String &header) override; /** * Implement this method! Do the actual authorization here. When not implemented returns &l:DefaultBasicAuthorizationObject;. * @param userId - user id. &id:oatpp::String;. * @param password - password. &id:oatpp::String;. * @return - `std::shared_ptr` to &l:AuthorizationObject;. `nullptr` - for "Unauthorized". */ virtual std::shared_ptr<AuthorizationObject> authorize(const oatpp::String& userId, const oatpp::String& password); }; /** * Default Bearer AuthorizationObject - Convenience object to enable Bearer-Authorization without the need to implement anything. */ class DefaultBearerAuthorizationObject : public AuthorizationObject { public: /** * Token. &id:oatpp::String;. */ oatpp::String token; }; /** * AuthorizationHandler for Authorization Type `Bearer`. <br> * See [RFC 6750](https://tools.ietf.org/html/rfc6750). <br> * Extend this class to implement Custom Bearer Authorization. */ class BearerAuthorizationHandler : public AuthorizationHandler { public: /** * Constructor. * @param realm */ BearerAuthorizationHandler(const oatpp::String& realm = "API"); /** * Implementation of &l:AuthorizationHandler::handleAuthorization (); * @param header - &id:oatpp::String;. * @return - std::shared_ptr to &id:oatpp::web::server::handler::AuthorizationObject;. */ std::shared_ptr<AuthorizationObject> handleAuthorization(const oatpp::String &header) override; /** * Implement this method! Do the actual authorization here. When not implemented returns &l:DefaultBearerAuthorizationObject;. * @param token - access token. * @return - `std::shared_ptr` to &l:AuthorizationObject;. `nullptr` - for "Unauthorized". */ virtual std::shared_ptr<AuthorizationObject> authorize(const oatpp::String& token); }; }}}} #endif /* oatpp_web_server_handler_ErrorHandler_hpp */
vincent-in-black-sesame/oat
src/oatpp/web/server/handler/AuthorizationHandler.hpp
C++
apache-2.0
6,524
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "./ErrorHandler.hpp" #include "oatpp/web/protocol/http/outgoing/BufferBody.hpp" namespace oatpp { namespace web { namespace server { namespace handler { std::shared_ptr<protocol::http::outgoing::Response> ErrorHandler::handleError(const std::exception_ptr& exceptionPtr) { std::shared_ptr<protocol::http::outgoing::Response> response; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" /* Default impl for backwards compatibility until the deprecated methods are removed */ try { if(exceptionPtr) { std::rethrow_exception(exceptionPtr); } } catch (protocol::http::HttpError& httpError) { response = handleError(httpError.getInfo().status, httpError.getMessage(), httpError.getHeaders()); } catch (std::exception& error) { response = handleError(protocol::http::Status::CODE_500, error.what()); } catch (...) { response = handleError(protocol::http::Status::CODE_500, "An unknown error has occurred"); } #pragma GCC diagnostic pop return response; } std::shared_ptr<protocol::http::outgoing::Response> ErrorHandler::handleError(const protocol::http::Status& status, const oatpp::String& message) { Headers headers; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" return handleError(status, message, headers); #pragma GCC diagnostic pop } std::shared_ptr<protocol::http::outgoing::Response> DefaultErrorHandler::handleError(const oatpp::web::protocol::http::Status &status, const oatpp::String &message, const Headers& headers){ data::stream::BufferOutputStream stream; stream << "server=" << protocol::http::Header::Value::SERVER << "\n"; stream << "code=" << status.code << "\n"; stream << "description=" << status.description << "\n"; stream << "message=" << message << "\n"; auto response = protocol::http::outgoing::Response::createShared (status, protocol::http::outgoing::BufferBody::createShared(stream.toString())); response->putHeader(protocol::http::Header::SERVER, protocol::http::Header::Value::SERVER); response->putHeader(protocol::http::Header::CONNECTION, protocol::http::Header::Value::CONNECTION_CLOSE); for(const auto& pair : headers.getAll()) { response->putHeader_Unsafe(pair.first, pair.second); } return response; } std::shared_ptr<protocol::http::outgoing::Response> DefaultErrorHandler::handleError(const std::exception_ptr& error) { return ErrorHandler::handleError(error); } }}}}
vincent-in-black-sesame/oat
src/oatpp/web/server/handler/ErrorHandler.cpp
C++
apache-2.0
3,482
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_web_server_handler_ErrorHandler_hpp #define oatpp_web_server_handler_ErrorHandler_hpp #include "oatpp/web/protocol/http/outgoing/Response.hpp" #include "oatpp/web/protocol/http/Http.hpp" namespace oatpp { namespace web { namespace server { namespace handler { /** * Error Handler. */ class ErrorHandler { public: /** * Convenience typedef for Headers. <br> * See &id:oatpp::web::protocol::http::Headers; */ typedef web::protocol::http::Headers Headers; public: /** * Virtual destructor since the class is meant to be derived from. * */ virtual ~ErrorHandler() = default; /** * Implement this method! * @param error - &std::exception;. * @return - std::shared_ptr to &id:oatpp::web::protocol::http::outgoing::Response;. */ virtual std::shared_ptr<protocol::http::outgoing::Response> handleError(const std::exception_ptr& exceptionPtr); /** * Implement this method! * @param status - &id:oatpp::web::protocol::http::Status;. * @param message - &id:oatpp::String;. * @param Headers - &id:oatpp::web::protocol::http::Headers; * @return - std::shared_ptr to &id:oatpp::web::protocol::http::outgoing::Response;. */ [[deprecated]] virtual std::shared_ptr<protocol::http::outgoing::Response> handleError(const protocol::http::Status& status, const oatpp::String& message, const Headers& headers) = 0; /** * Convenience method to call `handleError` method with no headers. * @param status - &id:oatpp::web::protocol::http::Status; * @param message - &id:oatpp::String;. * @return - std::shared_ptr to &id:oatpp::web::protocol::http::outgoing::Response;. */ [[deprecated]] std::shared_ptr<protocol::http::outgoing::Response> handleError(const protocol::http::Status& status, const oatpp::String& message); }; /** * Default Error Handler. */ class DefaultErrorHandler : public oatpp::base::Countable, public ErrorHandler { public: /** * Constructor. */ DefaultErrorHandler() = default; public: /** * Create shared DefaultErrorHandler. * @return - `std::shared_ptr` to DefaultErrorHandler. */ static std::shared_ptr<DefaultErrorHandler> createShared() { return std::make_shared<DefaultErrorHandler>(); } std::shared_ptr<protocol::http::outgoing::Response> handleError(const std::exception_ptr& error) override; /** * Implementation of &l:ErrorHandler::handleError (); * @param status - &id:oatpp::web::protocol::http::Status;. * @param message - &id:oatpp::String;. * @return - &id:oatpp::web::protocol::http::outgoing::Response;. */ std::shared_ptr<protocol::http::outgoing::Response> handleError(const protocol::http::Status& status, const oatpp::String& message, const Headers& headers) override; }; }}}} #endif /* oatpp_web_server_handler_ErrorHandler_hpp */
vincent-in-black-sesame/oat
src/oatpp/web/server/handler/ErrorHandler.hpp
C++
apache-2.0
3,823
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "AllowCorsGlobal.hpp" namespace oatpp { namespace web { namespace server { namespace interceptor { std::shared_ptr<protocol::http::outgoing::Response> AllowOptionsGlobal::intercept(const std::shared_ptr<IncomingRequest> &request) { const auto &line = request->getStartingLine(); if (line.method == "OPTIONS") { return OutgoingResponse::createShared(protocol::http::Status::CODE_204, nullptr); } return nullptr; } AllowCorsGlobal::AllowCorsGlobal(const oatpp::String &origin, const oatpp::String &methods, const oatpp::String &headers, const oatpp::String &maxAge) : m_origin(origin) , m_methods(methods) , m_headers(headers) , m_maxAge(maxAge) {} std::shared_ptr<protocol::http::outgoing::Response> AllowCorsGlobal::intercept(const std::shared_ptr<IncomingRequest>& request, const std::shared_ptr<OutgoingResponse>& response) { response->putHeaderIfNotExists(protocol::http::Header::CORS_ORIGIN, m_origin); response->putHeaderIfNotExists(protocol::http::Header::CORS_METHODS, m_methods); response->putHeaderIfNotExists(protocol::http::Header::CORS_HEADERS, m_headers); response->putHeaderIfNotExists(protocol::http::Header::CORS_MAX_AGE, m_maxAge); return response; } }}}}
vincent-in-black-sesame/oat
src/oatpp/web/server/interceptor/AllowCorsGlobal.cpp
C++
apache-2.0
2,395
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_web_server_interceptor_AllowCorsGlobal_hpp #define oatpp_web_server_interceptor_AllowCorsGlobal_hpp #include "oatpp/web/server/interceptor/ResponseInterceptor.hpp" #include "oatpp/web/server/interceptor/RequestInterceptor.hpp" namespace oatpp { namespace web { namespace server { namespace interceptor { class AllowOptionsGlobal : public RequestInterceptor { public: std::shared_ptr<OutgoingResponse> intercept(const std::shared_ptr<IncomingRequest>& request) override; }; class AllowCorsGlobal : public ResponseInterceptor { private: oatpp::String m_origin; oatpp::String m_methods; oatpp::String m_headers; oatpp::String m_maxAge; public: AllowCorsGlobal(const oatpp::String &origin = "*", const oatpp::String &methods = "GET, POST, OPTIONS", const oatpp::String &headers = "DNT, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Range, Authorization", const oatpp::String &maxAge = "1728000"); std::shared_ptr<OutgoingResponse> intercept(const std::shared_ptr<IncomingRequest>& request, const std::shared_ptr<OutgoingResponse>& response) override; }; }}}} #endif // oatpp_web_server_interceptor_AllowCorsGlobal_hpp
vincent-in-black-sesame/oat
src/oatpp/web/server/interceptor/AllowCorsGlobal.hpp
C++
apache-2.0
2,279
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_web_server_interceptor_RequestInterceptor_hpp #define oatpp_web_server_interceptor_RequestInterceptor_hpp #include "oatpp/web/protocol/http/outgoing/Response.hpp" #include "oatpp/web/protocol/http/incoming/Request.hpp" #include "oatpp/web/protocol/http/Http.hpp" namespace oatpp { namespace web { namespace server { namespace interceptor { /** * RequestInterceptor. */ class RequestInterceptor { public: /** * Convenience typedef for &id:oatpp::web::protocol::http::incoming::Request;. */ typedef oatpp::web::protocol::http::incoming::Request IncomingRequest; /** * Convenience typedef for &id:oatpp::web::protocol::http::outgoing::Response;. */ typedef oatpp::web::protocol::http::outgoing::Response OutgoingResponse; public: /** * Default virtual destructor. */ virtual ~RequestInterceptor() = default; /** * * This method should not do any "heavy" nor I/O operations * as it is used for both "Simple" and "Async" API * NOT FOR I/O operations!!! * * - return nullptr to continue. * - return OutgoingResponse to send response immediately * * possible usage ex: return 301 - redirect if needed * */ virtual std::shared_ptr<OutgoingResponse> intercept(const std::shared_ptr<IncomingRequest>& request) = 0; }; }}}} #endif /* oatpp_web_server_interceptor_RequestInterceptor_hpp */
vincent-in-black-sesame/oat
src/oatpp/web/server/interceptor/RequestInterceptor.hpp
C++
apache-2.0
2,380
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_web_server_interceptor_ResponseInterceptor_hpp #define oatpp_web_server_interceptor_ResponseInterceptor_hpp #include "oatpp/web/protocol/http/incoming/Request.hpp" #include "oatpp/web/protocol/http/outgoing/Response.hpp" #include "oatpp/web/protocol/http/Http.hpp" namespace oatpp { namespace web { namespace server { namespace interceptor { /** * ResponseInterceptor. */ class ResponseInterceptor { public: /** * Convenience typedef for &id:oatpp::web::protocol::http::incoming::Request;. */ typedef oatpp::web::protocol::http::incoming::Request IncomingRequest; /** * Convenience typedef for &id:oatpp::web::protocol::http::outgoing::Response;. */ typedef oatpp::web::protocol::http::outgoing::Response OutgoingResponse; public: /** * Default virtual destructor. */ virtual ~ResponseInterceptor() = default; /** * * This method should not do any "heavy" nor I/O operations <br> * as it is used for both "Simple" and "Async" API <br> * NOT FOR I/O operations!!! <br> * <br> * - return the same response, or the new one. <br> * - do **NOT** return `nullptr`. * <br><br> * possible usage ex: add extra headers to the response. * * @param request - the corresponding request. * @param response - response to the request * @return - &id:oatpp::web::protocol::http::outgoing::Response;. */ virtual std::shared_ptr<OutgoingResponse> intercept(const std::shared_ptr<IncomingRequest>& request, const std::shared_ptr<OutgoingResponse>& response) = 0; }; }}}} #endif /* oatpp_web_server_interceptor_ResponseInterceptor_hpp */
vincent-in-black-sesame/oat
src/oatpp/web/server/interceptor/ResponseInterceptor.hpp
C++
apache-2.0
2,668
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "Pattern.hpp" #include "oatpp/core/data/stream/BufferStream.hpp" namespace oatpp { namespace web { namespace url { namespace mapping { const char* Pattern::Part::FUNCTION_CONST = "const"; const char* Pattern::Part::FUNCTION_VAR = "var"; const char* Pattern::Part::FUNCTION_ANY_END = "tail"; std::shared_ptr<Pattern> Pattern::parse(p_char8 data, v_buff_size size){ if(size <= 0){ return nullptr; } auto result = Pattern::createShared(); v_buff_size lastPos = 0; v_buff_size i = 0; while(i < size){ v_char8 a = data[i]; if(a == '/'){ if(i - lastPos > 0){ auto part = Part::createShared(Part::FUNCTION_CONST, oatpp::String((const char*)&data[lastPos], i - lastPos)); result->m_parts->push_back(part); } lastPos = i + 1; } else if(a == '*'){ lastPos = i + 1; if(size > lastPos){ auto part = Part::createShared(Part::FUNCTION_ANY_END, oatpp::String((const char*)&data[lastPos], size - lastPos)); result->m_parts->push_back(part); }else{ auto part = Part::createShared(Part::FUNCTION_ANY_END, oatpp::String((v_buff_size)0)); result->m_parts->push_back(part); } return result; } else if(a == '{'){ lastPos = i + 1; while(i < size && data[i] != '}'){ i++; } if(i > lastPos){ auto part = Part::createShared(Part::FUNCTION_VAR, oatpp::String((const char*)&data[lastPos], i - lastPos)); result->m_parts->push_back(part); }else{ auto part = Part::createShared(Part::FUNCTION_VAR, oatpp::String((v_buff_size)0)); result->m_parts->push_back(part); } lastPos = i + 1; } i++; } if(i - lastPos > 0){ auto part = Part::createShared(Part::FUNCTION_CONST, oatpp::String((const char*)&data[lastPos], i - lastPos)); result->m_parts->push_back(part); } return result; } std::shared_ptr<Pattern> Pattern::parse(const char* data){ return parse((p_char8) data, std::strlen(data)); } std::shared_ptr<Pattern> Pattern::parse(const oatpp::String& data){ return parse((p_char8) data->data(), data->size()); } v_char8 Pattern::findSysChar(oatpp::parser::Caret& caret) { auto data = caret.getData(); for (v_buff_size i = caret.getPosition(); i < caret.getDataSize(); i++) { v_char8 a = data[i]; if(a == '/' || a == '?') { caret.setPosition(i); return a; } } caret.setPosition(caret.getDataSize()); return 0; } bool Pattern::match(const StringKeyLabel& url, MatchMap& matchMap) { oatpp::parser::Caret caret((const char*) url.getData(), url.getSize()); if (m_parts->empty()) { return !caret.skipChar('/'); } auto curr = std::begin(*m_parts); const auto end = std::end(*m_parts); while(curr != end){ const std::shared_ptr<Part>& part = *curr; ++curr; caret.skipChar('/'); if(part->function == Part::FUNCTION_CONST){ if(!caret.isAtText(part->text->data(), part->text->size(), true)) { return false; } if(caret.canContinue() && !caret.isAtChar('/')){ if(caret.isAtChar('?') && (curr == end || (*curr)->function == Part::FUNCTION_ANY_END)) { matchMap.m_tail = StringKeyLabel(url.getMemoryHandle(), caret.getCurrData(), caret.getDataSize() - caret.getPosition()); return true; } return false; } }else if(part->function == Part::FUNCTION_ANY_END){ if(caret.getDataSize() > caret.getPosition()){ matchMap.m_tail = StringKeyLabel(url.getMemoryHandle(), caret.getCurrData(), caret.getDataSize() - caret.getPosition()); } return true; }else if(part->function == Part::FUNCTION_VAR){ if(!caret.canContinue()){ return false; } auto label = caret.putLabel(); v_char8 a = findSysChar(caret); if(a == '?') { if(curr == end || (*curr)->function == Part::FUNCTION_ANY_END) { matchMap.m_variables[part->text] = StringKeyLabel(url.getMemoryHandle(), label.getData(), label.getSize()); matchMap.m_tail = StringKeyLabel(url.getMemoryHandle(), caret.getCurrData(), caret.getDataSize() - caret.getPosition()); return true; } caret.findChar('/'); } matchMap.m_variables[part->text] = StringKeyLabel(url.getMemoryHandle(), label.getData(), label.getSize()); } } caret.skipChar('/'); return !caret.canContinue(); } oatpp::String Pattern::toString() { oatpp::data::stream::BufferOutputStream stream; for (const std::shared_ptr<Part>& part : *m_parts) { if(part->function == Part::FUNCTION_CONST) { stream.writeSimple("/", 1); stream.writeSimple(part->text); } else if(part->function == Part::FUNCTION_VAR) { stream.writeSimple("/{", 2); stream.writeSimple(part->text); stream.writeSimple("}", 1); } else if(part->function == Part::FUNCTION_ANY_END) { stream.writeSimple("/*", 2); } } return stream.toString(); } }}}}
vincent-in-black-sesame/oat
src/oatpp/web/url/mapping/Pattern.cpp
C++
apache-2.0
6,127
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_web_url_mapping_Pattern_hpp #define oatpp_web_url_mapping_Pattern_hpp #include "oatpp/core/data/share/MemoryLabel.hpp" #include "oatpp/core/parser/Caret.hpp" #include <list> #include <unordered_map> namespace oatpp { namespace web { namespace url { namespace mapping { class Pattern : public base::Countable{ private: typedef oatpp::data::share::StringKeyLabel StringKeyLabel; public: class MatchMap { friend Pattern; public: typedef std::unordered_map<StringKeyLabel, StringKeyLabel> Variables; private: Variables m_variables; StringKeyLabel m_tail; public: MatchMap() {} MatchMap(const Variables& vars, const StringKeyLabel& urlTail) : m_variables(vars) , m_tail(urlTail) {} oatpp::String getVariable(const StringKeyLabel& key) const { auto it = m_variables.find(key); if(it != m_variables.end()) { return it->second.toString(); } return nullptr; } oatpp::String getTail() const { return m_tail.toString(); } const Variables& getVariables() const { return m_variables; } }; private: class Part : public base::Countable{ public: Part(const char* pFunction, const oatpp::String& pText) : function(pFunction) , text(pText) {} public: static const char* FUNCTION_CONST; static const char* FUNCTION_VAR; static const char* FUNCTION_ANY_END; static std::shared_ptr<Part> createShared(const char* function, const oatpp::String& text){ return std::make_shared<Part>(function, text); } const char* function; const oatpp::String text; }; private: std::shared_ptr<std::list<std::shared_ptr<Part>>> m_parts{std::make_shared<std::list<std::shared_ptr<Part>>>()}; private: v_char8 findSysChar(oatpp::parser::Caret& caret); public: static std::shared_ptr<Pattern> createShared(){ return std::make_shared<Pattern>(); } static std::shared_ptr<Pattern> parse(p_char8 data, v_buff_size size); static std::shared_ptr<Pattern> parse(const char* data); static std::shared_ptr<Pattern> parse(const oatpp::String& data); bool match(const StringKeyLabel& url, MatchMap& matchMap); oatpp::String toString(); }; }}}} #endif /* oatpp_web_url_mapping_Pattern_hpp */
vincent-in-black-sesame/oat
src/oatpp/web/url/mapping/Pattern.hpp
C++
apache-2.0
3,337
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_web_url_mapping_Router_hpp #define oatpp_web_url_mapping_Router_hpp #include "./Pattern.hpp" #include "oatpp/core/Types.hpp" #include <utility> #include <list> namespace oatpp { namespace web { namespace url { namespace mapping { /** * Class responsible to map "Path" to "Route" by "Path-Pattern". * @tparam Endpoint - endpoint of the route. */ template<typename Endpoint> class Router : public base::Countable { private: /** * Pair &id:oatpp::web::url::mapping::Pattern; to Endpoint. */ typedef std::pair<std::shared_ptr<Pattern>, Endpoint> Pair; /** * Convenience typedef &id:oatpp::data::share::StringKeyLabel;. */ typedef oatpp::data::share::StringKeyLabel StringKeyLabel; public: /** * Resolved "Route" for "path-pattern" */ class Route { private: bool m_valid; Endpoint m_endpoint; Pattern::MatchMap m_matchMap; public: /** * Default constructor. */ Route() : m_valid(false) {} /** * Constructor. * @param pEndpoint - route endpoint. * @param pMatchMap - Match map of resolved path containing resolved path variables. */ Route(const Endpoint& endpoint, Pattern::MatchMap&& matchMap) : m_valid(true) , m_endpoint(endpoint) , m_matchMap(matchMap) {} /** * Get Endpoint. */ const Endpoint& getEndpoint() { return m_endpoint; } /** * Match map of resolved path containing resolved path variables. */ const Pattern::MatchMap& getMatchMap() { return m_matchMap; } /** * Check if route is valid. * @return */ bool isValid() { return m_valid; } explicit operator bool() const { return m_valid; } }; private: std::list<Pair> m_endpointsByPattern; public: static std::shared_ptr<Router> createShared(){ return std::make_shared<Router>(); } /** * Add `path-pattern` to `endpoint` mapping. * @param pathPattern - path pattern for endpoint. * @param endpoint - route endpoint. */ void route(const oatpp::String& pathPattern, const Endpoint& endpoint) { auto pattern = Pattern::parse(pathPattern); m_endpointsByPattern.push_back({pattern, endpoint}); } /** * Resolve path to corresponding endpoint. * @param path * @return - &id:Router::Route;. */ Route getRoute(const StringKeyLabel& path){ for(auto& pair : m_endpointsByPattern) { Pattern::MatchMap matchMap; if(pair.first->match(path, matchMap)) { return Route(pair.second, std::move(matchMap)); } } return Route(); } void logRouterMappings(const oatpp::data::share::StringKeyLabel &branch) { for(auto& pair : m_endpointsByPattern) { auto mapping = pair.first->toString(); OATPP_LOGD("Router", "url '%s %s' -> mapped", (const char*)branch.getData(), mapping->c_str()); } } }; }}}} #endif /* oatpp_web_url_mapping_Router_hpp */
vincent-in-black-sesame/oat
src/oatpp/web/url/mapping/Router.hpp
C++
apache-2.0
3,975
add_executable(oatppAllTests oatpp/AllTestsMain.cpp oatpp/core/async/LockTest.cpp oatpp/core/async/LockTest.hpp oatpp/core/base/CommandLineArgumentsTest.cpp oatpp/core/base/CommandLineArgumentsTest.hpp oatpp/core/base/LoggerTest.cpp oatpp/core/base/LoggerTest.hpp oatpp/core/data/buffer/ProcessorTest.cpp oatpp/core/data/buffer/ProcessorTest.hpp oatpp/core/data/mapping/type/AnyTest.cpp oatpp/core/data/mapping/type/AnyTest.hpp oatpp/core/data/mapping/type/EnumTest.cpp oatpp/core/data/mapping/type/EnumTest.hpp oatpp/core/data/mapping/type/InterpretationTest.cpp oatpp/core/data/mapping/type/InterpretationTest.hpp oatpp/core/data/mapping/type/ListTest.cpp oatpp/core/data/mapping/type/ListTest.hpp oatpp/core/data/mapping/type/ObjectTest.cpp oatpp/core/data/mapping/type/ObjectTest.hpp oatpp/core/data/mapping/type/ObjectWrapperTest.cpp oatpp/core/data/mapping/type/ObjectWrapperTest.hpp oatpp/core/data/mapping/type/PairListTest.cpp oatpp/core/data/mapping/type/PairListTest.hpp oatpp/core/data/mapping/type/PrimitiveTest.cpp oatpp/core/data/mapping/type/PrimitiveTest.hpp oatpp/core/data/mapping/type/StringTest.cpp oatpp/core/data/mapping/type/StringTest.hpp oatpp/core/data/mapping/type/TypeTest.cpp oatpp/core/data/mapping/type/TypeTest.hpp oatpp/core/data/mapping/type/UnorderedMapTest.cpp oatpp/core/data/mapping/type/UnorderedMapTest.hpp oatpp/core/data/mapping/type/UnorderedSetTest.cpp oatpp/core/data/mapping/type/UnorderedSetTest.hpp oatpp/core/data/mapping/type/VectorTest.cpp oatpp/core/data/mapping/type/VectorTest.hpp oatpp/core/data/mapping/TypeResolverTest.cpp oatpp/core/data/mapping/TypeResolverTest.hpp oatpp/core/data/resource/InMemoryDataTest.cpp oatpp/core/data/resource/InMemoryDataTest.hpp oatpp/core/data/share/LazyStringMapTest.cpp oatpp/core/data/share/LazyStringMapTest.hpp oatpp/core/data/share/MemoryLabelTest.cpp oatpp/core/data/share/MemoryLabelTest.hpp oatpp/core/data/share/StringTemplateTest.cpp oatpp/core/data/share/StringTemplateTest.hpp oatpp/core/data/stream/BufferStreamTest.cpp oatpp/core/data/stream/BufferStreamTest.hpp oatpp/core/parser/CaretTest.cpp oatpp/core/parser/CaretTest.hpp oatpp/core/provider/PoolTest.cpp oatpp/core/provider/PoolTest.hpp oatpp/core/provider/PoolTemplateTest.cpp oatpp/core/provider/PoolTemplateTest.hpp oatpp/encoding/Base64Test.cpp oatpp/encoding/Base64Test.hpp oatpp/encoding/UnicodeTest.cpp oatpp/encoding/UnicodeTest.hpp oatpp/network/monitor/ConnectionMonitorTest.cpp oatpp/network/monitor/ConnectionMonitorTest.hpp oatpp/network/virtual_/InterfaceTest.cpp oatpp/network/virtual_/InterfaceTest.hpp oatpp/network/virtual_/PipeTest.cpp oatpp/network/virtual_/PipeTest.hpp oatpp/network/ConnectionPoolTest.cpp oatpp/network/ConnectionPoolTest.hpp oatpp/network/UrlTest.cpp oatpp/network/UrlTest.hpp oatpp/parser/json/mapping/DTOMapperPerfTest.cpp oatpp/parser/json/mapping/DTOMapperPerfTest.hpp oatpp/parser/json/mapping/DTOMapperTest.cpp oatpp/parser/json/mapping/DTOMapperTest.hpp oatpp/parser/json/mapping/DeserializerTest.cpp oatpp/parser/json/mapping/DeserializerTest.hpp oatpp/parser/json/mapping/EnumTest.cpp oatpp/parser/json/mapping/EnumTest.hpp oatpp/parser/json/mapping/UnorderedSetTest.cpp oatpp/parser/json/mapping/UnorderedSetTest.hpp oatpp/web/protocol/http/encoding/ChunkedTest.cpp oatpp/web/protocol/http/encoding/ChunkedTest.hpp oatpp/web/mime/multipart/StatefulParserTest.cpp oatpp/web/mime/multipart/StatefulParserTest.hpp oatpp/web/server/api/ApiControllerTest.cpp oatpp/web/server/api/ApiControllerTest.hpp oatpp/web/server/handler/AuthorizationHandlerTest.cpp oatpp/web/server/handler/AuthorizationHandlerTest.hpp oatpp/web/server/HttpRouterTest.cpp oatpp/web/server/HttpRouterTest.hpp oatpp/web/server/ServerStopTest.cpp oatpp/web/server/ServerStopTest.hpp oatpp/web/ClientRetryTest.cpp oatpp/web/ClientRetryTest.hpp oatpp/web/PipelineTest.cpp oatpp/web/PipelineTest.hpp oatpp/web/PipelineAsyncTest.cpp oatpp/web/PipelineAsyncTest.hpp oatpp/web/FullAsyncTest.cpp oatpp/web/FullAsyncTest.hpp oatpp/web/FullTest.cpp oatpp/web/FullTest.hpp oatpp/web/FullAsyncClientTest.cpp oatpp/web/FullAsyncClientTest.hpp oatpp/web/app/Client.hpp oatpp/web/app/BearerAuthorizationController.hpp oatpp/web/app/BasicAuthorizationController.hpp oatpp/web/app/Controller.hpp oatpp/web/app/ControllerAsync.hpp oatpp/web/app/DTOs.hpp oatpp/web/app/ControllerWithInterceptors.hpp oatpp/web/app/ControllerWithInterceptorsAsync.hpp oatpp/web/app/ControllerWithErrorHandler.hpp ) target_link_libraries(oatppAllTests PRIVATE oatpp PRIVATE oatpp-test) set_target_properties(oatppAllTests PROPERTIES CXX_STANDARD 11 CXX_EXTENSIONS OFF CXX_STANDARD_REQUIRED ON ) if (MSVC) target_compile_options(oatppAllTests PRIVATE /permissive-) endif() target_include_directories(oatppAllTests PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) add_test(oatppAllTests oatppAllTests)
vincent-in-black-sesame/oat
test/CMakeLists.txt
CMake
apache-2.0
5,728
#include "oatpp/web/ClientRetryTest.hpp" #include "oatpp/web/FullTest.hpp" #include "oatpp/web/FullAsyncTest.hpp" #include "oatpp/web/FullAsyncClientTest.hpp" #include "oatpp/web/PipelineTest.hpp" #include "oatpp/web/PipelineAsyncTest.hpp" #include "oatpp/web/protocol/http/encoding/ChunkedTest.hpp" #include "oatpp/web/server/api/ApiControllerTest.hpp" #include "oatpp/web/server/handler/AuthorizationHandlerTest.hpp" #include "oatpp/web/server/HttpRouterTest.hpp" #include "oatpp/web/server/ServerStopTest.hpp" #include "oatpp/web/mime/multipart/StatefulParserTest.hpp" #include "oatpp/network/virtual_/PipeTest.hpp" #include "oatpp/network/virtual_/InterfaceTest.hpp" #include "oatpp/network/UrlTest.hpp" #include "oatpp/network/ConnectionPoolTest.hpp" #include "oatpp/network/monitor/ConnectionMonitorTest.hpp" #include "oatpp/parser/json/mapping/DeserializerTest.hpp" #include "oatpp/parser/json/mapping/DTOMapperPerfTest.hpp" #include "oatpp/parser/json/mapping/DTOMapperTest.hpp" #include "oatpp/parser/json/mapping/EnumTest.hpp" #include "oatpp/parser/json/mapping/UnorderedSetTest.hpp" #include "oatpp/encoding/UnicodeTest.hpp" #include "oatpp/encoding/Base64Test.hpp" #include "oatpp/core/parser/CaretTest.hpp" #include "oatpp/core/provider/PoolTest.hpp" #include "oatpp/core/provider/PoolTemplateTest.hpp" #include "oatpp/core/async/LockTest.hpp" #include "oatpp/core/data/mapping/type/UnorderedMapTest.hpp" #include "oatpp/core/data/mapping/type/PairListTest.hpp" #include "oatpp/core/data/mapping/type/VectorTest.hpp" #include "oatpp/core/data/mapping/type/UnorderedSetTest.hpp" #include "oatpp/core/data/mapping/type/ListTest.hpp" #include "oatpp/core/data/mapping/type/ObjectTest.hpp" #include "oatpp/core/data/mapping/type/StringTest.hpp" #include "oatpp/core/data/mapping/type/PrimitiveTest.hpp" #include "oatpp/core/data/mapping/type/ObjectWrapperTest.hpp" #include "oatpp/core/data/mapping/type/TypeTest.hpp" #include "oatpp/core/data/mapping/type/AnyTest.hpp" #include "oatpp/core/data/mapping/type/EnumTest.hpp" #include "oatpp/core/data/mapping/type/InterpretationTest.hpp" #include "oatpp/core/data/mapping/TypeResolverTest.hpp" #include "oatpp/core/data/resource/InMemoryDataTest.hpp" #include "oatpp/core/data/stream/BufferStreamTest.hpp" #include "oatpp/core/data/share/LazyStringMapTest.hpp" #include "oatpp/core/data/share/StringTemplateTest.hpp" #include "oatpp/core/data/share/MemoryLabelTest.hpp" #include "oatpp/core/data/buffer/ProcessorTest.hpp" #include "oatpp/core/base/CommandLineArgumentsTest.hpp" #include "oatpp/core/base/LoggerTest.hpp" #include "oatpp/core/async/Coroutine.hpp" #include "oatpp/core/Types.hpp" #include "oatpp/core/base/Environment.hpp" #include <iostream> #include <mutex> namespace { void runTests() { oatpp::base::Environment::printCompilationConfig(); OATPP_LOGD("Tests", "coroutine size=%d", sizeof(oatpp::async::AbstractCoroutine)); OATPP_LOGD("Tests", "action size=%d", sizeof(oatpp::async::Action)); OATPP_LOGD("Tests", "class count=%d", oatpp::data::mapping::type::ClassId::getClassCount()); auto names = oatpp::data::mapping::type::ClassId::getRegisteredClassNames(); v_int32 i = 0; for(auto& name : names) { OATPP_LOGD("CLASS", "%d --> '%s'", i, name); i ++; } OATPP_RUN_TEST(oatpp::test::base::CommandLineArgumentsTest); OATPP_RUN_TEST(oatpp::test::base::LoggerTest); OATPP_RUN_TEST(oatpp::test::core::data::share::MemoryLabelTest); OATPP_RUN_TEST(oatpp::test::core::data::share::LazyStringMapTest); OATPP_RUN_TEST(oatpp::test::core::data::share::StringTemplateTest); OATPP_RUN_TEST(oatpp::test::core::data::buffer::ProcessorTest); OATPP_RUN_TEST(oatpp::test::core::data::stream::BufferStreamTest); OATPP_RUN_TEST(oatpp::test::core::data::mapping::type::ObjectWrapperTest); OATPP_RUN_TEST(oatpp::test::core::data::mapping::type::TypeTest); OATPP_RUN_TEST(oatpp::test::core::data::mapping::type::StringTest); OATPP_RUN_TEST(oatpp::test::core::data::mapping::type::PrimitiveTest); OATPP_RUN_TEST(oatpp::test::core::data::mapping::type::ListTest); OATPP_RUN_TEST(oatpp::test::core::data::mapping::type::VectorTest); OATPP_RUN_TEST(oatpp::test::core::data::mapping::type::UnorderedSetTest); OATPP_RUN_TEST(oatpp::test::core::data::mapping::type::PairListTest); OATPP_RUN_TEST(oatpp::test::core::data::mapping::type::UnorderedMapTest); OATPP_RUN_TEST(oatpp::test::core::data::mapping::type::AnyTest); OATPP_RUN_TEST(oatpp::test::core::data::mapping::type::EnumTest); OATPP_RUN_TEST(oatpp::test::core::data::mapping::type::ObjectTest); OATPP_RUN_TEST(oatpp::test::core::data::mapping::type::InterpretationTest); OATPP_RUN_TEST(oatpp::test::core::data::mapping::TypeResolverTest); OATPP_RUN_TEST(oatpp::test::core::data::resource::InMemoryDataTest); OATPP_RUN_TEST(oatpp::test::async::LockTest); OATPP_RUN_TEST(oatpp::test::parser::CaretTest); OATPP_RUN_TEST(oatpp::test::core::provider::PoolTest); OATPP_RUN_TEST(oatpp::test::core::provider::PoolTemplateTest); OATPP_RUN_TEST(oatpp::test::parser::json::mapping::EnumTest); OATPP_RUN_TEST(oatpp::test::parser::json::mapping::UnorderedSetTest); OATPP_RUN_TEST(oatpp::test::parser::json::mapping::DeserializerTest); OATPP_RUN_TEST(oatpp::test::parser::json::mapping::DTOMapperPerfTest); OATPP_RUN_TEST(oatpp::test::parser::json::mapping::DTOMapperTest); OATPP_RUN_TEST(oatpp::test::encoding::Base64Test); OATPP_RUN_TEST(oatpp::test::encoding::UnicodeTest); OATPP_RUN_TEST(oatpp::test::network::UrlTest); OATPP_RUN_TEST(oatpp::test::network::ConnectionPoolTest); OATPP_RUN_TEST(oatpp::test::network::monitor::ConnectionMonitorTest); OATPP_RUN_TEST(oatpp::test::network::virtual_::PipeTest); OATPP_RUN_TEST(oatpp::test::network::virtual_::InterfaceTest); OATPP_RUN_TEST(oatpp::test::web::protocol::http::encoding::ChunkedTest); OATPP_RUN_TEST(oatpp::test::web::mime::multipart::StatefulParserTest); OATPP_RUN_TEST(oatpp::test::web::server::HttpRouterTest); OATPP_RUN_TEST(oatpp::test::web::server::api::ApiControllerTest); OATPP_RUN_TEST(oatpp::test::web::server::handler::AuthorizationHandlerTest); { oatpp::test::web::server::ServerStopTest test_virtual(0); test_virtual.run(); oatpp::test::web::server::ServerStopTest test_port(8000); test_port.run(); } { oatpp::test::web::PipelineTest test_virtual(0, 3000); test_virtual.run(); oatpp::test::web::PipelineTest test_port(8000, 3000); test_port.run(); } { oatpp::test::web::PipelineAsyncTest test_virtual(0, 3000); test_virtual.run(); oatpp::test::web::PipelineAsyncTest test_port(8000, 3000); test_port.run(); } { oatpp::test::web::FullTest test_virtual(0, 1000); test_virtual.run(); oatpp::test::web::FullTest test_port(8000, 5); test_port.run(); } { oatpp::test::web::FullAsyncTest test_virtual(0, 1000); test_virtual.run(); oatpp::test::web::FullAsyncTest test_port(8000, 5); test_port.run(); } { oatpp::test::web::FullAsyncClientTest test_virtual(0, 1000); test_virtual.run(20); oatpp::test::web::FullAsyncClientTest test_port(8000, 5); test_port.run(1); } { oatpp::test::web::ClientRetryTest test_virtual(0); test_virtual.run(); oatpp::test::web::ClientRetryTest test_port(8000); test_port.run(); } } } int main() { oatpp::base::Environment::init(); runTests(); /* Print how much objects were created during app running, and what have left-probably leaked */ /* Disable object counting for release builds using '-D OATPP_DISABLE_ENV_OBJECT_COUNTERS' flag for better performance */ std::cout << "\nEnvironment:\n"; std::cout << "objectsCount = " << oatpp::base::Environment::getObjectsCount() << "\n"; std::cout << "objectsCreated = " << oatpp::base::Environment::getObjectsCreated() << "\n\n"; OATPP_ASSERT(oatpp::base::Environment::getObjectsCount() == 0); oatpp::base::Environment::destroy(); return 0; }
vincent-in-black-sesame/oat
test/oatpp/AllTestsMain.cpp
C++
apache-2.0
8,019
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "LockTest.hpp" #include "oatpp/core/data/stream/BufferStream.hpp" #include "oatpp/core/async/Executor.hpp" #include "oatpp/core/async/Lock.hpp" #include <thread> #include <list> namespace oatpp { namespace test { namespace async { namespace { static constexpr v_int32 NUM_SYMBOLS = 20; class Buff { private: oatpp::data::stream::BufferOutputStream *m_buffer; std::mutex m_mutex; public: Buff(oatpp::data::stream::BufferOutputStream *buffer) : m_buffer(buffer) {} void writeChar(char c) { std::lock_guard<std::mutex> lock(m_mutex); m_buffer->writeCharSimple(c); } }; class TestCoroutine : public oatpp::async::Coroutine<TestCoroutine> { private: char m_symbol; Buff *m_buff; oatpp::async::LockGuard m_lockGuard; v_int32 m_counter; public: TestCoroutine(char symbol, Buff *buff, oatpp::async::Lock *lock) : m_symbol(symbol), m_buff(buff), m_lockGuard(lock), m_counter(0) {} Action act() override { return m_lockGuard.lockAsync().next(yieldTo(&TestCoroutine::writeSymbol)); //return yieldTo(&TestCoroutine::writeSymbol); } Action writeSymbol() { if (m_counter < NUM_SYMBOLS) { m_counter++; m_buff->writeChar(m_symbol); return repeat(); } m_lockGuard.unlock(); return finish(); } }; class NotSynchronizedCoroutine : public oatpp::async::Coroutine<NotSynchronizedCoroutine> { private: char m_symbol; Buff *m_buff; v_int32 m_counter; public: NotSynchronizedCoroutine(char symbol, Buff *buff) : m_symbol(symbol), m_buff(buff), m_counter(0) {} Action act() override { if (m_counter < NUM_SYMBOLS) { m_counter++; m_buff->writeChar(m_symbol); return repeat(); } return finish(); } }; class TestCoroutine2 : public oatpp::async::Coroutine<TestCoroutine2> { private: char m_symbol; Buff *m_buff; oatpp::async::Lock *m_lock; public: TestCoroutine2(char symbol, Buff *buff, oatpp::async::Lock *lock) : m_symbol(symbol) , m_buff(buff) , m_lock(lock) {} Action act() override { return oatpp::async::synchronize(m_lock, NotSynchronizedCoroutine::start(m_symbol, m_buff)).next(finish()); } }; void testMethod(char symbol, Buff *buff, oatpp::async::Lock *lock) { std::lock_guard<oatpp::async::Lock> lockGuard(*lock); for (v_int32 i = 0; i < NUM_SYMBOLS; i++) { buff->writeChar(symbol); } } bool checkSymbol(char symbol, const char* data, v_buff_size size) { for (v_buff_size i = 0; i < size; i++) { if (data[i] == symbol && size - i >= NUM_SYMBOLS) { for (v_buff_size j = 0; j < NUM_SYMBOLS; j++) { if (data[i + j] != symbol) { OATPP_LOGD("aaa", "j pos=%d", j); return false; } } return true; } } OATPP_LOGD("aaa", "No symbol found"); return false; } bool checkSymbol(char symbol, const oatpp::String& str) { return checkSymbol(symbol, str->data(), str->size()); } } void LockTest::onRun() { oatpp::async::Lock lock; oatpp::data::stream::BufferOutputStream buffer; Buff buff(&buffer); oatpp::async::Executor executor(10, 1, 1); for (v_int32 c = 0; c <= 127; c++) { executor.execute<TestCoroutine>((char)c, &buff, &lock); } for (v_int32 c = 128; c <= 200; c++) { executor.execute<TestCoroutine2>((char)c, &buff, &lock); } std::list<std::thread> threads; for (v_int32 c = 201; c <= 255; c++) { threads.push_back(std::thread(testMethod, (char)c, &buff, &lock)); } for (std::thread &thread : threads) { thread.join(); } executor.waitTasksFinished(); executor.stop(); executor.join(); auto result = buffer.toString(); for (v_int32 c = 0; c <= 255; c++) { bool check = checkSymbol((char)c, result); if(!check) { v_int32 code = c; auto str = oatpp::String((const char*)&c, 1); OATPP_LOGE(TAG, "Failed for symbol %d, '%s'", code, str->data()); } OATPP_ASSERT(check); } } }}}
vincent-in-black-sesame/oat
test/oatpp/core/async/LockTest.cpp
C++
apache-2.0
4,939
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_async_LockTest_hpp #define oatpp_test_async_LockTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace async { class LockTest : public UnitTest{ public: LockTest():UnitTest("TEST[async::LockTest]"){} void onRun() override; }; }}} #endif // oatpp_test_async_LockTest_hpp
vincent-in-black-sesame/oat
test/oatpp/core/async/LockTest.hpp
C++
apache-2.0
1,330
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "CommandLineArgumentsTest.hpp" #include "oatpp/core/base/CommandLineArguments.hpp" #include <cstring> namespace oatpp { namespace test { namespace base { void CommandLineArgumentsTest::onRun() { /* -k -c 100 -n 500000 "http://127.0.0.1:8000/" */ int argc = 6; const char * argv[] = {"-k", "-c", "100", "-n", "500000", "http://127.0.0.1:8000/"}; oatpp::base::CommandLineArguments args(argc, argv); OATPP_ASSERT(args.getArgumentIndex("-k") == 0); OATPP_ASSERT(args.getArgumentIndex("-c") == 1); OATPP_ASSERT(args.getArgumentIndex("100") == 2); OATPP_ASSERT(args.getArgumentIndex("-n") == 3); OATPP_ASSERT(args.getArgumentIndex("500000") == 4); OATPP_ASSERT(args.getArgumentIndex("http://127.0.0.1:8000/") == 5); OATPP_ASSERT(args.getArgumentIndex("not-existing-arg") == -1); OATPP_ASSERT(args.hasArgument("-k")); OATPP_ASSERT(args.hasArgument("not-existing-arg") == false); OATPP_ASSERT(std::strcmp(args.getArgumentStartingWith("http"), "http://127.0.0.1:8000/") == 0); OATPP_ASSERT(std::strcmp(args.getArgumentStartingWith("tcp", "tcp://default/"), "tcp://default/") == 0); OATPP_ASSERT(std::strcmp(args.getNamedArgumentValue("-c"), "100") == 0); OATPP_ASSERT(std::strcmp(args.getNamedArgumentValue("-c", nullptr), "100") == 0); OATPP_ASSERT(std::strcmp(args.getNamedArgumentValue("-n"), "500000") == 0); OATPP_ASSERT(std::strcmp(args.getNamedArgumentValue("--non-existing", "default"), "default") == 0); } }}}
vincent-in-black-sesame/oat
test/oatpp/core/base/CommandLineArgumentsTest.cpp
C++
apache-2.0
2,484
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_base_CommandLineArgumentsTest_hpp #define oatpp_test_base_CommandLineArgumentsTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace base { /** * Test command line arguments parsing. */ class CommandLineArgumentsTest : public UnitTest{ public: CommandLineArgumentsTest():UnitTest("TEST[base::CommandLineArgumentsTest]"){} void onRun() override; }; }}} #endif /* oatpp_test_core_base_CommandLineArgumentsTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/core/base/CommandLineArgumentsTest.hpp
C++
apache-2.0
1,485
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * Benedikt-Alexander Mokroß <oatpp@bamkrs.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "LoggerTest.hpp" namespace oatpp { namespace test { namespace base { OATPP_LOG_CATEGORY(LoggerTest::TESTCATEGORY, "LogCategory", true); void LoggerTest::onRun() { auto logger = std::static_pointer_cast<oatpp::base::DefaultLogger>(oatpp::base::Environment::getLogger()); OATPP_LOGV("LoggerTest", "Verbose Log"); OATPP_LOGD("LoggerTest", "Debug Log"); OATPP_LOGI("LoggerTest", "Info Log"); OATPP_LOGW("LoggerTest", "Warning Log"); OATPP_LOGE("LoggerTest", "Error Log"); OATPP_LOGI("LoggerTest", " --- Disabling Debug Log"); logger->disablePriority(oatpp::base::DefaultLogger::PRIORITY_D); OATPP_ASSERT(!logger->isLogPriorityEnabled(oatpp::base::DefaultLogger::PRIORITY_D)) OATPP_LOGV("LoggerTest", "Verbose Log"); OATPP_LOGD("LoggerTest", "Debug Log"); OATPP_LOGI("LoggerTest", "Info Log"); OATPP_LOGW("LoggerTest", "Warning Log"); OATPP_LOGE("LoggerTest", "Error Log"); OATPP_LOGI("LoggerTest", " --- Enabling Debug Log again"); logger->enablePriority(oatpp::base::DefaultLogger::PRIORITY_D); OATPP_ASSERT(logger->isLogPriorityEnabled(oatpp::base::DefaultLogger::PRIORITY_D)) OATPP_LOGV("LoggerTest", "Verbose Log"); OATPP_LOGD("LoggerTest", "Debug Log"); OATPP_LOGI("LoggerTest", "Info Log"); OATPP_LOGW("LoggerTest", "Warning Log"); OATPP_LOGE("LoggerTest", "Error Log"); OATPP_LOGI(TESTCATEGORY, " --- Log-Test with category"); OATPP_LOGV(TESTCATEGORY, "Verbose Log"); OATPP_LOGD(TESTCATEGORY, "Debug Log"); OATPP_LOGI(TESTCATEGORY, "Info Log"); OATPP_LOGW(TESTCATEGORY, "Warning Log"); OATPP_LOGE(TESTCATEGORY, "Error Log"); OATPP_LOGI(TESTCATEGORY, " --- Disabling Debug Log for category"); TESTCATEGORY.disablePriority(oatpp::base::DefaultLogger::PRIORITY_D); OATPP_ASSERT(!TESTCATEGORY.isLogPriorityEnabled(oatpp::base::DefaultLogger::PRIORITY_D)) OATPP_LOGV(TESTCATEGORY, "Verbose Log"); OATPP_LOGD(TESTCATEGORY, "Debug Log"); OATPP_LOGI(TESTCATEGORY, "Info Log"); OATPP_LOGW(TESTCATEGORY, "Warning Log"); OATPP_LOGE(TESTCATEGORY, "Error Log"); } }}}
vincent-in-black-sesame/oat
test/oatpp/core/base/LoggerTest.cpp
C++
apache-2.0
3,120
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * Benedikt-Alexander Mokroß <oatpp@bamkrs.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_base_LoggerTest_hpp #define oatpp_test_base_LoggerTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace base { class LoggerTest : public UnitTest{ public: LoggerTest():UnitTest("TEST[base::LoggerTest]"){} void onRun() override; OATPP_DECLARE_LOG_CATEGORY(TESTCATEGORY); }; }}} #endif /* oatpp_test_base_LoggerTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/core/base/LoggerTest.hpp
C++
apache-2.0
1,457
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "ProcessorTest.hpp" #include "oatpp/core/data/stream/BufferStream.hpp" #include "oatpp/core/data/buffer/Processor.hpp" #include "oatpp/core/async/Executor.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace buffer { namespace { typedef oatpp::data::buffer::Processor Processor; class BaseProcessor : public oatpp::data::buffer::Processor { private: v_int32 m_bufferSize; oatpp::data::stream::BufferOutputStream m_buffer; public: BaseProcessor(v_int32 bufferSize) : m_bufferSize(bufferSize) {} oatpp::v_io_size suggestInputStreamReadSize() override { return m_bufferSize; } virtual void process(p_char8 data, v_buff_size size) = 0; v_int32 iterate(oatpp::data::buffer::InlineReadData& dataIn, oatpp::data::buffer::InlineReadData& dataOut) override { if(dataOut.bytesLeft > 0) { return Error::FLUSH_DATA_OUT; } if(dataIn.currBufferPtr != nullptr) { while (dataIn.bytesLeft > 0 && m_buffer.getCurrentPosition() < m_bufferSize) { m_buffer.writeSimple(dataIn.currBufferPtr, 1); dataIn.inc(1); } if(m_buffer.getCurrentPosition() < m_bufferSize) { return Error::PROVIDE_DATA_IN; } dataOut.set(m_buffer.getData(), m_buffer.getCurrentPosition()); process(m_buffer.getData(), m_buffer.getCurrentPosition()); m_buffer.setCurrentPosition(0); return Error::FLUSH_DATA_OUT; } else if(m_buffer.getCurrentPosition() > 0) { dataOut.set(m_buffer.getData(), m_buffer.getCurrentPosition()); process(m_buffer.getData(), m_buffer.getCurrentPosition()); m_buffer.setCurrentPosition(0); return Error::FLUSH_DATA_OUT; } dataOut.set(nullptr, 0); return Error::FINISHED; } }; class ProcessorToUpper : public BaseProcessor { public: ProcessorToUpper(v_int32 bufferSize) : BaseProcessor(bufferSize) {} void process(p_char8 data, v_buff_size size) override { utils::String::upperCase_ASCII(data, size); } }; class ProcessorToLower : public BaseProcessor { public: ProcessorToLower(v_int32 bufferSize) : BaseProcessor(bufferSize) {} void process(p_char8 data, v_buff_size size) override { utils::String::lowerCase_ASCII(data, size); } }; class ProcessorChangeLetter : public BaseProcessor { private: v_char8 m_fromChar; v_char8 m_toChar; public: ProcessorChangeLetter(v_char8 fromChar, v_char8 toChar, v_int32 bufferSize) : BaseProcessor(bufferSize) , m_fromChar(fromChar) , m_toChar(toChar) {} void process(p_char8 data, v_buff_size size) override { for(v_buff_size i = 0; i < size; i ++) { if(data[i] == m_fromChar) { data[i] = m_toChar; } } } }; class TestCoroutine : public oatpp::async::Coroutine<TestCoroutine> { public: static std::atomic<v_int64> COUNTER; private: oatpp::String m_data; oatpp::String m_etalon; std::shared_ptr<oatpp::data::stream::ReadCallback> m_readCallback; std::shared_ptr<oatpp::data::stream::BufferOutputStream> m_writeCallback; std::shared_ptr<oatpp::data::buffer::Processor> m_processor; std::shared_ptr<oatpp::data::buffer::IOBuffer> m_buffer; public: TestCoroutine(const oatpp::String &mData, const oatpp::String &mEtalon, const std::shared_ptr<oatpp::data::stream::ReadCallback> &mReadCallback, const std::shared_ptr<oatpp::data::stream::BufferOutputStream> &mWriteCallback, const std::shared_ptr<Processor> &mProcessor, const std::shared_ptr<oatpp::data::buffer::IOBuffer> &mBuffer) : m_data(mData) , m_etalon(mEtalon) , m_readCallback(mReadCallback) , m_writeCallback(mWriteCallback) , m_processor(mProcessor) , m_buffer(mBuffer) { COUNTER ++; } ~TestCoroutine() { COUNTER --; } Action act() { return oatpp::data::stream::transferAsync(m_readCallback, m_writeCallback, 0, m_buffer, m_processor) .next(yieldTo(&TestCoroutine::compare)); } Action compare() { auto result = m_writeCallback->toString(); OATPP_ASSERT(m_etalon == result); return finish(); } }; std::atomic<v_int64> TestCoroutine::COUNTER(0); oatpp::String runTestCase(const oatpp::String& data, v_int32 p1N, v_int32 p2N, v_int32 p3N, v_int32 bufferSize) { oatpp::data::stream::BufferInputStream inStream(data); oatpp::data::stream::BufferOutputStream outStream; oatpp::data::buffer::ProcessingPipeline processor({ oatpp::base::ObjectHandle<Processor>(std::make_shared<ProcessorToUpper>(p1N)), oatpp::base::ObjectHandle<Processor>(std::make_shared<ProcessorChangeLetter>('A', '-', p2N)), oatpp::base::ObjectHandle<Processor>(std::make_shared<ProcessorToLower>(p3N)), }); std::unique_ptr<v_char8[]> buffer(new v_char8[bufferSize]); oatpp::data::stream::transfer(&inStream, &outStream, 0, buffer.get(), bufferSize, &processor); return outStream.toString(); } } void ProcessorTest::onRun() { oatpp::String data = ">aaaaa0123456789bbbbb<"; oatpp::String etalon = ">-----0123456789bbbbb<"; for(v_int32 p1N = 1; p1N < 11; p1N ++) { for(v_int32 p2N = 1; p2N < 11; p2N ++) { for (v_int32 p3N = 1; p3N < 11; p3N++) { for (v_int32 buffSize = 1; buffSize < 11; buffSize++) { auto result = runTestCase(data, p1N, p2N, p3N, buffSize); if (result != etalon) { OATPP_LOGD(TAG, "error[%d, %d, %d, b=%d] result='%s'", p1N, p2N, p3N, buffSize, result->data()); } OATPP_ASSERT(result == etalon); } } } } { v_char8 buffer[1024]; for(v_int32 i = 1; i < 30; i++) { oatpp::data::stream::BufferInputStream inStream(data); oatpp::data::stream::BufferOutputStream outStream; auto progress = oatpp::data::stream::transfer(&inStream, &outStream, 0, buffer, i); auto result = outStream.toString(); OATPP_ASSERT(result == data); OATPP_ASSERT(inStream.getCurrentPosition() == progress); } } oatpp::async::Executor executor; { for(v_int32 p1N = 1; p1N < 11; p1N ++) { for(v_int32 p2N = 1; p2N < 11; p2N ++) { for (v_int32 p3N = 1; p3N < 11; p3N++) { auto inStream = std::make_shared<oatpp::data::stream::BufferInputStream>(data); auto outStream = std::make_shared<oatpp::data::stream::BufferOutputStream>(); auto processor = std::shared_ptr<oatpp::data::buffer::ProcessingPipeline>(new oatpp::data::buffer::ProcessingPipeline({ oatpp::base::ObjectHandle<Processor>(std::make_shared<ProcessorToUpper>(p1N)), oatpp::base::ObjectHandle<Processor>(std::make_shared<ProcessorChangeLetter>('A', '-', p2N)), oatpp::base::ObjectHandle<Processor>(std::make_shared<ProcessorToLower>(p3N)), })); auto buffer = std::make_shared<oatpp::data::buffer::IOBuffer>(); executor.execute<TestCoroutine>(data, etalon, inStream, outStream, processor, buffer); } } } while(TestCoroutine::COUNTER > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } executor.waitTasksFinished(); executor.stop(); executor.join(); } }}}}}
vincent-in-black-sesame/oat
test/oatpp/core/data/buffer/ProcessorTest.cpp
C++
apache-2.0
8,190
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_core_data_buffer_ProcessorTest_hpp #define oatpp_test_core_data_buffer_ProcessorTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace buffer { class ProcessorTest : public UnitTest{ public: ProcessorTest():UnitTest("TEST[core::data::buffer::ProcessorTest]"){} void onRun() override; }; }}}}} #endif // oatpp_test_core_data_buffer_ProcessorTest_hpp
vincent-in-black-sesame/oat
test/oatpp/core/data/buffer/ProcessorTest.hpp
C++
apache-2.0
1,443
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "TypeResolverTest.hpp" #include "oatpp/core/data/mapping/TypeResolver.hpp" #include "oatpp/core/Types.hpp" #include "oatpp/core/macro/codegen.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace { #include OATPP_CODEGEN_BEGIN(DTO) class TestDto : public oatpp::DTO { DTO_INIT(TestDto, DTO) DTO_FIELD(String, f_str); DTO_FIELD(Int8, f_int8); DTO_FIELD(UInt8, f_uint8); DTO_FIELD(Int16, f_int16); DTO_FIELD(UInt16, f_uint16); DTO_FIELD(Int32, f_int32); DTO_FIELD(UInt32, f_uint32); DTO_FIELD(Int64, f_int64); DTO_FIELD(UInt64, f_uint64); DTO_FIELD(Float32, f_float32); DTO_FIELD(Float64, f_float64); DTO_FIELD(Boolean, f_bool); DTO_FIELD(Vector<String>, f_vector); DTO_FIELD(List<String>, f_list); DTO_FIELD(UnorderedSet<String>, f_set); DTO_FIELD(Fields<String>, f_fields); DTO_FIELD(UnorderedFields<String>, f_unordered_fields); DTO_FIELD(Any, f_any); DTO_FIELD(Object<TestDto>, f_dto); }; #include OATPP_CODEGEN_END(DTO) } void TypeResolverTest::onRun() { oatpp::data::mapping::TypeResolver::Cache cache; oatpp::data::mapping::TypeResolver tr; auto dto1 = TestDto::createShared(); dto1->f_str = "hello dto1"; dto1->f_int8 = 8; dto1->f_uint8 = 88; dto1->f_int16 = 16; dto1->f_uint16 = 1616; dto1->f_int32 = 32; dto1->f_uint32 = 3232; dto1->f_int64 = 64; dto1->f_uint64 = 6464; dto1->f_float32 = 0.32f; dto1->f_float64 = 0.64; dto1->f_bool = true; dto1->f_vector = {"hello", "world"}; dto1->f_list = {"hello", "world"}; dto1->f_set = {"hello", "world"}; dto1->f_fields = {{"hello", "world"}}; dto1->f_unordered_fields = {{"hello", "world"}}; dto1->f_any = oatpp::String("hey ANY!"); dto1->f_dto = TestDto::createShared(); { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_str"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::String::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_str"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::String::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_str.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto", "f_str"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::String::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto", "f_str"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::String::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_dto->f_str.get()); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Int8 { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_int8"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::Int8::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_int8"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::Int8::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_int8.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto", "f_int8"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::Int8::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto", "f_int8"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::Int8::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_dto->f_int8.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_uint8"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::UInt8::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_uint8"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::UInt8::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_uint8.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto", "f_uint8"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::UInt8::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto", "f_uint8"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::UInt8::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_dto->f_uint8.get()); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Int16 { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_int16"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::Int16::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_int16"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::Int16::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_int16.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto", "f_int16"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::Int16::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto", "f_int16"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::Int16::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_dto->f_int16.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_uint16"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::UInt16::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_uint16"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::UInt16::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_uint16.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto", "f_uint16"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::UInt16::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto", "f_uint16"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::UInt16::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_dto->f_uint16.get()); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Int32 { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_int32"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::Int32::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_int32"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::Int32::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_int32.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto", "f_int32"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::Int32::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto", "f_int32"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::Int32::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_dto->f_int32.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_uint32"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::UInt32::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_uint32"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::UInt32::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_uint32.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto", "f_uint32"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::UInt32::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto", "f_uint32"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::UInt32::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_dto->f_uint32.get()); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Int64 { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_int64"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::Int64::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_int64"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::Int64::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_int64.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto", "f_int64"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::Int64::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto", "f_int64"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::Int64::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_dto->f_int64.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_uint64"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::UInt64::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_uint64"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::UInt64::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_uint64.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto", "f_uint64"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::UInt64::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto", "f_uint64"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::UInt64::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_dto->f_uint64.get()); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Float32 { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_float32"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::Float32::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_float32"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::Float32::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_float32.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto", "f_float32"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::Float32::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto", "f_float32"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::Float32::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_dto->f_float32.get()); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Float64 { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_float64"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::Float64::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_float64"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::Float64::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_float64.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto", "f_float64"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::Float64::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto", "f_float64"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::Float64::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_dto->f_float64.get()); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Boolean { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_bool"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::Boolean::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_bool"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::Boolean::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_bool.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto", "f_bool"}, cache); OATPP_ASSERT(type != nullptr); OATPP_ASSERT(type->classId.id == oatpp::Boolean::Class::CLASS_ID.id); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto", "f_bool"}, cache); OATPP_ASSERT(val.getValueType()->classId.id == oatpp::Boolean::Class::CLASS_ID.id); OATPP_ASSERT(val.get() == dto1->f_dto->f_bool.get()); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Vector { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_vector"}, cache); OATPP_ASSERT(type == dto1->f_vector.getValueType()); auto val = tr.resolveObjectPropertyValue(dto1, {"f_vector"}, cache); OATPP_ASSERT(val.getValueType() == dto1->f_vector.getValueType()); OATPP_ASSERT(val.get() == dto1->f_vector.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto", "f_vector"}, cache); OATPP_ASSERT(type == dto1->f_dto->f_vector.getValueType()); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto", "f_vector"}, cache); OATPP_ASSERT(val.getValueType() == dto1->f_dto->f_vector.getValueType()); OATPP_ASSERT(val.get() == dto1->f_dto->f_vector.get()); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // List { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_list"}, cache); OATPP_ASSERT(type == dto1->f_list.getValueType()); auto val = tr.resolveObjectPropertyValue(dto1, {"f_list"}, cache); OATPP_ASSERT(val.getValueType() == dto1->f_list.getValueType()); OATPP_ASSERT(val.get() == dto1->f_list.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto", "f_list"}, cache); OATPP_ASSERT(type == dto1->f_dto->f_list.getValueType()); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto", "f_list"}, cache); OATPP_ASSERT(val.getValueType() == dto1->f_dto->f_list.getValueType()); OATPP_ASSERT(val.get() == dto1->f_dto->f_list.get()); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Set { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_set"}, cache); OATPP_ASSERT(type == dto1->f_set.getValueType()); auto val = tr.resolveObjectPropertyValue(dto1, {"f_set"}, cache); OATPP_ASSERT(val.getValueType() == dto1->f_set.getValueType()); OATPP_ASSERT(val.get() == dto1->f_set.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto", "f_set"}, cache); OATPP_ASSERT(type == dto1->f_dto->f_set.getValueType()); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto", "f_set"}, cache); OATPP_ASSERT(val.getValueType() == dto1->f_dto->f_set.getValueType()); OATPP_ASSERT(val.get() == dto1->f_dto->f_set.get()); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Fields { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_fields"}, cache); OATPP_ASSERT(type == dto1->f_fields.getValueType()); auto val = tr.resolveObjectPropertyValue(dto1, {"f_fields"}, cache); OATPP_ASSERT(val.getValueType() == dto1->f_fields.getValueType()); OATPP_ASSERT(val.get() == dto1->f_fields.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto", "f_fields"}, cache); OATPP_ASSERT(type == dto1->f_dto->f_fields.getValueType()); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto", "f_fields"}, cache); OATPP_ASSERT(val.getValueType() == dto1->f_dto->f_fields.getValueType()); OATPP_ASSERT(val.get() == dto1->f_dto->f_fields.get()); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // UnorderedFields { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_unordered_fields"}, cache); OATPP_ASSERT(type == dto1->f_unordered_fields.getValueType()); auto val = tr.resolveObjectPropertyValue(dto1, {"f_unordered_fields"}, cache); OATPP_ASSERT(val.getValueType() == dto1->f_unordered_fields.getValueType()); OATPP_ASSERT(val.get() == dto1->f_unordered_fields.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto", "f_unordered_fields"}, cache); OATPP_ASSERT(type == dto1->f_dto->f_unordered_fields.getValueType()); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto", "f_unordered_fields"}, cache); OATPP_ASSERT(val.getValueType() == dto1->f_dto->f_unordered_fields.getValueType()); OATPP_ASSERT(val.get() == dto1->f_dto->f_unordered_fields.get()); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Any { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_any"}, cache); OATPP_ASSERT(type == dto1->f_any.getValueType()); auto val = tr.resolveObjectPropertyValue(dto1, {"f_any"}, cache); OATPP_ASSERT(val.getValueType() == dto1->f_any.getValueType()); OATPP_ASSERT(val.get() == dto1->f_any.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto", "f_any"}, cache); OATPP_ASSERT(type == dto1->f_dto->f_any.getValueType()); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto", "f_any"}, cache); OATPP_ASSERT(val.getValueType() == dto1->f_dto->f_any.getValueType()); OATPP_ASSERT(val.get() == dto1->f_dto->f_any.get()); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Dto { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto"}, cache); OATPP_ASSERT(type == dto1->f_dto.getValueType()); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto"}, cache); OATPP_ASSERT(val.getValueType() == dto1->f_dto.getValueType()); OATPP_ASSERT(val.get() == dto1->f_dto.get()); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto", "f_dto"}, cache); OATPP_ASSERT(type == dto1->f_dto->f_dto.getValueType()); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto", "f_dto"}, cache); OATPP_ASSERT(val.getValueType() == dto1->f_dto->f_dto.getValueType()); OATPP_ASSERT(val.get() == dto1->f_dto->f_dto.get()); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Non-Existing { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_non_existing"}, cache); OATPP_ASSERT(type == nullptr); auto val = tr.resolveObjectPropertyValue(dto1, {"f_non_existing"}, cache); OATPP_ASSERT(val.getValueType() == oatpp::Void::Class::getType()); OATPP_ASSERT(val == nullptr); } { auto type = tr.resolveObjectPropertyType(oatpp::Object<TestDto>::Class::getType(), {"f_dto", "f_non_existing"}, cache); OATPP_ASSERT(type == nullptr); auto val = tr.resolveObjectPropertyValue(dto1, {"f_dto", "f_non_existing"}, cache); OATPP_ASSERT(val.getValueType() == oatpp::Void::Class::getType()); OATPP_ASSERT(val == nullptr); } } }}}}}
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/TypeResolverTest.cpp
C++
apache-2.0
21,886
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_core_data_mapping_TypeResolverTest_hpp #define oatpp_test_core_data_mapping_TypeResolverTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { class TypeResolverTest : public UnitTest{ public: TypeResolverTest():UnitTest("TEST[core::data::mapping::type::TypeResolverTest]"){} void onRun() override; }; }}}}} #endif /* oatpp_test_core_data_mapping_TypeResolverTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/TypeResolverTest.hpp
C++
apache-2.0
1,475
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "AnyTest.hpp" #include "oatpp/core/data/mapping/type/Any.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/core/macro/codegen.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { namespace { #include OATPP_CODEGEN_BEGIN(DTO) class Dto1 : public oatpp::DTO { DTO_INIT(Dto1, DTO); }; class Dto2 : public oatpp::DTO { DTO_INIT(Dto2, DTO); }; class Test : public oatpp::DTO { DTO_INIT(Test, DTO); DTO_FIELD(oatpp::Any, any); }; #include OATPP_CODEGEN_END(DTO) } void AnyTest::onRun() { { OATPP_LOGI(TAG, "Test default constructor..."); oatpp::Any any; OATPP_ASSERT(!any); OATPP_ASSERT(any.getValueType() == oatpp::data::mapping::type::__class::Any::getType()); OATPP_ASSERT(any.getStoredType() == nullptr); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test nullptr constructor..."); oatpp::Any any(nullptr); OATPP_ASSERT(!any); OATPP_ASSERT(any.getValueType() == oatpp::data::mapping::type::__class::Any::getType()); OATPP_ASSERT(any.getStoredType() == nullptr); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test retrieve()..."); oatpp::Any any(oatpp::String("Hello Any!")); OATPP_ASSERT(any); OATPP_ASSERT(any.getValueType() == oatpp::data::mapping::type::__class::Any::getType()); OATPP_ASSERT(any.getStoredType() == oatpp::data::mapping::type::__class::String::getType()); auto str = any.retrieve<oatpp::String>(); OATPP_ASSERT(str == "Hello Any!"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test store()..."); oatpp::Any any(oatpp::Int32(32)); OATPP_ASSERT(any); OATPP_ASSERT(any.getValueType() == oatpp::data::mapping::type::__class::Any::getType()); OATPP_ASSERT(any.getStoredType() == oatpp::data::mapping::type::__class::Int32::getType()); any.store(oatpp::String("Hello Any!")); OATPP_ASSERT(any); OATPP_ASSERT(any.getValueType() == oatpp::data::mapping::type::__class::Any::getType()); OATPP_ASSERT(any.getStoredType() == oatpp::data::mapping::type::__class::String::getType()); auto str = any.retrieve<oatpp::String>(); OATPP_ASSERT(str == "Hello Any!"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test retrieve() class check..."); oatpp::Any any(Dto1::createShared()); OATPP_ASSERT(any); OATPP_ASSERT(any.getValueType() == oatpp::data::mapping::type::__class::Any::getType()); OATPP_ASSERT(any.getStoredType() == Object<Dto1>::Class::getType()); bool wasError = false; try { auto obj = any.retrieve<oatpp::Object<Dto2>>(); // wrong object } catch (std::runtime_error&) { wasError = true; } OATPP_ASSERT(wasError); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test copy-assign operator..."); oatpp::Any any1(oatpp::String("Hello!")); oatpp::Any any2; any2 = any1; OATPP_ASSERT(any1); OATPP_ASSERT(any2); OATPP_ASSERT(any1.getValueType() == oatpp::data::mapping::type::__class::Any::getType()); OATPP_ASSERT(any2.getValueType() == oatpp::data::mapping::type::__class::Any::getType()); OATPP_ASSERT(any1.getStoredType() == oatpp::data::mapping::type::__class::String::getType()); OATPP_ASSERT(any2.getStoredType() == oatpp::data::mapping::type::__class::String::getType()); OATPP_ASSERT(any1 == any2); OATPP_ASSERT(any1.getPtr().get() != any2.getPtr().get()); auto str1 = any1.retrieve<oatpp::String>(); auto str2 = any2.retrieve<oatpp::String>(); OATPP_ASSERT(str1 == str2); OATPP_ASSERT(str1.get() == str2.get() && str1 == "Hello!"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test move-assign operator..."); oatpp::Any any1(oatpp::String("Hello!")); oatpp::Any any2; any2 = std::move(any1); OATPP_ASSERT(!any1); OATPP_ASSERT(any2); OATPP_ASSERT(any1.getValueType() == oatpp::data::mapping::type::__class::Any::getType()); OATPP_ASSERT(any2.getValueType() == oatpp::data::mapping::type::__class::Any::getType()); OATPP_ASSERT(any1.getStoredType() == nullptr); OATPP_ASSERT(any2.getStoredType() == oatpp::data::mapping::type::__class::String::getType()); OATPP_ASSERT(any1 != any2); OATPP_ASSERT(any1.getPtr().get() != any2.getPtr().get()); auto str1 = any1.retrieve<oatpp::String>(); auto str2 = any2.retrieve<oatpp::String>(); OATPP_ASSERT(str1 != str2); OATPP_ASSERT(str2 == "Hello!"); OATPP_LOGI(TAG, "OK"); } } }}}}}}
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/AnyTest.cpp
C++
apache-2.0
5,518
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_core_data_mapping_type_AnyTest_hpp #define oatpp_test_core_data_mapping_type_AnyTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { class AnyTest : public UnitTest{ public: AnyTest():UnitTest("TEST[core::data::mapping::type::AnyTest]"){} void onRun() override; }; }}}}}} #endif /* oatpp_test_core_data_mapping_type_AnyTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/AnyTest.hpp
C++
apache-2.0
1,455
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "EnumTest.hpp" #include "oatpp/core/Types.hpp" #include "oatpp/core/macro/codegen.hpp" #include <unordered_map> namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { #include OATPP_CODEGEN_BEGIN(DTO) ENUM(Enum0, v_int32) ENUM(Enum1, v_int32, VALUE(V1, 1), VALUE(V2, 2), VALUE(V3, 3) ) ENUM(Enum2, v_int32, VALUE(NAME_1, 1, "name-1"), VALUE(NAME_2, 2, "name-2"), VALUE(NAME_3, 3, "name-3") ) ENUM(Enum3, v_int32, VALUE(V_1, 1, "v-1", "description_1"), VALUE(V_2, 2, "v-2", "description_2"), VALUE(V_3, 3, "v-3", "description_3") ) #include OATPP_CODEGEN_END(DTO) void EnumTest::onRun() { { OATPP_LOGI(TAG, "Check Hash..."); { auto v = std::hash<oatpp::Enum<Enum1>>{}(oatpp::Enum<Enum1>()); OATPP_ASSERT(v == 0); } { auto v = std::hash<oatpp::Enum<Enum1>>{}(oatpp::Enum<Enum1>(Enum1::V1)); OATPP_ASSERT(v == 1); } { auto v = std::hash<oatpp::Enum<Enum1>>{}(oatpp::Enum<Enum1>(Enum1::V2)); OATPP_ASSERT(v == 2); } { auto v = std::hash<oatpp::Enum<Enum1>>{}(oatpp::Enum<Enum1>(Enum1::V3)); OATPP_ASSERT(v == 3); } std::unordered_map<oatpp::Enum<Enum1>, oatpp::String> map({ {Enum1::V1, "v1"}, {Enum1::V2, "v2"}, {Enum1::V3, "v3"}, }); OATPP_ASSERT(map.size() == 3); OATPP_ASSERT(map[Enum1::V1] == "v1"); OATPP_ASSERT(map[Enum1::V2] == "v2"); OATPP_ASSERT(map[Enum1::V3] == "v3"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Check Meta..."); { const auto &entries = oatpp::Enum<Enum0>::getEntries(); OATPP_ASSERT(entries.size() == 0); } { const auto &v = oatpp::Enum<Enum1>::getEntries(); OATPP_ASSERT(v.size() == 3); OATPP_ASSERT(v[0].index == 0 && v[0].name == "V1" && v[0].value == Enum1::V1 && v[0].description == nullptr); OATPP_ASSERT(v[1].index == 1 && v[1].name == "V2" && v[1].value == Enum1::V2 && v[1].description == nullptr); OATPP_ASSERT(v[2].index == 2 && v[2].name == "V3" && v[2].value == Enum1::V3 && v[2].description == nullptr); } { const auto &v = oatpp::Enum<Enum2>::getEntries(); OATPP_ASSERT(v.size() == 3); OATPP_ASSERT(v[0].index == 0 && v[0].name == "name-1" && v[0].value == Enum2::NAME_1 && v[0].description == nullptr); OATPP_ASSERT(v[1].index == 1 && v[1].name == "name-2" && v[1].value == Enum2::NAME_2 && v[1].description == nullptr); OATPP_ASSERT(v[2].index == 2 && v[2].name == "name-3" && v[2].value == Enum2::NAME_3 && v[2].description == nullptr); } { const auto &v = oatpp::Enum<Enum3>::getEntries(); OATPP_ASSERT(v.size() == 3); OATPP_ASSERT(v[0].index == 0 && v[0].name == "v-1" && v[0].value == Enum3::V_1 && v[0].description == "description_1"); OATPP_ASSERT(v[1].index == 1 && v[1].name == "v-2" && v[1].value == Enum3::V_2 && v[1].description == "description_2"); OATPP_ASSERT(v[2].index == 2 && v[2].name == "v-3" && v[2].value == Enum3::V_3 && v[2].description == "description_3"); } OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Declaration..."); OATPP_ASSERT(oatpp::Enum<Enum2>::Interpreter::notNull == false); OATPP_ASSERT(oatpp::Enum<Enum2>::NotNull::Interpreter::notNull == true); OATPP_ASSERT(oatpp::Enum<Enum2>::AsString::Interpreter::notNull == false); OATPP_ASSERT(oatpp::Enum<Enum2>::AsString::NotNull::Interpreter::notNull == true); OATPP_ASSERT(oatpp::Enum<Enum2>::AsNumber::Interpreter::notNull == false); OATPP_ASSERT(oatpp::Enum<Enum2>::AsNumber::NotNull::Interpreter::notNull == true); OATPP_ASSERT(oatpp::Enum<Enum2>::NotNull::AsString::Interpreter::notNull == true); OATPP_ASSERT(oatpp::Enum<Enum2>::NotNull::AsNumber::Interpreter::notNull == true); auto pd1 = static_cast<const oatpp::data::mapping::type::__class::AbstractEnum::PolymorphicDispatcher*>( oatpp::Enum<Enum2>::Class::getType()->polymorphicDispatcher ); auto pd2 = static_cast<const oatpp::data::mapping::type::__class::AbstractEnum::PolymorphicDispatcher*>( oatpp::Enum<Enum2>::NotNull::Class::getType()->polymorphicDispatcher ); OATPP_ASSERT(pd1->notNull == false); OATPP_ASSERT(pd2->notNull == true); { auto interEnum = pd1->getInterpretedEnum(); OATPP_ASSERT(interEnum.size() == 3); OATPP_ASSERT(interEnum[0].getStoredType() == oatpp::String::Class::getType()); } OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test Interpreter AsString..."); oatpp::data::mapping::type::EnumInterpreterError e = oatpp::data::mapping::type::EnumInterpreterError::OK; auto inter = oatpp::Enum<Enum2>::AsString::Interpreter::toInterpretation(oatpp::Enum<Enum2>::AsString(Enum2::NAME_1), e); OATPP_ASSERT(inter.getValueType() == oatpp::String::Class::getType()); OATPP_ASSERT(e == oatpp::data::mapping::type::EnumInterpreterError::OK); auto interValue = inter.cast<oatpp::String>(); OATPP_ASSERT(interValue == "name-1"); oatpp::Void voidValue = oatpp::Enum<Enum2>::AsString::Interpreter::fromInterpretation(interValue, e); OATPP_ASSERT(voidValue.getValueType() == oatpp::Enum<Enum2>::AsString::Class::getType()); OATPP_ASSERT(e == oatpp::data::mapping::type::EnumInterpreterError::OK); auto value = voidValue.cast<oatpp::Enum<Enum2>::AsString>(); OATPP_ASSERT(value == Enum2::NAME_1); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test Interpreter AsNumber..."); oatpp::data::mapping::type::EnumInterpreterError e = oatpp::data::mapping::type::EnumInterpreterError::OK; auto inter = oatpp::Enum<Enum2>::AsNumber::Interpreter::toInterpretation(oatpp::Enum<Enum2>::AsNumber(Enum2::NAME_1), e); OATPP_ASSERT(inter.getValueType() == oatpp::Int32::Class::getType()); OATPP_ASSERT(e == oatpp::data::mapping::type::EnumInterpreterError::OK); auto interValue = inter.cast<oatpp::Int32>(); OATPP_ASSERT(interValue == static_cast<v_int32>(Enum2::NAME_1)); oatpp::Void voidValue = oatpp::Enum<Enum2>::AsNumber::Interpreter::fromInterpretation(interValue, e); OATPP_ASSERT(voidValue.getValueType() == oatpp::Enum<Enum2>::AsNumber::Class::getType()); OATPP_ASSERT(e == oatpp::data::mapping::type::EnumInterpreterError::OK); auto value = voidValue.cast<oatpp::Enum<Enum2>::AsNumber>(); OATPP_ASSERT(value == Enum2::NAME_1); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test default constructors and == operators..."); oatpp::Enum<Enum2>::AsString e1; oatpp::Enum<Enum2>::AsString e2; OATPP_ASSERT(!e1); OATPP_ASSERT(e1 == nullptr); OATPP_ASSERT(e1 == e2); OATPP_ASSERT(e2 == e1); oatpp::Enum<Enum2>::NotNull e3; OATPP_ASSERT(e1 == e3); OATPP_ASSERT(e3 == e1); oatpp::Enum<Enum2>::AsNumber::NotNull e4; OATPP_ASSERT(e1 == e4); OATPP_ASSERT(e4 == e1); OATPP_ASSERT(e1.getValueType() != e4.getValueType()); // Types are not equal because interpreters are different OATPP_ASSERT(e1.getValueType()->classId.id == e4.getValueType()->classId.id); // But classId is the same OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test value constructor and == operators..."); oatpp::Enum<Enum2> e1(Enum2::NAME_1); oatpp::Enum<Enum2> e2(Enum2::NAME_1); oatpp::Enum<Enum2> e3; OATPP_ASSERT(e1); OATPP_ASSERT(e1 != nullptr); OATPP_ASSERT(e1 == e2); OATPP_ASSERT(e1 != e3); OATPP_ASSERT(e3 != e1); OATPP_ASSERT(e1 == Enum2::NAME_1); OATPP_ASSERT(e1 != Enum2::NAME_2); OATPP_ASSERT(e3 != Enum2::NAME_1); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test copy-assignment operator..."); oatpp::Enum<Enum2>::AsString e1; oatpp::Enum<Enum2>::AsNumber e2(Enum2::NAME_1); Enum2 ve; OATPP_ASSERT(e1.getValueType() == oatpp::Enum<Enum2>::AsString::Class::getType()); OATPP_ASSERT(e2.getValueType() == oatpp::Enum<Enum2>::AsNumber::Class::getType()); OATPP_ASSERT(e1.getValueType() != e2.getValueType()); e1 = e2; OATPP_ASSERT(e1.getValueType() == oatpp::Enum<Enum2>::AsString::Class::getType()); OATPP_ASSERT(e2.getValueType() == oatpp::Enum<Enum2>::AsNumber::Class::getType()); OATPP_ASSERT(e1.getValueType() != e2.getValueType()); OATPP_ASSERT(e1 == e2); OATPP_ASSERT(e2 == e1); OATPP_ASSERT(e1.get() == e2.get()); e1 = Enum2::NAME_2; OATPP_ASSERT(e1 != e2); OATPP_ASSERT(e2 != e1); OATPP_ASSERT(e1.get() != e2.get()); OATPP_ASSERT(e1 == Enum2::NAME_2); OATPP_ASSERT(e2 == Enum2::NAME_1); ve = e1; OATPP_ASSERT(ve == Enum2::NAME_2); ve = e2; OATPP_ASSERT(ve == Enum2::NAME_1); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test move-assignment operator..."); oatpp::Enum<Enum2>::AsString e1; oatpp::Enum<Enum2>::AsNumber e2(Enum2::NAME_1); e1 = std::move(e2); OATPP_ASSERT(e1); OATPP_ASSERT(!e2); OATPP_ASSERT(e1 == Enum2::NAME_1); OATPP_LOGI(TAG, "OK"); } } }}}}}}
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/EnumTest.cpp
C++
apache-2.0
10,041
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_core_data_mapping_type_EnumTest_hpp #define oatpp_test_core_data_mapping_type_EnumTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { class EnumTest : public UnitTest{ public: EnumTest():UnitTest("TEST[core::data::mapping::type::EnumTest]"){} void onRun() override; }; }}}}}} #endif /* oatpp_test_core_data_mapping_type_EnumTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/EnumTest.hpp
C++
apache-2.0
1,461
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "InterpretationTest.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/core/data/mapping/TypeResolver.hpp" #include "oatpp/core/Types.hpp" #include "oatpp/core/macro/codegen.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { namespace { #include OATPP_CODEGEN_BEGIN(DTO) struct VPoint { v_int32 x; v_int32 y; v_int32 z; }; struct VLine { VPoint p1; VPoint p2; }; namespace __class { class PointClass; class LineClass; } typedef oatpp::data::mapping::type::Primitive<VPoint, __class::PointClass> Point; typedef oatpp::data::mapping::type::Primitive<VLine, __class::LineClass> Line; namespace __class { class PointClass { private: class PointDto : public oatpp::DTO { DTO_INIT(PointDto, DTO) DTO_FIELD(Int32, x); DTO_FIELD(Int32, y); DTO_FIELD(Int32, z); }; class Inter : public oatpp::Type::Interpretation<Point, oatpp::Object<PointDto>> { public: oatpp::Object<PointDto> interpret(const Point& value) const override { OATPP_LOGD("Point::Interpretation", "interpret"); auto dto = PointDto::createShared(); dto->x = value->x; dto->y = value->y; dto->z = value->z; return dto; } Point reproduce(const oatpp::Object<PointDto>& value) const override { OATPP_LOGD("Point::Interpretation", "reproduce"); return Point({value->x, value->y, value->z}); } }; private: static oatpp::Type* createType() { oatpp::Type::Info info; info.interpretationMap = { {"test", new Inter()} }; return new Type(CLASS_ID, info); } public: static const oatpp::ClassId CLASS_ID; static oatpp::Type* getType(){ static Type* type = createType(); return type; } }; const oatpp::ClassId PointClass::CLASS_ID("test::Point"); class LineClass { private: class LineDto : public oatpp::DTO { DTO_INIT(LineDto, DTO) DTO_FIELD(Point, p1); DTO_FIELD(Point, p2); }; class Inter : public oatpp::Type::Interpretation<Line, oatpp::Object<LineDto>> { public: oatpp::Object<LineDto> interpret(const Line& value) const override { OATPP_LOGD("Line::Interpretation", "interpret"); auto dto = LineDto::createShared(); dto->p1 = {value->p1.x, value->p1.y, value->p1.z}; dto->p2 = {value->p2.x, value->p2.y, value->p2.z}; return dto; } Line reproduce(const oatpp::Object<LineDto>& value) const override { OATPP_LOGD("Line::Interpretation", "reproduce"); return Line({{value->p1->x, value->p1->y, value->p1->z}, {value->p2->x, value->p2->y, value->p2->z}}); } }; private: static oatpp::Type* createType() { oatpp::Type::Info info; info.interpretationMap = { {"test", new Inter()} }; return new oatpp::Type(CLASS_ID, info); } public: static const oatpp::ClassId CLASS_ID; static oatpp::Type* getType(){ static Type* type = createType(); return type; } }; const oatpp::ClassId LineClass::CLASS_ID("test::Line"); } #include OATPP_CODEGEN_END(DTO) } void InterpretationTest::onRun() { oatpp::parser::json::mapping::ObjectMapper mapper; { auto config = mapper.getSerializer()->getConfig(); config->enabledInterpretations = {"test"}; config->useBeautifier = false; } { auto config = mapper.getDeserializer()->getConfig(); config->enabledInterpretations = {"test"}; } Point p1 ({1, 2, 3}); Point p2 ({11, 12, 13}); Line l ({p1, p2}); auto json1 = mapper.writeToString(l); OATPP_LOGD(TAG, "json1='%s'", json1->c_str()); auto rl = mapper.readFromString<Line>(json1); auto json2 = mapper.writeToString(rl); OATPP_LOGD(TAG, "json2='%s'", json2->c_str()); OATPP_ASSERT(json1 == json2); oatpp::data::mapping::TypeResolver::Cache cache; { oatpp::data::mapping::TypeResolver tr; tr.setEnabledInterpretations({"test"}); //oatpp::data::mapping::TypeResolver::Cache cache; auto v = tr.resolveObjectPropertyValue(l, {"p1", "x"}, cache); OATPP_ASSERT(v); OATPP_ASSERT(v.getValueType() == oatpp::Int32::Class::getType()); OATPP_ASSERT(v.cast<oatpp::Int32>() == 1); } { oatpp::data::mapping::TypeResolver tr; tr.setEnabledInterpretations({"test"}); //oatpp::data::mapping::TypeResolver::Cache cache; auto v = tr.resolveObjectPropertyValue(l, {"p1", "y"}, cache); OATPP_ASSERT(v); OATPP_ASSERT(v.getValueType() == oatpp::Int32::Class::getType()); OATPP_ASSERT(v.cast<oatpp::Int32>() == 2); } { oatpp::data::mapping::TypeResolver tr; tr.setEnabledInterpretations({"test"}); //oatpp::data::mapping::TypeResolver::Cache cache; auto v = tr.resolveObjectPropertyValue(l, {"p1", "z"}, cache); OATPP_ASSERT(v); OATPP_ASSERT(v.getValueType() == oatpp::Int32::Class::getType()); OATPP_ASSERT(v.cast<oatpp::Int32>() == 3); } } }}}}}}
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/InterpretationTest.cpp
C++
apache-2.0
6,088
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_core_data_mapping_type_InterpretationTest_hpp #define oatpp_test_core_data_mapping_type_InterpretationTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { class InterpretationTest : public UnitTest{ public: InterpretationTest():UnitTest("TEST[core::data::mapping::type::InterpretationTest]"){} void onRun() override; }; }}}}}} #endif // oatpp_test_core_data_mapping_type_InterpretationTest_hpp
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/InterpretationTest.hpp
C++
apache-2.0
1,518
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "ListTest.hpp" #include "oatpp/core/Types.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { void ListTest::onRun() { { OATPP_LOGI(TAG, "test default constructor..."); oatpp::List<oatpp::String> list; OATPP_ASSERT(!list); OATPP_ASSERT(list == nullptr); OATPP_ASSERT(list.get() == nullptr); OATPP_ASSERT(list.getValueType()->classId.id == oatpp::data::mapping::type::__class::AbstractList::CLASS_ID.id); OATPP_ASSERT(list.getValueType()->params.size() == 1); OATPP_ASSERT(list.getValueType()->params.front() == oatpp::String::Class::getType()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test empty ilist constructor..."); oatpp::List<oatpp::String> list({}); OATPP_ASSERT(list); OATPP_ASSERT(list != nullptr); OATPP_ASSERT(list->size() == 0); OATPP_ASSERT(list.get() != nullptr); OATPP_ASSERT(list.getValueType()->classId.id == oatpp::data::mapping::type::__class::AbstractList::CLASS_ID.id); OATPP_ASSERT(list.getValueType()->params.size() == 1); OATPP_ASSERT(list.getValueType()->params.front() == oatpp::String::Class::getType()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test createShared()..."); oatpp::List<oatpp::String> list = oatpp::List<oatpp::String>::createShared(); OATPP_ASSERT(list); OATPP_ASSERT(list != nullptr); OATPP_ASSERT(list->size() == 0); OATPP_ASSERT(list.get() != nullptr); OATPP_ASSERT(list.getValueType()->classId.id == oatpp::data::mapping::type::__class::AbstractList::CLASS_ID.id); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test copy-assignment operator..."); oatpp::List<oatpp::String> list1({}); oatpp::List<oatpp::String> list2; list2 = list1; OATPP_ASSERT(list1); OATPP_ASSERT(list2); OATPP_ASSERT(list1->size() == 0); OATPP_ASSERT(list2->size() == 0); OATPP_ASSERT(list1.get() == list2.get()); list2->push_back("a"); OATPP_ASSERT(list1->size() == 1); OATPP_ASSERT(list2->size() == 1); list2 = {"b", "c"}; OATPP_ASSERT(list1->size() == 1); OATPP_ASSERT(list2->size() == 2); OATPP_ASSERT(list2[0] == "b"); OATPP_ASSERT(list2[1] == "c"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test move-assignment operator..."); oatpp::List<oatpp::String> list1({}); oatpp::List<oatpp::String> list2; list2 = std::move(list1); OATPP_ASSERT(!list1); OATPP_ASSERT(list2); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test get element by index..."); oatpp::List<oatpp::String> list = {"a", "b", "c"}; OATPP_ASSERT(list); OATPP_ASSERT(list != nullptr); OATPP_ASSERT(list->size() == 3); OATPP_ASSERT(list[0] == "a"); OATPP_ASSERT(list[1] == "b"); OATPP_ASSERT(list[2] == "c"); list[1] = "Hello!"; OATPP_ASSERT(list->size() == 3); OATPP_ASSERT(list[0] == "a"); OATPP_ASSERT(list[1] == "Hello!"); OATPP_ASSERT(list[2] == "c"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test polymorphicDispatcher..."); oatpp::List<oatpp::String> list = {"a", "b", "c"}; auto polymorphicDispatcher = static_cast<const oatpp::data::mapping::type::__class::Collection::PolymorphicDispatcher*>( list.getValueType()->polymorphicDispatcher ); polymorphicDispatcher->addItem(list, oatpp::String("d")); OATPP_ASSERT(list->size() == 4); OATPP_ASSERT(list[0] == "a"); OATPP_ASSERT(list[1] == "b"); OATPP_ASSERT(list[2] == "c"); OATPP_ASSERT(list[3] == "d"); OATPP_LOGI(TAG, "OK"); } } }}}}}}
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/ListTest.cpp
C++
apache-2.0
4,633
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_core_data_mapping_type_ListTest_hpp #define oatpp_test_core_data_mapping_type_ListTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { class ListTest : public UnitTest{ public: ListTest():UnitTest("TEST[core::data::mapping::type::ListTest]"){} void onRun() override; }; }}}}}} #endif /* oatpp_test_core_data_mapping_type_ListTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/ListTest.hpp
C++
apache-2.0
1,461
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "ObjectTest.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/core/macro/codegen.hpp" #include "oatpp/core/Types.hpp" #include "oatpp-test/Checker.hpp" #include <thread> namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { namespace { #include OATPP_CODEGEN_BEGIN(DTO) class Dto0 : public oatpp::DTO { DTO_INIT(Dto0, DTO) }; class DtoA : public oatpp::DTO { DTO_INIT(DtoA, DTO) DTO_FIELD_INFO(id) { info->description = "identifier"; info->pattern = "^[a-z0-9]+$"; } DTO_FIELD(String, id) = "Some default id"; DTO_HC_EQ(id) public: DtoA() = default; DtoA(const String& pId) : id(pId) {} }; class DtoB : public DtoA { DTO_INIT(DtoB, DtoA) DTO_FIELD_INFO(a) { info->description = "some field with a qualified name"; } DTO_FIELD(String, a, "field-a") = "default-value"; }; class DtoC : public DtoA { DTO_INIT(DtoC, DtoA) DTO_FIELD(String, a); DTO_FIELD(String, b); DTO_FIELD(String, c); DTO_HC_EQ(a, b, c); }; class DtoD : public DtoA { DTO_INIT(DtoD, DtoA) DTO_FIELD(Int32, a) = Int64(64); }; class DtoTypeA : public oatpp::DTO { DTO_INIT(DtoTypeA, DTO) DTO_FIELD(String, fieldA) = "type-A"; }; class DtoTypeB : public oatpp::DTO { DTO_INIT(DtoTypeB, DTO) DTO_FIELD(String, fieldB) = "type-B"; }; class PolymorphicDto1 : public oatpp::DTO { DTO_INIT(PolymorphicDto1, DTO) DTO_FIELD(String, type); DTO_FIELD(Any, polymorph); DTO_FIELD_TYPE_SELECTOR(polymorph) { if(type == "A") return Object<DtoTypeA>::Class::getType(); if(type == "B") return Object<DtoTypeB>::Class::getType(); return Object<DTO>::Class::getType(); } }; class PolymorphicDto2 : public oatpp::DTO { DTO_INIT(PolymorphicDto2, DTO) DTO_FIELD(String, type); DTO_FIELD_INFO(polymorph) { info->description = "description"; } DTO_FIELD(Any, polymorph); DTO_FIELD_TYPE_SELECTOR(polymorph) { if(type == "A") return Object<DtoTypeA>::Class::getType(); if(type == "B") return Object<DtoTypeB>::Class::getType(); return Object<DTO>::Class::getType(); } }; class PolymorphicDto3 : public oatpp::DTO { DTO_INIT(PolymorphicDto3, DTO) DTO_FIELD(String, type); DTO_FIELD(Any, polymorph); DTO_FIELD_TYPE_SELECTOR(polymorph) { if(type == "str") return String::Class::getType(); if(type == "int") return Int32::Class::getType(); return Void::Class::getType(); } }; #include OATPP_CODEGEN_END(DTO) void runDtoInitializations() { for(v_int32 i = 0; i < 1000; i ++) { auto dto = DtoB::createShared(); } } void runDtoInitializetionsInThreads() { std::list<std::thread> threads; for(v_int32 i = 0; i < 500; i++) { threads.push_back(std::thread(runDtoInitializations)); } for(auto& t : threads) { t.join(); } } } void ObjectTest::onRun() { { oatpp::test::PerformanceChecker timer("DTO - Initializations."); runDtoInitializetionsInThreads(); } { auto dto = DtoA::createShared("id1"); OATPP_ASSERT(dto->id == "id1"); } { OATPP_LOGI(TAG, "Test Meta 1..."); auto type = Object<DtoA>::Class::getType(); auto dispatcher = static_cast<const oatpp::data::mapping::type::__class::AbstractObject::PolymorphicDispatcher*>(type->polymorphicDispatcher); const auto& propsMap = dispatcher->getProperties()->getMap(); OATPP_ASSERT(propsMap.size() == 1); auto it = propsMap.find("id"); OATPP_ASSERT(it != propsMap.end()); OATPP_ASSERT(it->second->info.description == "identifier"); OATPP_ASSERT(it->second->info.pattern == "^[a-z0-9]+$"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test Meta 2..."); auto type = Object<DtoB>::Class::getType(); auto dispatcher = static_cast<const oatpp::data::mapping::type::__class::AbstractObject::PolymorphicDispatcher*>(type->polymorphicDispatcher); const auto& propsMap = dispatcher->getProperties()->getMap(); OATPP_ASSERT(propsMap.size() == 2); { auto it = propsMap.find("id"); OATPP_ASSERT("id" && it != propsMap.end()); OATPP_ASSERT(it->second->info.description == "identifier"); } { auto it = propsMap.find("field-a"); OATPP_ASSERT("field-a" && it != propsMap.end()); OATPP_ASSERT(it->second->info.description == "some field with a qualified name"); } OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test 1..."); Object<DtoA> a; OATPP_ASSERT(!a); OATPP_ASSERT(a == nullptr); OATPP_ASSERT(a.getValueType()->classId.id == oatpp::data::mapping::type::__class::AbstractObject::CLASS_ID.id); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test 2..."); Object<DtoA> a; Object<DtoA> b; OATPP_ASSERT(a == b); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test 3..."); auto a = DtoA::createShared(); Object<DtoA> b; OATPP_ASSERT(a != b); OATPP_ASSERT(b != a); auto ohc = a->hashCode(); auto whc = std::hash<oatpp::Object<DtoA>>{}(a); OATPP_ASSERT(ohc == whc); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test 4..."); auto a = Dto0::createShared(); auto b = Dto0::createShared(); OATPP_ASSERT(a != b); OATPP_ASSERT(a->hashCode() != b->hashCode()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test 5..."); auto a = DtoA::createShared(); auto b = DtoA::createShared(); OATPP_ASSERT(a == b); OATPP_ASSERT(a->hashCode() == b->hashCode()); a->id = "hello"; OATPP_ASSERT(a != b); OATPP_ASSERT(a->hashCode() != b->hashCode()); b->id = "hello"; OATPP_ASSERT(a == b); OATPP_ASSERT(a->hashCode() == b->hashCode()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test 6..."); auto a = DtoB::createShared(); auto b = DtoB::createShared(); OATPP_ASSERT(a->a == "default-value"); OATPP_ASSERT(b->a == "default-value"); a->a = "value1"; // value that is ignored in HC & EQ a->a = "value2"; // value that is ignored in HC & EQ OATPP_ASSERT(a == b); OATPP_ASSERT(a->hashCode() == b->hashCode()); a->id = "hello"; OATPP_ASSERT(a != b); OATPP_ASSERT(a->hashCode() != b->hashCode()); b->id = "hello"; OATPP_ASSERT(a == b); OATPP_ASSERT(a->hashCode() == b->hashCode()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test 7..."); auto a = DtoC::createShared(); auto b = DtoC::createShared(); a->id = "1"; b->id = "2"; OATPP_ASSERT(a != b); OATPP_ASSERT(a->hashCode() != b->hashCode()); a->id = "2"; OATPP_ASSERT(a == b); OATPP_ASSERT(a->hashCode() == b->hashCode()); a->c = "a"; OATPP_ASSERT(a != b); OATPP_ASSERT(a->hashCode() != b->hashCode()); b->c = "a"; OATPP_ASSERT(a == b); OATPP_ASSERT(a->hashCode() == b->hashCode()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test 8..."); auto a = DtoB::createShared(); auto b = DtoB::createShared(); auto c = DtoB::createShared(); auto d = DtoB::createShared(); auto e = DtoB::createShared(); a->a = "1"; b->a = "2"; c->a = "3"; d->a = "4"; e->a = "5"; a->id = "1"; e->id = "1"; oatpp::UnorderedSet<oatpp::Object<DtoB>> set = {a, b, c, d, e}; OATPP_ASSERT(set->size() == 2); OATPP_ASSERT(set[a] == true); OATPP_ASSERT(set[b] == true); OATPP_ASSERT(set[c] == true); OATPP_ASSERT(set[d] == true); OATPP_ASSERT(set[e] == true); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test 9..."); auto dto = DtoD::createShared(); OATPP_ASSERT(dto->a.getValueType() == oatpp::Int32::Class::getType()); OATPP_ASSERT(dto->a); OATPP_ASSERT(dto->a == 64); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test 10..."); OATPP_ASSERT(oatpp::Object<DtoA>::Class::getType()->extends(oatpp::Object<oatpp::DTO>::Class::getType())) OATPP_ASSERT(oatpp::Object<DtoA>::Class::getType()->extends(oatpp::Object<DtoA>::Class::getType())) OATPP_ASSERT(oatpp::Object<DtoB>::Class::getType()->extends(oatpp::Object<DtoA>::Class::getType())) OATPP_ASSERT(oatpp::Object<DtoB>::Class::getType()->extends(oatpp::Object<oatpp::DTO>::Class::getType())) OATPP_ASSERT(oatpp::Object<DtoC>::Class::getType()->extends(oatpp::Object<DtoA>::Class::getType())) OATPP_ASSERT(oatpp::Object<DtoD>::Class::getType()->extends(oatpp::Object<DtoA>::Class::getType())) OATPP_ASSERT(!oatpp::Object<DtoC>::Class::getType()->extends(oatpp::Object<DtoB>::Class::getType())) OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test 11..."); auto map = oatpp::Object<PolymorphicDto1>::getPropertiesMap(); auto p = map["polymorph"]; OATPP_ASSERT(p->info.description == ""); OATPP_ASSERT(p->info.typeSelector != nullptr); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test 12..."); auto map = oatpp::Object<PolymorphicDto2>::getPropertiesMap(); auto p = map["polymorph"]; OATPP_ASSERT(p->info.description == "description"); OATPP_ASSERT(p->info.typeSelector != nullptr); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test 13..."); auto dto = oatpp::Object<PolymorphicDto2>::createShared(); OATPP_ASSERT(dto->type == nullptr) OATPP_ASSERT(dto->type.getValueType() == oatpp::String::Class::getType()) OATPP_ASSERT(dto["type"] == nullptr) OATPP_ASSERT(dto["type"].getValueType() == oatpp::String::Class::getType()) dto["type"] = oatpp::String("hello"); OATPP_ASSERT(dto->type == "hello"); OATPP_ASSERT(dto->type.getValueType() == oatpp::String::Class::getType()) OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test 14..."); auto dto = oatpp::Object<PolymorphicDto2>::createShared(); bool thrown = false; try{ dto["type"] = oatpp::Int32(32); } catch(std::runtime_error e) { OATPP_LOGD(TAG, "error='%s'", e.what()); thrown = true; } OATPP_ASSERT(thrown) OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test 15..."); auto dto = oatpp::Object<PolymorphicDto2>::createShared(); bool thrown = false; try{ dto["non-existing"]; } catch(std::out_of_range e) { OATPP_LOGD(TAG, "error='%s'", e.what()); thrown = true; } OATPP_ASSERT(thrown) OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test 16..."); oatpp::parser::json::mapping::ObjectMapper mapper; auto dto = PolymorphicDto1::createShared(); dto->type = "A"; dto->polymorph = DtoTypeA::createShared(); OATPP_ASSERT(dto->polymorph.getValueType() == oatpp::Any::Class::getType()) auto json = mapper.writeToString(dto); OATPP_LOGD(TAG, "json0='%s'", json->c_str()) auto dtoClone = mapper.readFromString<oatpp::Object<PolymorphicDto1>>(json); auto jsonClone = mapper.writeToString(dtoClone); OATPP_LOGD(TAG, "json1='%s'", jsonClone->c_str()) OATPP_ASSERT(json == jsonClone) OATPP_ASSERT(dtoClone->polymorph) OATPP_ASSERT(dtoClone->polymorph.getValueType() == oatpp::Any::Class::getType()) auto polymorphClone = dtoClone->polymorph.retrieve<oatpp::Object<DtoTypeA>>(); OATPP_ASSERT(polymorphClone->fieldA == "type-A") OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test 17..."); oatpp::parser::json::mapping::ObjectMapper mapper; auto dto = PolymorphicDto3::createShared(); dto->type = "str"; dto->polymorph = oatpp::String("Hello World!"); OATPP_ASSERT(dto->polymorph.getValueType() == oatpp::Any::Class::getType()) auto json = mapper.writeToString(dto); OATPP_LOGD(TAG, "json0='%s'", json->c_str()) auto dtoClone = mapper.readFromString<oatpp::Object<PolymorphicDto3>>(json); auto jsonClone = mapper.writeToString(dtoClone); OATPP_LOGD(TAG, "json1='%s'", jsonClone->c_str()) OATPP_ASSERT(json == jsonClone) OATPP_ASSERT(dtoClone->polymorph) OATPP_ASSERT(dtoClone->polymorph.getValueType() == oatpp::Any::Class::getType()) auto polymorphClone = dtoClone->polymorph.retrieve<oatpp::String>(); OATPP_ASSERT(polymorphClone == "Hello World!") OATPP_LOGI(TAG, "OK"); } } }}}}}}
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/ObjectTest.cpp
C++
apache-2.0
13,155
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_core_data_mapping_type_ObjectTest_hpp #define oatpp_test_core_data_mapping_type_ObjectTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { class ObjectTest : public UnitTest{ public: ObjectTest():UnitTest("TEST[core::data::mapping::type::ObjectTest]"){} void onRun() override; }; }}}}}} #endif /* oatpp_test_core_data_mapping_type_ObjectTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/ObjectTest.hpp
C++
apache-2.0
1,473
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "ObjectWrapperTest.hpp" #include "oatpp/core/Types.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { namespace { template<class T, class Clazz = oatpp::data::mapping::type::__class::Void> using ObjectWrapper = oatpp::data::mapping::type::ObjectWrapper<T, Clazz>; } void ObjectWrapperTest::onRun() { { OATPP_LOGI(TAG, "Check default valueType is assigned (default tparam Clazz)..."); ObjectWrapper<std::string> pw; OATPP_ASSERT(!pw); OATPP_ASSERT(pw == nullptr); OATPP_ASSERT(pw.getValueType() == oatpp::data::mapping::type::__class::Void::getType()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Check default valueType is assigned (specified tparam Clazz)..."); ObjectWrapper<std::string, oatpp::data::mapping::type::__class::String> pw; OATPP_ASSERT(!pw); OATPP_ASSERT(pw == nullptr); OATPP_ASSERT(pw.getValueType() == oatpp::data::mapping::type::__class::String::getType()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Check valueType is assigned from constructor..."); ObjectWrapper<std::string> pw(oatpp::data::mapping::type::__class::String::getType()); OATPP_ASSERT(!pw); OATPP_ASSERT(pw == nullptr); OATPP_ASSERT(pw.getValueType() == oatpp::data::mapping::type::__class::String::getType()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Check valueType is assigned from copy constructor..."); ObjectWrapper<std::string> pw1(oatpp::data::mapping::type::__class::String::getType()); ObjectWrapper<std::string> pw2(pw1); OATPP_ASSERT(pw2.getValueType() == oatpp::data::mapping::type::__class::String::getType()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Check valueType is assigned from move constructor..."); ObjectWrapper<std::string> pw1(oatpp::data::mapping::type::__class::String::getType()); ObjectWrapper<std::string> pw2(std::move(pw1)); OATPP_ASSERT(pw2.getValueType() == oatpp::data::mapping::type::__class::String::getType()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Check valueType is NOT assigned from copy-assign operator..."); ObjectWrapper<std::string> pw1(oatpp::data::mapping::type::__class::String::getType()); ObjectWrapper<std::string> pw2; bool throws = false; try { pw2 = pw1; } catch (std::runtime_error& e) { throws = true; } OATPP_ASSERT(pw2.getValueType() == oatpp::data::mapping::type::__class::Void::getType()); OATPP_ASSERT(throws) OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Check valueType is NOT assigned from move-assign operator..."); ObjectWrapper<std::string> pw1(oatpp::data::mapping::type::__class::String::getType()); ObjectWrapper<std::string> pw2; bool throws = false; try { pw2 = std::move(pw1); } catch (std::runtime_error& e) { throws = true; } OATPP_ASSERT(pw2.getValueType() == oatpp::data::mapping::type::__class::Void::getType()); OATPP_ASSERT(throws) OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Check copy-assign operator. Check == operator..."); ObjectWrapper<std::string> pw1; OATPP_ASSERT(!pw1); OATPP_ASSERT(pw1 == nullptr); OATPP_ASSERT(pw1.getValueType() == oatpp::data::mapping::type::__class::Void::getType()); ObjectWrapper<std::string> pw2 = std::make_shared<std::string>("Hello!"); OATPP_ASSERT(pw2); OATPP_ASSERT(pw2 != nullptr); OATPP_ASSERT(pw2.getValueType() == oatpp::data::mapping::type::__class::Void::getType()); pw1 = pw2; OATPP_ASSERT(pw1); OATPP_ASSERT(pw1 != nullptr); OATPP_ASSERT(pw2); OATPP_ASSERT(pw2 != nullptr); OATPP_ASSERT(pw1 == pw2); OATPP_ASSERT(pw1.get() == pw2.get()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Check != operator..."); ObjectWrapper<std::string, oatpp::data::mapping::type::__class::String> pw1(std::make_shared<std::string>("Hello!")); OATPP_ASSERT(pw1); OATPP_ASSERT(pw1 != nullptr); OATPP_ASSERT(pw1.getValueType() == oatpp::data::mapping::type::__class::String::getType()); ObjectWrapper<std::string, oatpp::data::mapping::type::__class::String> pw2(std::make_shared<std::string>("Hello!")); OATPP_ASSERT(pw2); OATPP_ASSERT(pw2 != nullptr); OATPP_ASSERT(pw2.getValueType() == oatpp::data::mapping::type::__class::String::getType()); OATPP_ASSERT(pw1 != pw2); OATPP_ASSERT(pw1.get() != pw2.get()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Check move-assign operator. Check != operator..."); ObjectWrapper<std::string> pw1; OATPP_ASSERT(!pw1); OATPP_ASSERT(pw1 == nullptr); OATPP_ASSERT(pw1.getValueType() == oatpp::data::mapping::type::__class::Void::getType()); ObjectWrapper<std::string> pw2 = std::make_shared<std::string>("Hello!"); OATPP_ASSERT(pw2); OATPP_ASSERT(pw2 != nullptr); OATPP_ASSERT(pw2.getValueType() == oatpp::data::mapping::type::__class::Void::getType()); pw1 = std::move(pw2); OATPP_ASSERT(pw1); OATPP_ASSERT(pw1 != nullptr); OATPP_ASSERT(!pw2); OATPP_ASSERT(pw2 == nullptr); OATPP_ASSERT(pw1 != pw2); OATPP_ASSERT(pw1.get() != pw2.get()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Check oatpp::Void type reassigned"); oatpp::Void v; v = oatpp::String("test"); OATPP_ASSERT(v.getValueType() == oatpp::String::Class::getType()); v = oatpp::Int32(32); OATPP_ASSERT(v.getValueType() == oatpp::Int32::Class::getType()); oatpp::Int32 i = v.cast<oatpp::Int32>(); OATPP_ASSERT(i.getValueType() == oatpp::Int32::Class::getType()); OATPP_ASSERT(i == 32); } } }}}}}}
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/ObjectWrapperTest.cpp
C++
apache-2.0
6,687
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_core_data_mapping_type_ObjectWrapperTest_hpp #define oatpp_test_core_data_mapping_type_ObjectWrapperTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { class ObjectWrapperTest : public UnitTest{ public: ObjectWrapperTest():UnitTest("TEST[core::data::mapping::type::ObjectWrapperTest]"){} void onRun() override; }; }}}}}} #endif /* oatpp_test_core_data_mapping_type_ObjectWrapperTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/ObjectWrapperTest.hpp
C++
apache-2.0
1,515
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "PairListTest.hpp" #include "oatpp/core/Types.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { void PairListTest::onRun() { { OATPP_LOGI(TAG, "test default constructor..."); oatpp::Fields<String> map; OATPP_ASSERT(!map); OATPP_ASSERT(map == nullptr); OATPP_ASSERT(map.get() == nullptr); OATPP_ASSERT(map.getValueType()->classId.id == oatpp::data::mapping::type::__class::AbstractPairList::CLASS_ID.id); OATPP_ASSERT(map.getValueType()->params.size() == 2); auto it = map.getValueType()->params.begin(); OATPP_ASSERT(*it++ == oatpp::String::Class::getType()); OATPP_ASSERT(*it++ == oatpp::String::Class::getType()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test empty ilist constructor..."); oatpp::Fields<String> map({}); OATPP_ASSERT(map); OATPP_ASSERT(map != nullptr); OATPP_ASSERT(map->size() == 0); OATPP_ASSERT(map.get() != nullptr); OATPP_ASSERT(map.getValueType()->classId.id == oatpp::data::mapping::type::__class::AbstractPairList::CLASS_ID.id); OATPP_ASSERT(map.getValueType()->params.size() == 2); auto it = map.getValueType()->params.begin(); OATPP_ASSERT(*it++ == oatpp::String::Class::getType()); OATPP_ASSERT(*it++ == oatpp::String::Class::getType()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test createShared()..."); oatpp::Fields<String> map = oatpp::Fields<String>::createShared(); OATPP_ASSERT(map); OATPP_ASSERT(map != nullptr); OATPP_ASSERT(map->size() == 0); OATPP_ASSERT(map.get() != nullptr); OATPP_ASSERT(map.getValueType()->classId.id == oatpp::data::mapping::type::__class::AbstractPairList::CLASS_ID.id); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test copy-assignment operator..."); oatpp::Fields<String> map1({}); oatpp::Fields<String> map2; map2 = map1; OATPP_ASSERT(map1); OATPP_ASSERT(map2); OATPP_ASSERT(map1->size() == 0); OATPP_ASSERT(map2->size() == 0); OATPP_ASSERT(map1.get() == map2.get()); map2->push_back({"key", "a"}); OATPP_ASSERT(map1->size() == 1); OATPP_ASSERT(map2->size() == 1); map2 = {{"key1", "b"}, {"key2", "c"}}; OATPP_ASSERT(map1->size() == 1); OATPP_ASSERT(map2->size() == 2); OATPP_ASSERT(map2["key1"] == "b"); OATPP_ASSERT(map2["key2"] == "c"); OATPP_ASSERT(map2.getValueByKey("key1") == "b"); OATPP_ASSERT(map2.getValueByKey("key2") == "c"); OATPP_ASSERT(map2.getValueByKey("key3") == nullptr); OATPP_ASSERT(map2.getValueByKey("key3", "default-val") == "default-val"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test move-assignment operator..."); oatpp::Fields<String> map1({}); oatpp::Fields<String> map2; map2 = std::move(map1); OATPP_ASSERT(!map1); OATPP_ASSERT(map2); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test get element by index..."); oatpp::Fields<String> map = {{"key1", "a"}, {"key2", "b"}, {"key3", "c"}}; OATPP_ASSERT(map); OATPP_ASSERT(map != nullptr); OATPP_ASSERT(map->size() == 3); OATPP_ASSERT(map["key1"] == "a"); OATPP_ASSERT(map["key2"] == "b"); OATPP_ASSERT(map["key3"] == "c"); map["key2"] = "Hello!"; OATPP_ASSERT(map->size() == 3); OATPP_ASSERT(map["key1"] == "a"); OATPP_ASSERT(map["key2"] == "Hello!"); OATPP_ASSERT(map["key3"] == "c"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test polymorphicDispatcher..."); oatpp::Fields<String> map = {{"key1", "a"}, {"key2", "b"}, {"key3", "c"}}; auto polymorphicDispatcher = static_cast<const typename oatpp::data::mapping::type::__class::Map::PolymorphicDispatcher*>( map.getValueType()->polymorphicDispatcher ); polymorphicDispatcher->addItem(map, oatpp::String("key1"), oatpp::String("d")); OATPP_ASSERT(map->size() == 4); OATPP_ASSERT(map[0].first == "key1" && map[0].second == "a"); OATPP_ASSERT(map[1].first == "key2" && map[1].second == "b"); OATPP_ASSERT(map[2].first == "key3" && map[2].second == "c"); OATPP_ASSERT(map[3].first == "key1" && map[3].second == "d"); OATPP_LOGI(TAG, "OK"); } } }}}}}}
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/PairListTest.cpp
C++
apache-2.0
5,232
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_core_data_mapping_type_PairListTest_hpp #define oatpp_test_core_data_mapping_type_PairListTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { class PairListTest : public UnitTest{ public: PairListTest():UnitTest("TEST[core::data::mapping::type::PairListTest]"){} void onRun() override; }; }}}}}} #endif /* oatpp_test_core_data_mapping_type_PairListTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/PairListTest.hpp
C++
apache-2.0
1,485
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "PrimitiveTest.hpp" #include "oatpp/core/Types.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { namespace { template<class T> void checkHash(const T& val) { auto h = std::hash<T>{}(val); OATPP_LOGI("HASH", "type='%s', hash=%llu", val.getValueType()->classId.name, h); } } void PrimitiveTest::onRun() { { checkHash(oatpp::Boolean(true)); checkHash(oatpp::Int8(0x7F)); checkHash(oatpp::UInt8(0xFF)); checkHash(oatpp::Int16(0x7FFF)); checkHash(oatpp::UInt16(0xFFFF)); checkHash(oatpp::Int32(0x7FFFFFFF)); checkHash(oatpp::UInt32(0xFFFFFFFF)); checkHash(oatpp::Int64(0x7FFFFFFFFFFFFFFF)); checkHash(oatpp::UInt64(0xFFFFFFFFFFFFFFFF)); checkHash(oatpp::Float32(0.2f)); checkHash(oatpp::Float64(0.2)); } { OATPP_LOGI(TAG, "test default constructor"); oatpp::Int32 i; OATPP_ASSERT(!i); OATPP_ASSERT(i == nullptr); OATPP_ASSERT(i.getValueType() == oatpp::Int32::Class::getType()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test value constructor"); oatpp::Int32 i(0); OATPP_ASSERT(i); OATPP_ASSERT(i != nullptr); OATPP_ASSERT(i == 0); OATPP_ASSERT(i.getValueType() == oatpp::Int32::Class::getType()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test implicit value constructor"); oatpp::Int32 i = 0; OATPP_ASSERT(i); OATPP_ASSERT(i != nullptr); OATPP_ASSERT(i == 0); OATPP_ASSERT(i.getValueType() == oatpp::Int32::Class::getType()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test '==' and '!=' operators"); oatpp::Int32 i1 = 0; oatpp::Int32 i2; OATPP_ASSERT(i1); OATPP_ASSERT(i1 != nullptr); OATPP_ASSERT(i1 == 0); OATPP_ASSERT(i1 != 1); OATPP_ASSERT(!i2); OATPP_ASSERT(i2 == nullptr) OATPP_ASSERT(i1 != i2); OATPP_ASSERT(i2 != i1); i2 = 0; OATPP_ASSERT(i1 == i2); OATPP_ASSERT(i2 == i1); i1 = nullptr; i2 = nullptr; OATPP_ASSERT(i1 == i2); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test copy-assign operator"); oatpp::Int32 i1 = 0; oatpp::Int32 i2; OATPP_ASSERT(i1 != i2); i2 = i1; OATPP_ASSERT(i1 == i2); OATPP_ASSERT(i1.get() == i2.get()); i2 = 1; OATPP_ASSERT(i1 != i2); OATPP_ASSERT(i1.get() != i2.get()); OATPP_ASSERT(i1 == 0); OATPP_ASSERT(i2 == 1); } { OATPP_LOGI(TAG, "test move-assign operator"); oatpp::Int32 i1 = 0; oatpp::Int32 i2; OATPP_ASSERT(i1 != i2); i2 = std::move(i1); OATPP_ASSERT(i1 == nullptr); OATPP_ASSERT(i2 != nullptr); OATPP_ASSERT(i2 == 0); } { OATPP_LOGI(TAG, "test move-assign operator"); oatpp::Int32 i = 0; v_int32 v = i; OATPP_ASSERT(v == i); } { OATPP_LOGI(TAG, "Test Boolean [nullptr]"); oatpp::Boolean b; OATPP_ASSERT(!b); OATPP_ASSERT(b == nullptr); OATPP_ASSERT(b != false); OATPP_ASSERT(b != true); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test Boolean nullptr constructor"); oatpp::Boolean b = nullptr; OATPP_ASSERT(!b); OATPP_ASSERT(b == nullptr); OATPP_ASSERT(b != false); OATPP_ASSERT(b != true); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test Boolean [false]"); oatpp::Boolean b = false; OATPP_ASSERT(!b); // <--- still !b OATPP_ASSERT(b != nullptr); OATPP_ASSERT(b == false); OATPP_ASSERT(b != true); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test Boolean [true]"); oatpp::Boolean b = true; OATPP_ASSERT(b); OATPP_ASSERT(b != nullptr); OATPP_ASSERT(b != false); OATPP_ASSERT(b == true); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test Boolean copy-assign operator"); oatpp::Boolean b1 = true; oatpp::Boolean b2; b2 = b1; OATPP_ASSERT(b2); OATPP_ASSERT(b1); OATPP_ASSERT(b1 == b2); OATPP_ASSERT(b1.get() == b2.get()); b2 = false; OATPP_ASSERT(b1.get() != b2.get()); OATPP_ASSERT(b1 != b2); OATPP_ASSERT(b2 != b1); b1 = false; b2 = nullptr; OATPP_ASSERT(b1 != b2); OATPP_ASSERT(b2 != b1); b1 = nullptr; b2 = nullptr; OATPP_ASSERT(b1 == b2); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Test Boolean move-assign operator"); oatpp::Boolean b1 = true; oatpp::Boolean b2; b2 = std::move(b1); OATPP_ASSERT(b2 != nullptr); OATPP_ASSERT(b1 == nullptr); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "check default value"); oatpp::UInt8 s0; oatpp::UInt8 s1 = 255; OATPP_ASSERT(s0.getValue(128) == 128) OATPP_ASSERT(s1.getValue(128) == 255) } } }}}}}}
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/PrimitiveTest.cpp
C++
apache-2.0
5,719
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_core_data_mapping_type_PrimitiveTest_hpp #define oatpp_test_core_data_mapping_type_PrimitiveTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { class PrimitiveTest : public UnitTest{ public: PrimitiveTest():UnitTest("TEST[core::data::mapping::type::PrimitiveTest]"){} void onRun() override; }; }}}}}} #endif /* oatpp_test_core_data_mapping_type_PrimitiveTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/PrimitiveTest.hpp
C++
apache-2.0
1,491
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "StringTest.hpp" #include "oatpp/core/Types.hpp" #include <functional> namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { void StringTest::onRun() { { oatpp::String s = "hello"; // check hash function exists std::hash<oatpp::String>{}(s); } { OATPP_LOGI(TAG, "test default constructor"); oatpp::String s; OATPP_ASSERT(!s); OATPP_ASSERT(s == nullptr); OATPP_ASSERT(s == (const char*) nullptr); OATPP_ASSERT(s.getValueType() == oatpp::String::Class::getType()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test nullptr constructor"); oatpp::String s(nullptr); OATPP_ASSERT(!s); OATPP_ASSERT(s == nullptr); OATPP_ASSERT(s == (const char*) nullptr); OATPP_ASSERT(s.getValueType() == oatpp::String::Class::getType()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test const char* constructor"); oatpp::String s("abc\0xyz"); OATPP_ASSERT(s); OATPP_ASSERT(s != nullptr); OATPP_ASSERT(s != (const char*) nullptr) OATPP_ASSERT(s->size() == 3); OATPP_ASSERT(s == "abc"); OATPP_ASSERT(s == "abc\0xyz"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test std::string constructor"); std::string a("abc\0xyz", 7); oatpp::String s(a); OATPP_ASSERT(s); OATPP_ASSERT(s != nullptr); OATPP_ASSERT(s != (const char*) nullptr) OATPP_ASSERT(s->size() == 7); OATPP_ASSERT(s != "abc"); OATPP_ASSERT(s != "abc\0xyz"); OATPP_ASSERT(s == std::string("abc\0xyz", 7)); OATPP_ASSERT(s == a); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test std::string move constructor"); std::string a("abc\0xyz", 7); oatpp::String s(std::move(a)); OATPP_ASSERT(s); OATPP_ASSERT(s != nullptr); OATPP_ASSERT(s != (const char*) nullptr) OATPP_ASSERT(s->size() == 7); OATPP_ASSERT(s != "abc"); OATPP_ASSERT(s != "abc\0xyz"); OATPP_ASSERT(s == std::string("abc\0xyz", 7)); OATPP_ASSERT(a == ""); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test const char* assign operator"); oatpp::String s; s = "abc\0xyz"; OATPP_ASSERT(s); OATPP_ASSERT(s != nullptr); OATPP_ASSERT(s != (const char*) nullptr) OATPP_ASSERT(s->size() == 3); OATPP_ASSERT(s == "abc"); OATPP_ASSERT(s == "abc\0xyz"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test std::string assign operator"); oatpp::String s; std::string a = std::string("abc\0xyz", 7); s = a; OATPP_ASSERT(s); OATPP_ASSERT(s != nullptr); OATPP_ASSERT(s != (const char*) nullptr) OATPP_ASSERT(s->size() == 7); OATPP_ASSERT(s != "abc"); OATPP_ASSERT(s != "abc\0xyz"); OATPP_ASSERT(s == std::string("abc\0xyz", 7)); OATPP_ASSERT(s == a); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test std::string move assign operator"); oatpp::String s; std::string a = std::string("abc\0xyz", 7); s = std::move(a); OATPP_ASSERT(s); OATPP_ASSERT(s != nullptr); OATPP_ASSERT(s != (const char*) nullptr) OATPP_ASSERT(s->size() == 7); OATPP_ASSERT(s != "abc"); OATPP_ASSERT(s != "abc\0xyz"); OATPP_ASSERT(s == std::string("abc\0xyz", 7)); OATPP_ASSERT(a == ""); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test const char* implicit constructor"); oatpp::String s = ""; OATPP_ASSERT(s); OATPP_ASSERT(s != nullptr); OATPP_ASSERT(s != (const char*) nullptr) OATPP_ASSERT(s->size() == 0); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test '==', '!=' operators"); oatpp::String s1 = "a"; oatpp::String s2; OATPP_ASSERT(s1 != s2); OATPP_ASSERT(s2 != s1); OATPP_ASSERT(s1 == "a"); OATPP_ASSERT(s1 != "aa"); OATPP_ASSERT(s1 != ""); s2 = "aa"; OATPP_ASSERT(s1 != s2); OATPP_ASSERT(s2 != s1); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test copy-asssign operator"); oatpp::String s1 = "s1"; oatpp::String s2; s2 = s1; OATPP_ASSERT(s1 == s2); OATPP_ASSERT(s1.get() == s2.get()); s1 = "s2"; OATPP_ASSERT(s1 != s2); OATPP_ASSERT(s2 != s1); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test const char* assign operator"); oatpp::String s1 = "s1"; oatpp::String s2(s1); OATPP_ASSERT(s1 == s2); OATPP_ASSERT(s1.get() == s2.get()); s1 = "s2"; OATPP_ASSERT(s1 != s2); OATPP_ASSERT(s2 != s1); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test move assign operator"); oatpp::String s1 = "s1"; oatpp::String s2; s2 = std::move(s1); OATPP_ASSERT(s1 == nullptr); OATPP_ASSERT(s2 != nullptr); OATPP_ASSERT(s2 == "s1"); OATPP_ASSERT(s1 != s2); OATPP_ASSERT(s1.get() != s2.get()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test compareCI_ASCII methods 1"); oatpp::String s1 = "hello"; { oatpp::String s2; OATPP_ASSERT(!s1.equalsCI_ASCII(s2)); } { const char* s2 = nullptr; OATPP_ASSERT(!s1.equalsCI_ASCII(s2)); } } { OATPP_LOGI(TAG, "test compareCI_ASCII methods 2"); oatpp::String s1; { oatpp::String s2 = "hello"; OATPP_ASSERT(!s1.equalsCI_ASCII(s2)); } { std::string s2 = "hello"; OATPP_ASSERT(!s1.equalsCI_ASCII(s2)); } { const char* s2 = "hello"; OATPP_ASSERT(!s1.equalsCI_ASCII(s2)); } { oatpp::String s2; OATPP_ASSERT(s1.equalsCI_ASCII(s2)); } { const char* s2 = nullptr; OATPP_ASSERT(s1.equalsCI_ASCII(s2)); } { OATPP_ASSERT(s1.equalsCI_ASCII(nullptr)); } { bool exceptionThrown = false; try { std::string s2 = s1; } catch (const std::runtime_error& e) { exceptionThrown = true; } OATPP_ASSERT(exceptionThrown); } } { OATPP_LOGI(TAG, "test compareCI_ASCII methods 3"); oatpp::String s1 = "hello"; { oatpp::String s2 = "HELLO"; OATPP_ASSERT(s1.equalsCI_ASCII(s2)); } { std::string s2 = "HELLO"; OATPP_ASSERT(s1.equalsCI_ASCII(s2)); } { const char* s2 = "HELLO"; OATPP_ASSERT(s1.equalsCI_ASCII(s2)); } { OATPP_ASSERT(s1.equalsCI_ASCII("HELLO")); } } { OATPP_LOGI(TAG, "check default value"); oatpp::String s0; oatpp::String s1 = "hello"; OATPP_ASSERT(s0.getValue("def") == "def") OATPP_ASSERT(s1.getValue("def") == "hello") } } }}}}}}
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/StringTest.cpp
C++
apache-2.0
7,532
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_core_data_mapping_type_StringTest_hpp #define oatpp_test_core_data_mapping_type_StringTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { class StringTest : public UnitTest{ public: StringTest():UnitTest("TEST[core::data::mapping::type::StringTest]"){} void onRun() override; }; }}}}}} #endif /* oatpp_test_core_data_mapping_type_StringTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/StringTest.hpp
C++
apache-2.0
1,473
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "TypeTest.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/core/macro/codegen.hpp" #include "oatpp/core/Types.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { namespace { #include OATPP_CODEGEN_BEGIN(DTO) class TestDto : public oatpp::DTO { DTO_INIT(TestDto, DTO); DTO_FIELD(String, field_string); DTO_FIELD(Int8, field_int8); DTO_FIELD(Int16, field_int16); DTO_FIELD(Int32, field_int32); DTO_FIELD(Int64, field_int64); DTO_FIELD(Float32, field_float32); DTO_FIELD(Float64, field_float64); DTO_FIELD(Boolean, field_boolean); DTO_FIELD(List<String>, field_list_string); DTO_FIELD(List<Int32>, field_list_int32); DTO_FIELD(List<Int64>, field_list_int64); DTO_FIELD(List<Float32>, field_list_float32); DTO_FIELD(List<Float64>, field_list_float64); DTO_FIELD(List<Boolean>, field_list_boolean); DTO_FIELD(Fields<String>, field_map_string_string); DTO_FIELD(Object<TestDto>, obj1); }; #include OATPP_CODEGEN_END(DTO) } void TypeTest::onRun() { auto obj = TestDto::createShared(); OATPP_LOGV(TAG, "type: '%s'", obj->field_string.getValueType()->classId.name); OATPP_ASSERT(obj->field_string.getValueType()->classId == oatpp::data::mapping::type::__class::String::CLASS_ID); OATPP_LOGV(TAG, "type: '%s'", obj->field_int8.getValueType()->classId.name); OATPP_ASSERT(obj->field_int8.getValueType()->classId == oatpp::data::mapping::type::__class::Int8::CLASS_ID); OATPP_LOGV(TAG, "type: '%s'", obj->field_int16.getValueType()->classId.name); OATPP_ASSERT(obj->field_int16.getValueType()->classId == oatpp::data::mapping::type::__class::Int16::CLASS_ID); OATPP_LOGV(TAG, "type: '%s'", obj->field_int32.getValueType()->classId.name); OATPP_ASSERT(obj->field_int32.getValueType()->classId == oatpp::data::mapping::type::__class::Int32::CLASS_ID); OATPP_LOGV(TAG, "type: '%s'", obj->field_int64.getValueType()->classId.name); OATPP_ASSERT(obj->field_int64.getValueType()->classId == oatpp::data::mapping::type::__class::Int64::CLASS_ID); OATPP_LOGV(TAG, "type: '%s'", obj->field_float32.getValueType()->classId.name); OATPP_ASSERT(obj->field_float32.getValueType()->classId == oatpp::data::mapping::type::__class::Float32::CLASS_ID); OATPP_LOGV(TAG, "type: '%s'", obj->field_float64.getValueType()->classId.name); OATPP_ASSERT(obj->field_float64.getValueType()->classId == oatpp::data::mapping::type::__class::Float64::CLASS_ID); OATPP_LOGV(TAG, "type: '%s'", obj->field_boolean.getValueType()->classId.name); OATPP_ASSERT(obj->field_boolean.getValueType()->classId == oatpp::data::mapping::type::__class::Boolean::CLASS_ID); OATPP_LOGV(TAG, "type: '%s'", obj->field_list_string.getValueType()->classId.name); OATPP_ASSERT(obj->field_list_string.getValueType()->classId == oatpp::data::mapping::type::__class::AbstractList::CLASS_ID); OATPP_LOGV(TAG, "type: '%s'", obj->field_list_int32.getValueType()->classId.name); OATPP_ASSERT(obj->field_list_int32.getValueType()->classId == oatpp::data::mapping::type::__class::AbstractList::CLASS_ID); OATPP_LOGV(TAG, "type: '%s'", obj->field_list_int64.getValueType()->classId.name); OATPP_ASSERT(obj->field_list_int64.getValueType()->classId == oatpp::data::mapping::type::__class::AbstractList::CLASS_ID); OATPP_LOGV(TAG, "type: '%s'", obj->field_list_float32.getValueType()->classId.name); OATPP_ASSERT(obj->field_list_float32.getValueType()->classId == oatpp::data::mapping::type::__class::AbstractList::CLASS_ID); OATPP_LOGV(TAG, "type: '%s'", obj->field_list_float64.getValueType()->classId.name); OATPP_ASSERT(obj->field_list_float64.getValueType()->classId == oatpp::data::mapping::type::__class::AbstractList::CLASS_ID); OATPP_LOGV(TAG, "type: '%s'", obj->field_list_boolean.getValueType()->classId.name); OATPP_ASSERT(obj->field_list_boolean.getValueType()->classId == oatpp::data::mapping::type::__class::AbstractList::CLASS_ID); OATPP_LOGV(TAG, "type: '%s'", obj->field_map_string_string.getValueType()->classId.name); OATPP_ASSERT(obj->field_map_string_string.getValueType()->classId == oatpp::data::mapping::type::__class::AbstractPairList::CLASS_ID); OATPP_LOGV(TAG, "type: '%s'", obj->obj1.getValueType()->classId.name); OATPP_ASSERT(obj->obj1.getValueType()->classId == oatpp::data::mapping::type::__class::AbstractObject::CLASS_ID); OATPP_ASSERT(oatpp::String::Class::getType()->extends(oatpp::String::Class::getType())) OATPP_ASSERT(oatpp::Int32::Class::getType()->extends(oatpp::Int32::Class::getType())) OATPP_ASSERT(!oatpp::String::Class::getType()->extends(oatpp::Int32::Class::getType())) } }}}}}}
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/TypeTest.cpp
C++
apache-2.0
5,790
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_core_data_mapping_type_TypeTest_hpp #define oatpp_test_core_data_mapping_type_TypeTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { class TypeTest : public UnitTest{ public: TypeTest():UnitTest("TEST[core::data::mapping::type::TypeTest]"){} void onRun() override; }; }}}}}} #endif /* oatpp_test_core_data_mapping_type_TypeTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/TypeTest.hpp
C++
apache-2.0
1,469
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "UnorderedMapTest.hpp" #include "oatpp/core/Types.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { void UnorderedMapTest::onRun() { { OATPP_LOGI(TAG, "test default constructor..."); oatpp::UnorderedFields<String> map; OATPP_ASSERT(!map); OATPP_ASSERT(map == nullptr); OATPP_ASSERT(map.get() == nullptr); OATPP_ASSERT(map.getValueType()->classId.id == oatpp::data::mapping::type::__class::AbstractUnorderedMap::CLASS_ID.id); OATPP_ASSERT(map.getValueType()->params.size() == 2); auto it = map.getValueType()->params.begin(); OATPP_ASSERT(*it++ == oatpp::String::Class::getType()); OATPP_ASSERT(*it++ == oatpp::String::Class::getType()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test empty ilist constructor..."); oatpp::UnorderedFields<String> map({}); OATPP_ASSERT(map); OATPP_ASSERT(map != nullptr); OATPP_ASSERT(map->size() == 0); OATPP_ASSERT(map.get() != nullptr); OATPP_ASSERT(map.getValueType()->classId.id == oatpp::data::mapping::type::__class::AbstractUnorderedMap::CLASS_ID.id); OATPP_ASSERT(map.getValueType()->params.size() == 2); auto it = map.getValueType()->params.begin(); OATPP_ASSERT(*it++ == oatpp::String::Class::getType()); OATPP_ASSERT(*it++ == oatpp::String::Class::getType()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test createShared()..."); oatpp::UnorderedFields<String> map = oatpp::UnorderedFields<String>::createShared(); OATPP_ASSERT(map); OATPP_ASSERT(map != nullptr); OATPP_ASSERT(map->size() == 0); OATPP_ASSERT(map.get() != nullptr); OATPP_ASSERT(map.getValueType()->classId.id == oatpp::data::mapping::type::__class::AbstractUnorderedMap::CLASS_ID.id); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test copy-assignment operator..."); oatpp::UnorderedFields<String> map1({}); oatpp::UnorderedFields<String> map2; map2 = map1; OATPP_ASSERT(map1); OATPP_ASSERT(map2); OATPP_ASSERT(map1->size() == 0); OATPP_ASSERT(map2->size() == 0); OATPP_ASSERT(map1.get() == map2.get()); map2->insert({"key", "a"}); OATPP_ASSERT(map1->size() == 1); OATPP_ASSERT(map2->size() == 1); map2 = {{"key1", "b"}, {"key2", "c"}}; OATPP_ASSERT(map1->size() == 1); OATPP_ASSERT(map2->size() == 2); OATPP_ASSERT(map2["key1"] == "b"); OATPP_ASSERT(map2["key2"] == "c"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test move-assignment operator..."); oatpp::UnorderedFields<String> map1({}); oatpp::UnorderedFields<String> map2; map2 = std::move(map1); OATPP_ASSERT(!map1); OATPP_ASSERT(map2); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test get element by index..."); oatpp::UnorderedFields<String> map = {{"key1", "a"}, {"key2", "b"}, {"key3", "c"}}; OATPP_ASSERT(map); OATPP_ASSERT(map != nullptr); OATPP_ASSERT(map->size() == 3); OATPP_ASSERT(map["key1"] == "a"); OATPP_ASSERT(map["key2"] == "b"); OATPP_ASSERT(map["key3"] == "c"); map["key2"] = "Hello!"; OATPP_ASSERT(map->size() == 3); OATPP_ASSERT(map["key1"] == "a"); OATPP_ASSERT(map["key2"] == "Hello!"); OATPP_ASSERT(map["key3"] == "c"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test polymorphicDispatcher..."); oatpp::UnorderedFields<String> map = {{"key1", "a"}, {"key2", "b"}, {"key3", "c"}}; auto polymorphicDispatcher = static_cast<const typename oatpp::data::mapping::type::__class::Map::PolymorphicDispatcher*>( map.getValueType()->polymorphicDispatcher ); polymorphicDispatcher->addItem(map, oatpp::String("key1"), oatpp::String("d")); OATPP_ASSERT(map->size() == 3); OATPP_ASSERT(map["key1"] == "d"); OATPP_ASSERT(map["key2"] == "b"); OATPP_ASSERT(map["key3"] == "c"); OATPP_LOGI(TAG, "OK"); } } }}}}}}
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/UnorderedMapTest.cpp
C++
apache-2.0
4,948
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_core_data_mapping_type_UnorderedMapTest_hpp #define oatpp_test_core_data_mapping_type_UnorderedMapTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { class UnorderedMapTest : public UnitTest{ public: UnorderedMapTest():UnitTest("TEST[core::data::mapping::type::UnorderedMapTest]"){} void onRun() override; }; }}}}}} #endif /* oatpp_test_core_data_mapping_type_UnorderedMapTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/UnorderedMapTest.hpp
C++
apache-2.0
1,509
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "UnorderedSetTest.hpp" #include "oatpp/core/Types.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { void UnorderedSetTest::onRun() { { OATPP_LOGI(TAG, "test default constructor..."); oatpp::UnorderedSet<oatpp::String> set; OATPP_ASSERT(!set); OATPP_ASSERT(set == nullptr); OATPP_ASSERT(set.get() == nullptr); OATPP_ASSERT(set.getValueType()->classId.id == oatpp::data::mapping::type::__class::AbstractUnorderedSet::CLASS_ID.id); OATPP_ASSERT(set.getValueType()->params.size() == 1); OATPP_ASSERT(set.getValueType()->params.front() == oatpp::String::Class::getType()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test empty ilist constructor..."); oatpp::UnorderedSet<oatpp::String> set({}); OATPP_ASSERT(set); OATPP_ASSERT(set != nullptr); OATPP_ASSERT(set->size() == 0); OATPP_ASSERT(set.get() != nullptr); OATPP_ASSERT(set.getValueType()->classId.id == oatpp::data::mapping::type::__class::AbstractUnorderedSet::CLASS_ID.id); OATPP_ASSERT(set.getValueType()->params.size() == 1); OATPP_ASSERT(set.getValueType()->params.front() == oatpp::String::Class::getType()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test createShared()..."); oatpp::UnorderedSet<oatpp::String> set = oatpp::UnorderedSet<oatpp::String>::createShared(); OATPP_ASSERT(set); OATPP_ASSERT(set != nullptr); OATPP_ASSERT(set->size() == 0); OATPP_ASSERT(set.get() != nullptr); OATPP_ASSERT(set.getValueType()->classId.id == oatpp::data::mapping::type::__class::AbstractUnorderedSet::CLASS_ID.id); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test copy-assignment operator..."); oatpp::UnorderedSet<oatpp::String> set1({}); oatpp::UnorderedSet<oatpp::String> set2; set2 = set1; OATPP_ASSERT(set1); OATPP_ASSERT(set2); OATPP_ASSERT(set1->size() == 0); OATPP_ASSERT(set2->size() == 0); OATPP_ASSERT(set1.get() == set2.get()); set2->insert("a"); OATPP_ASSERT(set1->size() == 1); OATPP_ASSERT(set2->size() == 1); set2 = {"b", "c"}; OATPP_ASSERT(set1->size() == 1); OATPP_ASSERT(set2->size() == 2); OATPP_ASSERT(set2["b"] == true); OATPP_ASSERT(set2["c"] == true); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test move-assignment operator..."); oatpp::UnorderedSet<oatpp::String> set1({}); oatpp::UnorderedSet<oatpp::String> set2; set2 = std::move(set1); OATPP_ASSERT(!set1); OATPP_ASSERT(set2); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test polymorphicDispatcher..."); oatpp::UnorderedSet<oatpp::String> set = {"a", "b", "c"}; auto polymorphicDispatcher = static_cast<const typename oatpp::data::mapping::type::__class::Collection::PolymorphicDispatcher*>( set.getValueType()->polymorphicDispatcher ); polymorphicDispatcher->addItem(set, oatpp::String("a")); polymorphicDispatcher->addItem(set, oatpp::String("b")); polymorphicDispatcher->addItem(set, oatpp::String("c")); polymorphicDispatcher->addItem(set, oatpp::String("d")); OATPP_ASSERT(set->size() == 4); OATPP_ASSERT(set["a"]); OATPP_ASSERT(set["b"]); OATPP_ASSERT(set["c"]); OATPP_ASSERT(set["d"]); OATPP_LOGI(TAG, "OK"); } } }}}}}}
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/UnorderedSetTest.cpp
C++
apache-2.0
4,355
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_core_data_mapping_type_UnorderedSetTest_hpp #define oatpp_test_core_data_mapping_type_UnorderedSetTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { class UnorderedSetTest : public UnitTest{ public: UnorderedSetTest():UnitTest("TEST[core::data::mapping::type::UnorderedSetTest]"){} void onRun() override; }; }}}}}} #endif /* oatpp_test_core_data_mapping_type_UnorderedSetTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/UnorderedSetTest.hpp
C++
apache-2.0
1,509
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "VectorTest.hpp" #include "oatpp/core/Types.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { void VectorTest::onRun() { { OATPP_LOGI(TAG, "test default constructor..."); oatpp::Vector<oatpp::String> vector; OATPP_ASSERT(!vector); OATPP_ASSERT(vector == nullptr); OATPP_ASSERT(vector.get() == nullptr); OATPP_ASSERT(vector.getValueType()->classId.id == oatpp::data::mapping::type::__class::AbstractVector::CLASS_ID.id); OATPP_ASSERT(vector.getValueType()->params.size() == 1); OATPP_ASSERT(vector.getValueType()->params.front() == oatpp::String::Class::getType()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test empty ilist constructor..."); oatpp::Vector<oatpp::String> vector({}); OATPP_ASSERT(vector); OATPP_ASSERT(vector != nullptr); OATPP_ASSERT(vector->size() == 0); OATPP_ASSERT(vector.get() != nullptr); OATPP_ASSERT(vector.getValueType()->classId.id == oatpp::data::mapping::type::__class::AbstractVector::CLASS_ID.id); OATPP_ASSERT(vector.getValueType()->params.size() == 1); OATPP_ASSERT(vector.getValueType()->params.front() == oatpp::String::Class::getType()); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test createShared()..."); oatpp::Vector<oatpp::String> vector = oatpp::Vector<oatpp::String>::createShared(); OATPP_ASSERT(vector); OATPP_ASSERT(vector != nullptr); OATPP_ASSERT(vector->size() == 0); OATPP_ASSERT(vector.get() != nullptr); OATPP_ASSERT(vector.getValueType()->classId.id == oatpp::data::mapping::type::__class::AbstractVector::CLASS_ID.id); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test copy-assignment operator..."); oatpp::Vector<oatpp::String> vector1({}); oatpp::Vector<oatpp::String> vector2; vector2 = vector1; OATPP_ASSERT(vector1); OATPP_ASSERT(vector2); OATPP_ASSERT(vector1->size() == 0); OATPP_ASSERT(vector2->size() == 0); OATPP_ASSERT(vector1.get() == vector2.get()); vector2->push_back("a"); OATPP_ASSERT(vector1->size() == 1); OATPP_ASSERT(vector2->size() == 1); vector2 = {"b", "c"}; OATPP_ASSERT(vector1->size() == 1); OATPP_ASSERT(vector2->size() == 2); OATPP_ASSERT(vector2[0] == "b"); OATPP_ASSERT(vector2[1] == "c"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test move-assignment operator..."); oatpp::Vector<oatpp::String> vector1({}); oatpp::Vector<oatpp::String> vector2; vector2 = std::move(vector1); OATPP_ASSERT(!vector1); OATPP_ASSERT(vector2); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test get element by index..."); oatpp::Vector<oatpp::String> vector = {"a", "b", "c"}; OATPP_ASSERT(vector); OATPP_ASSERT(vector != nullptr); OATPP_ASSERT(vector->size() == 3); OATPP_ASSERT(vector[0] == "a"); OATPP_ASSERT(vector[1] == "b"); OATPP_ASSERT(vector[2] == "c"); vector[1] = "Hello!"; OATPP_ASSERT(vector->size() == 3); OATPP_ASSERT(vector[0] == "a"); OATPP_ASSERT(vector[1] == "Hello!"); OATPP_ASSERT(vector[2] == "c"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "test polymorphicDispatcher..."); oatpp::Vector<oatpp::String> vector = {"a", "b", "c"}; auto polymorphicDispatcher = static_cast<const oatpp::data::mapping::type::__class::Collection::PolymorphicDispatcher*>( vector.getValueType()->polymorphicDispatcher ); polymorphicDispatcher->addItem(vector, oatpp::String("d")); OATPP_ASSERT(vector->size() == 4); OATPP_ASSERT(vector[0] == "a"); OATPP_ASSERT(vector[1] == "b"); OATPP_ASSERT(vector[2] == "c"); OATPP_ASSERT(vector[3] == "d"); OATPP_LOGI(TAG, "OK"); } } }}}}}}
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/VectorTest.cpp
C++
apache-2.0
4,793
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_core_data_mapping_type_VectorTest_hpp #define oatpp_test_core_data_mapping_type_VectorTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type { class VectorTest : public UnitTest{ public: VectorTest():UnitTest("TEST[core::data::mapping::type::VectorTest]"){} void onRun() override; }; }}}}}} #endif /* oatpp_test_core_data_mapping_type_VectorTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/core/data/mapping/type/VectorTest.hpp
C++
apache-2.0
1,473
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "InMemoryDataTest.hpp" #include "oatpp/core/data/resource/InMemoryData.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace resource { void InMemoryDataTest::onRun() { { oatpp::data::resource::InMemoryData data; OATPP_ASSERT(data.getKnownSize() == 0) OATPP_ASSERT(data.getInMemoryData() == nullptr) OATPP_ASSERT(data.getLocation() == nullptr) } { oatpp::String testData = "Hello World"; oatpp::data::resource::InMemoryData data; { auto s = data.openOutputStream(); s->writeExactSizeDataSimple(testData->data(), testData->size()); } OATPP_ASSERT(data.getKnownSize() == testData->size()) OATPP_ASSERT(data.getInMemoryData() == testData) OATPP_ASSERT(data.getLocation() == nullptr) } { oatpp::String testData1 = "Hello"; oatpp::String testData2 = "World"; oatpp::data::resource::InMemoryData data("data="); { auto s1 = data.openOutputStream(); s1->writeExactSizeDataSimple(testData1->data(), testData1->size()); auto s2 = data.openOutputStream(); s2->writeExactSizeDataSimple(testData2->data(), testData2->size()); s1.reset(); OATPP_ASSERT(data.getInMemoryData() == "data=" + testData1) } OATPP_ASSERT(data.getInMemoryData() == "data=" + testData2) } { oatpp::String testData = "Hello"; oatpp::data::resource::InMemoryData data("data="); auto is = data.openInputStream(); { auto s1 = data.openOutputStream(); s1->writeExactSizeDataSimple(testData->data(), testData->size()); } oatpp::data::stream::BufferOutputStream s; char buffer[100]; oatpp::data::stream::transfer(is, &s, 0, buffer, 100); OATPP_ASSERT(s.toString() == "data=") } } }}}}}
vincent-in-black-sesame/oat
test/oatpp/core/data/resource/InMemoryDataTest.cpp
C++
apache-2.0
2,775
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_core_data_resource_InMemoryDataTest_hpp #define oatpp_test_core_data_resource_InMemoryDataTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace resource { class InMemoryDataTest : public UnitTest{ public: InMemoryDataTest():UnitTest("TEST[core::data::resource::type::InMemoryDataTest]"){} void onRun() override; }; }}}}} #endif /* oatpp_test_core_data_resource_InMemoryDataTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/core/data/resource/InMemoryDataTest.hpp
C++
apache-2.0
1,480
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "LazyStringMapTest.hpp" #include "oatpp/core/data/share/LazyStringMap.hpp" #include "oatpp/core/Types.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace share { namespace { typedef oatpp::data::share::StringKeyLabel StringKeyLabel; typedef oatpp::data::share::StringKeyLabelCI StringKeyLabelCI; template<class T> using LazyStringMap = oatpp::data::share::LazyStringMap<T>; } void LazyStringMapTest::onRun() { const char* text = "Hello World!"; { LazyStringMap<StringKeyLabel> map; map.put("key1", StringKeyLabel(nullptr, text, 5)); map.put("key2", StringKeyLabel(nullptr, text + 6, 6)); oatpp::String s1 = map.get("key1"); oatpp::String s2 = map.get("key2"); OATPP_ASSERT(s1 == "Hello"); OATPP_ASSERT(s2 == "World!"); oatpp::String s12 = map.get("key1"); oatpp::String s22 = map.get("key2"); OATPP_ASSERT(s1.get() == s12.get()); OATPP_ASSERT(s2.get() == s22.get()); OATPP_ASSERT(map.get("KEY1") == nullptr); OATPP_ASSERT(map.get("KEY2") == nullptr); auto all = map.getAll(); auto s13 = all["key1"]; auto s23 = all["key2"]; OATPP_ASSERT(s13.getData() == s1->data() && s13.getSize() == s1->size()); OATPP_ASSERT(s23.getData() == s2->data() && s23.getSize() == s2->size()); OATPP_ASSERT(s1.get() == s13.getMemoryHandle().get()); OATPP_ASSERT(s2.get() == s23.getMemoryHandle().get()); OATPP_ASSERT(map.getSize() == 2); } { LazyStringMap<StringKeyLabelCI> map; map.put("key1", StringKeyLabel(nullptr, text, 5)); map.put("key2", StringKeyLabel(nullptr, text + 6, 6)); auto s01 = map.getAsMemoryLabel_Unsafe<StringKeyLabel>("key1"); auto s02 = map.getAsMemoryLabel_Unsafe<StringKeyLabel>("key2"); OATPP_ASSERT(s01 == "Hello"); OATPP_ASSERT(s02 == "World!"); OATPP_ASSERT(s01.getMemoryHandle() == nullptr); OATPP_ASSERT(s02.getMemoryHandle() == nullptr); auto s1 = map.getAsMemoryLabel<StringKeyLabel>("key1"); auto s2 = map.getAsMemoryLabel<StringKeyLabel>("key2"); OATPP_ASSERT(s1 == "Hello"); OATPP_ASSERT(s2 == "World!"); oatpp::String s12 = map.get("key1"); oatpp::String s22 = map.get("key2"); OATPP_ASSERT(s1.getMemoryHandle().get() == s12.get()); OATPP_ASSERT(s2.getMemoryHandle().get() == s22.get()); OATPP_ASSERT(map.getAsMemoryLabel<StringKeyLabel>("KEY1") == s1); OATPP_ASSERT(map.getAsMemoryLabel<StringKeyLabel>("KEY2") == s2); } { LazyStringMap<StringKeyLabelCI> map1; LazyStringMap<StringKeyLabelCI> map2; map1.put("key1", StringKeyLabel(nullptr, text, 5)); map1.put("key2", StringKeyLabel(nullptr, text + 6, 6)); OATPP_ASSERT(map1.getSize() == 2); OATPP_ASSERT(map2.getSize() == 0); map2 = std::move(map1); OATPP_ASSERT(map1.getSize() == 0); OATPP_ASSERT(map2.getSize() == 2); { auto all = map2.getAll_Unsafe(); auto s1 = all["key1"]; auto s2 = all["key2"]; OATPP_ASSERT(s1.getMemoryHandle() == nullptr); OATPP_ASSERT(s2.getMemoryHandle() == nullptr); OATPP_ASSERT(s1 == "Hello"); OATPP_ASSERT(s2 == "World!"); } { auto all = map2.getAll(); auto s1 = all["key1"]; auto s2 = all["key2"]; OATPP_ASSERT(s1.getMemoryHandle()); OATPP_ASSERT(s2.getMemoryHandle()); OATPP_ASSERT(s1 == "Hello"); OATPP_ASSERT(s2 == "World!"); auto s12 = map2.get("key1"); auto s22 = map2.get("key2"); OATPP_ASSERT(s1.getMemoryHandle().get() == s12.get()); OATPP_ASSERT(s2.getMemoryHandle().get() == s22.get()); } } } }}}}}
vincent-in-black-sesame/oat
test/oatpp/core/data/share/LazyStringMapTest.cpp
C++
apache-2.0
4,644
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_core_data_share_LazyStringMapTest_hpp #define oatpp_test_core_data_share_LazyStringMapTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace share { class LazyStringMapTest : public UnitTest{ public: LazyStringMapTest():UnitTest("TEST[core::data::share::LazyStringMapTest]"){} void onRun() override; }; }}}}} #endif // oatpp_test_core_data_share_LazyStringMapTest_hpp
vincent-in-black-sesame/oat
test/oatpp/core/data/share/LazyStringMapTest.hpp
C++
apache-2.0
1,462
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "MemoryLabelTest.hpp" #include "oatpp/core/data/share/MemoryLabel.hpp" #include <unordered_map> #include "oatpp/web/protocol/http/Http.hpp" #include "oatpp-test/Checker.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace share { namespace { typedef oatpp::data::share::MemoryLabel MemoryLabel; typedef oatpp::data::share::StringKeyLabel StringKeyLabel; typedef oatpp::data::share::StringKeyLabelCI StringKeyLabelCI; } void MemoryLabelTest::onRun() { { OATPP_LOGI(TAG, "StringKeyLabel default constructor..."); StringKeyLabel s; StringKeyLabel s0; OATPP_ASSERT(!s); OATPP_ASSERT(s == nullptr); OATPP_ASSERT(s == s0); OATPP_ASSERT(s != "text"); OATPP_ASSERT(s != oatpp::String("text")); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "StringKeyLabel nullptr constructor..."); StringKeyLabel s(nullptr); OATPP_ASSERT(!s); OATPP_ASSERT(s == nullptr); OATPP_ASSERT(s != "text"); OATPP_ASSERT(s != oatpp::String("text")); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "StringKeyLabel const char* constructor..."); StringKeyLabel s("hello"); StringKeyLabel s0; OATPP_ASSERT(s); OATPP_ASSERT(s != nullptr); OATPP_ASSERT(s != s0); OATPP_ASSERT(s0 != s); OATPP_ASSERT(s == "hello"); OATPP_ASSERT(s == oatpp::String("hello")); OATPP_ASSERT(s != "text"); OATPP_ASSERT(s != oatpp::String("text")); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "StringKeyLabel oatpp::String constructor..."); StringKeyLabel s(oatpp::String("hello")); OATPP_ASSERT(s); OATPP_ASSERT(s != nullptr); OATPP_ASSERT(s == "hello"); OATPP_ASSERT(s == oatpp::String("hello")); OATPP_ASSERT(s != "text"); OATPP_ASSERT(s != oatpp::String("text")); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "StringKeyLabelCI default constructor..."); StringKeyLabelCI s; StringKeyLabelCI s0; OATPP_ASSERT(!s); OATPP_ASSERT(s == nullptr); OATPP_ASSERT(s == s0); OATPP_ASSERT(s != "teXt"); OATPP_ASSERT(s != oatpp::String("teXt")); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "StringKeyLabelCI nullptr constructor..."); StringKeyLabelCI s(nullptr); OATPP_ASSERT(!s); OATPP_ASSERT(s == nullptr); OATPP_ASSERT(s != "teXt"); OATPP_ASSERT(s != oatpp::String("teXt")); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "StringKeyLabelCI const char* constructor..."); StringKeyLabelCI s("hello"); StringKeyLabelCI s0; OATPP_ASSERT(s); OATPP_ASSERT(s != nullptr); OATPP_ASSERT(s != s0); OATPP_ASSERT(s0 != s); OATPP_ASSERT(s == "helLO"); OATPP_ASSERT(s == oatpp::String("helLO")); OATPP_ASSERT(s != "text"); OATPP_ASSERT(s != oatpp::String("teXt")); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "StringKeyLabelCI oatpp::String constructor..."); StringKeyLabelCI s(oatpp::String("hello")); OATPP_ASSERT(s); OATPP_ASSERT(s != nullptr); OATPP_ASSERT(s == "helLO"); OATPP_ASSERT(s == oatpp::String("helLO")); OATPP_ASSERT(s != "text"); OATPP_ASSERT(s != oatpp::String("teXt")); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "general test..."); oatpp::String sharedData = "big text goes here"; oatpp::String key1 = "key1"; oatpp::String key2 = "key2"; oatpp::String key3 = "key3"; oatpp::String key4 = "key4"; std::unordered_map<StringKeyLabel, MemoryLabel> stringMap; std::unordered_map<StringKeyLabelCI, MemoryLabel> stringMapCI; // Case-Sensitive stringMap[key1] = MemoryLabel(sharedData.getPtr(), &sharedData->data()[0], 3); stringMap[key2] = MemoryLabel(sharedData.getPtr(), &sharedData->data()[4], 4); stringMap[key3] = MemoryLabel(sharedData.getPtr(), &sharedData->data()[9], 4); stringMap[key4] = MemoryLabel(sharedData.getPtr(), &sharedData->data()[14], 4); OATPP_ASSERT(stringMap["key1"].equals("big")); OATPP_ASSERT(stringMap["key2"].equals("text")); OATPP_ASSERT(stringMap["key3"].equals("goes")); OATPP_ASSERT(stringMap["key4"].equals("here")); OATPP_ASSERT(stringMap.find("Key1") == stringMap.end()); OATPP_ASSERT(stringMap.find("Key2") == stringMap.end()); OATPP_ASSERT(stringMap.find("Key3") == stringMap.end()); OATPP_ASSERT(stringMap.find("Key4") == stringMap.end()); // CI stringMapCI[key1] = MemoryLabel(sharedData.getPtr(), &sharedData->data()[0], 3); stringMapCI[key2] = MemoryLabel(sharedData.getPtr(), &sharedData->data()[4], 4); stringMapCI[key3] = MemoryLabel(sharedData.getPtr(), &sharedData->data()[9], 4); stringMapCI[key4] = MemoryLabel(sharedData.getPtr(), &sharedData->data()[14], 4); OATPP_ASSERT(stringMapCI["key1"].equals("big")); OATPP_ASSERT(stringMapCI["key2"].equals("text")); OATPP_ASSERT(stringMapCI["key3"].equals("goes")); OATPP_ASSERT(stringMapCI["key4"].equals("here")); OATPP_ASSERT(stringMapCI["KEY1"].equals("big")); OATPP_ASSERT(stringMapCI["KEY2"].equals("text")); OATPP_ASSERT(stringMapCI["KEY3"].equals("goes")); OATPP_ASSERT(stringMapCI["KEY4"].equals("here")); { v_int32 iterationsCount = 100; oatpp::String headersText = "header0: value0\r\n" "header1: value1\r\n" "header2: value2\r\n" "header3: value3\r\n" "header4: value4\r\n" "header5: value5\r\n" "header6: value6\r\n" "header7: value7\r\n" "header8: value8\r\n" "header9: value9\r\n" "\r\n"; { oatpp::test::PerformanceChecker timer("timer"); for (v_int32 i = 0; i < iterationsCount; i++) { oatpp::parser::Caret caret(headersText); oatpp::web::protocol::http::Status status; oatpp::web::protocol::http::Headers headers; oatpp::web::protocol::http::Parser::parseHeaders(headers, headersText.getPtr(), caret, status); OATPP_ASSERT(status.code == 0); OATPP_ASSERT(headers.getSize() == 10); OATPP_ASSERT(headers.getAsMemoryLabel<StringKeyLabel>("header0").equals("value0", 6)); OATPP_ASSERT(headers.getAsMemoryLabel<StringKeyLabel>("header1").equals("value1", 6)); OATPP_ASSERT(headers.getAsMemoryLabel<StringKeyLabel>("header2").equals("value2", 6)); OATPP_ASSERT(headers.getAsMemoryLabel<StringKeyLabel>("header3").equals("value3", 6)); OATPP_ASSERT(headers.getAsMemoryLabel<StringKeyLabel>("header4").equals("value4", 6)); OATPP_ASSERT(headers.getAsMemoryLabel<StringKeyLabel>("header5").equals("value5", 6)); OATPP_ASSERT(headers.getAsMemoryLabel<StringKeyLabel>("header6").equals("value6", 6)); OATPP_ASSERT(headers.getAsMemoryLabel<StringKeyLabel>("header7").equals("value7", 6)); OATPP_ASSERT(headers.getAsMemoryLabel<StringKeyLabel>("header8").equals("value8", 6)); OATPP_ASSERT(headers.getAsMemoryLabel<StringKeyLabel>("header9").equals("value9", 6)); OATPP_ASSERT(headers.getAsMemoryLabel<StringKeyLabel>("header0").equals("value0")); OATPP_ASSERT(headers.getAsMemoryLabel<StringKeyLabel>("header1").equals("value1")); OATPP_ASSERT(headers.getAsMemoryLabel<StringKeyLabel>("header2").equals("value2")); OATPP_ASSERT(headers.getAsMemoryLabel<StringKeyLabel>("header3").equals("value3")); OATPP_ASSERT(headers.getAsMemoryLabel<StringKeyLabel>("header4").equals("value4")); OATPP_ASSERT(headers.getAsMemoryLabel<StringKeyLabel>("header5").equals("value5")); OATPP_ASSERT(headers.getAsMemoryLabel<StringKeyLabel>("header6").equals("value6")); OATPP_ASSERT(headers.getAsMemoryLabel<StringKeyLabel>("header7").equals("value7")); OATPP_ASSERT(headers.getAsMemoryLabel<StringKeyLabel>("header8").equals("value8")); OATPP_ASSERT(headers.getAsMemoryLabel<StringKeyLabel>("header9").equals("value9")); } } } OATPP_LOGI(TAG, "OK"); } { v_int32 iterationsCount = 100; oatpp::String headersText = "header0: value0\r\n" "header0: value1\r\n" "header1: value2\r\n" "header1: value3\r\n" "header2: value4\r\n" "header2: value5\r\n" "header3: value6\r\n" "header3: value7\r\n" "header4: value8\r\n" "header4: value9\r\n" "\r\n"; oatpp::parser::Caret caret(headersText); oatpp::web::protocol::http::Status status; oatpp::web::protocol::http::Headers headers; oatpp::web::protocol::http::Parser::parseHeaders(headers, headersText.getPtr(), caret, status); OATPP_ASSERT(status.code == 0); OATPP_ASSERT(headers.getSize() == 10); for(auto& h : headers.getAll()) { auto key = h.first.toString(); auto val = h.second.toString(); OATPP_LOGD(TAG, "'%s': '%s'", key->c_str(), val->c_str()); } } } }}}}}
vincent-in-black-sesame/oat
test/oatpp/core/data/share/MemoryLabelTest.cpp
C++
apache-2.0
9,899
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_core_data_share_MemoryLabelTest_hpp #define oatpp_test_core_data_share_MemoryLabelTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace share { class MemoryLabelTest : public UnitTest{ public: MemoryLabelTest():UnitTest("TEST[core::data::share::MemoryLabelTest]"){} void onRun() override; }; }}}}} #endif /* oatpp_test_core_data_share_MemoryLabelTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/core/data/share/MemoryLabelTest.hpp
C++
apache-2.0
1,461
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "StringTemplateTest.hpp" #include "oatpp/core/data/share/StringTemplate.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace share { void StringTemplateTest::onRun() { typedef oatpp::data::share::StringTemplate StringTemplate; { OATPP_LOGI(TAG, "Case1 ..."); StringTemplate t("{} World!", {{0, 1, "p1"}}); auto result = t.format(std::vector<oatpp::String>({"Hello"})); OATPP_ASSERT(result == "Hello World!"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Case2 ..."); StringTemplate t("{} World!", {{0, 1, "p1"}}); auto result = t.format(std::unordered_map<oatpp::String, oatpp::String>({{"p1", "Hello"}})); OATPP_ASSERT(result == "Hello World!"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Case3 ..."); StringTemplate t("Hello {}", {{6, 7, "p1"}}); auto result = t.format(std::vector<oatpp::String>({"World!"})); OATPP_ASSERT(result == "Hello World!"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Case4 ..."); StringTemplate t("Hello {}", {{6, 7, "p1"}}); auto result = t.format(std::unordered_map<oatpp::String, oatpp::String>({{"p1", "World!"}})); OATPP_ASSERT(result == "Hello World!"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Case5 ..."); StringTemplate t("Hello {} World!", {{6, 7, "p1"}}); auto result = t.format(std::vector<oatpp::String>({"My"})); OATPP_ASSERT(result == "Hello My World!"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Case6 ..."); StringTemplate t("Hello {} World!", {{6, 7, "p1"}}); auto result = t.format(std::unordered_map<oatpp::String, oatpp::String>({{"p1", "My"}})); OATPP_ASSERT(result == "Hello My World!"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Case7 ..."); StringTemplate t("? ? ?", {{0, 0, "p1"}, {2, 2, "p2"}, {4, 4, "p3"}}); auto result = t.format(std::vector<oatpp::String>({"Hello", "World", "Oat++!"})); OATPP_ASSERT(result == "Hello World Oat++!"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Case8 ..."); StringTemplate t("? ? ?", {{0, 0, "p1"}, {2, 2, "p2"}, {4, 4, "p3"}}); auto result = t.format(std::unordered_map<oatpp::String, oatpp::String>({{"p3", "Hello"}, {"p2", "World"}, {"p1", "Oat++!"}})); OATPP_ASSERT(result == "Oat++! World Hello"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Case9 ..."); StringTemplate t("? ? ?", {{0, 0, "p1"}, {2, 2, "p2"}, {4, 4, "p3"}}); auto result = t.format("A"); OATPP_ASSERT(result == "A A A"); OATPP_LOGI(TAG, "OK"); } { OATPP_LOGI(TAG, "Case10 ..."); StringTemplate t("? ? ?", { {0, 0, "p1", std::make_shared<oatpp::base::Countable>()}, {2, 2, "p2", std::make_shared<oatpp::base::Countable>()}, {4, 4, "p3", std::make_shared<oatpp::base::Countable>()} } ); auto result = t.format("(A)"); OATPP_ASSERT(result == "(A) (A) (A)"); OATPP_LOGI(TAG, "OK"); } } }}}}}
vincent-in-black-sesame/oat
test/oatpp/core/data/share/StringTemplateTest.cpp
C++
apache-2.0
3,995
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_core_data_share_StringTemplateTest_hpp #define oatpp_test_core_data_share_StringTemplateTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace share { class StringTemplateTest : public UnitTest{ public: StringTemplateTest():UnitTest("TEST[core::data::share::StringTemplateTest]"){} void onRun() override; }; }}}}} #endif /* oatpp_test_core_data_share_StringTemplateTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/core/data/share/StringTemplateTest.hpp
C++
apache-2.0
1,471
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "BufferStreamTest.hpp" #include "oatpp/core/data/stream/BufferStream.hpp" #include "oatpp/core/utils/ConversionUtils.hpp" #include "oatpp/core/utils/Binary.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace stream { void BufferStreamTest::onRun() { typedef oatpp::data::stream::BufferOutputStream BufferOutputStream; { BufferOutputStream stream; stream << "int=" << 1 << ", float=" << 1.1 << ", " << "bool=" << true << " or " << false; OATPP_LOGV(TAG, "str='%s'", stream.toString()->c_str()); stream.setCurrentPosition(0); stream << 101; OATPP_ASSERT(stream.toString() == oatpp::utils::conversion::int32ToStr(101)); stream.setCurrentPosition(0); stream << (v_float32)101.1; OATPP_ASSERT(stream.toString() == oatpp::utils::conversion::float32ToStr(101.1f)); stream.setCurrentPosition(0); stream << (v_float64)101.1; OATPP_ASSERT(stream.toString() == oatpp::utils::conversion::float64ToStr(101.1)); stream.setCurrentPosition(0); stream << true; OATPP_ASSERT(stream.toString() == "true"); stream.setCurrentPosition(0); stream << false; OATPP_ASSERT(stream.toString() == "false"); stream.setCurrentPosition(0); stream << oatpp::String("oat++"); OATPP_ASSERT(stream.toString() == "oat++"); stream.setCurrentPosition(0); stream << oatpp::Int8(8); OATPP_ASSERT(stream.toString() == oatpp::utils::conversion::int32ToStr(8)); stream.setCurrentPosition(0); stream << oatpp::Int16(16); OATPP_ASSERT(stream.toString() == oatpp::utils::conversion::int32ToStr(16)); stream.setCurrentPosition(0); stream << oatpp::Int32(32); OATPP_ASSERT(stream.toString() == oatpp::utils::conversion::int32ToStr(32)); stream.setCurrentPosition(0); stream << oatpp::Int64(64); OATPP_ASSERT(stream.toString() == oatpp::utils::conversion::int32ToStr(64)); stream.setCurrentPosition(0); stream << oatpp::Float32(0.32f); OATPP_ASSERT(stream.toString() == oatpp::utils::conversion::float32ToStr(0.32f)); stream.setCurrentPosition(0); stream << oatpp::Float64(0.64); OATPP_ASSERT(stream.toString() == oatpp::utils::conversion::float64ToStr(0.64)); stream.setCurrentPosition(0); stream << oatpp::Boolean(true); OATPP_ASSERT(stream.toString() == "true"); stream.setCurrentPosition(0); stream << oatpp::Boolean(false); OATPP_ASSERT(stream.toString() == "false"); } { BufferOutputStream stream; v_int32 fragmentsCount = 1024 * 10; for(v_int32 i = 0; i < fragmentsCount; i++) { stream.writeSimple("0123456789", 10); } auto wholeText = stream.toString(); OATPP_ASSERT(wholeText->size() == fragmentsCount * 10); v_int32 substringSize = 10; for(v_int32 i = 0; i < wholeText->size() - substringSize; i ++) { OATPP_ASSERT(oatpp::String(&wholeText->data()[i], substringSize) == stream.getSubstring(i, substringSize)); } } { oatpp::String sample = "0123456789"; oatpp::String text = ""; for(v_int32 i = 0; i < 1024; i++ ) { text = text + sample; } BufferOutputStream stream(0); for(v_int32 i = 0; i < 1024; i++ ) { stream << sample; OATPP_ASSERT(stream.getCapacity() >= stream.getCurrentPosition()); } OATPP_ASSERT(text == stream.toString()); OATPP_ASSERT(stream.getCapacity() == oatpp::utils::Binary::nextP2(1024 * (10))); } } }}}}}
vincent-in-black-sesame/oat
test/oatpp/core/data/stream/BufferStreamTest.cpp
C++
apache-2.0
4,471
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_core_data_stream_BufferStream_hpp #define oatpp_test_core_data_stream_BufferStream_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace data { namespace stream { class BufferStreamTest : public UnitTest{ public: BufferStreamTest():UnitTest("TEST[core::data::stream::BufferStreamTest]"){} void onRun() override; }; }}}}} #endif // oatpp_test_core_data_stream_BufferStream_hpp
vincent-in-black-sesame/oat
test/oatpp/core/data/stream/BufferStreamTest.hpp
C++
apache-2.0
1,450
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "CaretTest.hpp" #include "oatpp/core/parser/Caret.hpp" namespace oatpp { namespace test { namespace parser { namespace { typedef oatpp::parser::Caret Caret; } void CaretTest::onRun() { { Caret caret(" \t\n\r\f \t\n\r\f \t\n\r\fhello!\t\n\r\f"); OATPP_ASSERT(caret.skipBlankChars()); OATPP_ASSERT(caret.isAtChar('h')); OATPP_ASSERT(caret.isAtText("hello!")); OATPP_ASSERT(caret.isAtText("hello!", true)); OATPP_ASSERT(caret.skipBlankChars() == false); // false because no other char found OATPP_ASSERT(caret.canContinue() == false); OATPP_ASSERT(caret.getPosition() == caret.getDataSize()); } { Caret caret(" \t\n\r\f \t\n\r\f \t\n\r\fhello!\t\n\r\f"); OATPP_ASSERT(caret.findText("hello!")); OATPP_ASSERT(caret.isAtText("hello!")); OATPP_ASSERT(caret.isAtTextNCS("HELLO!")); OATPP_ASSERT(caret.isAtTextNCS("HELLO!", true)); OATPP_ASSERT(caret.skipBlankChars() == false); // false because no other char found OATPP_ASSERT(caret.canContinue() == false); OATPP_ASSERT(caret.getPosition() == caret.getDataSize()); } { Caret caret(" \t\n\r\f \t\n\r\f \t\n\r\fhello!\t\n\r\f"); OATPP_ASSERT(caret.findText("hello world!") == false); OATPP_ASSERT(caret.canContinue() == false); OATPP_ASSERT(caret.getPosition() == caret.getDataSize()); } { Caret caret("\r\n'let\\'s'\r\n'play'"); OATPP_ASSERT(caret.findRN()); OATPP_ASSERT(caret.skipRN()); auto label = caret.parseStringEnclosed('\'', '\'', '\\'); OATPP_ASSERT(label); OATPP_ASSERT(label.toString() == "let\\'s"); OATPP_ASSERT(caret.skipRN()); label = caret.parseStringEnclosed('\'', '\'', '\\'); OATPP_ASSERT(label); OATPP_ASSERT(label.toString() == "play"); OATPP_ASSERT(caret.canContinue() == false); OATPP_ASSERT(caret.getPosition() == caret.getDataSize()); } } }}}
vincent-in-black-sesame/oat
test/oatpp/core/parser/CaretTest.cpp
C++
apache-2.0
2,883
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_base_CaretTest_hpp #define oatpp_test_base_CaretTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace parser { class CaretTest : public UnitTest{ public: CaretTest():UnitTest("TEST[parser::CaretTest]"){} void onRun() override; }; }}} #endif //oatpp_test_base_CaretTest_hpp
vincent-in-black-sesame/oat
test/oatpp/core/parser/CaretTest.hpp
C++
apache-2.0
1,335
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>, * Matthias Haselmaier <mhaselmaier@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "PoolTemplateTest.hpp" #include <future> #include "oatpp/core/provider/Pool.hpp" #include "oatpp/core/async/Executor.hpp" namespace oatpp { namespace test { namespace core { namespace provider { namespace { struct Resource { }; class Provider : public oatpp::provider::Provider<Resource> { private: class ResourceInvalidator : public oatpp::provider::Invalidator<Resource> { public: void invalidate(const std::shared_ptr<Resource>& resource) override { (void) resource; } }; private: std::shared_ptr<ResourceInvalidator> m_invalidator; public: oatpp::provider::ResourceHandle<Resource> get() override { return oatpp::provider::ResourceHandle<Resource>(std::make_shared<Resource>(), m_invalidator); } async::CoroutineStarterForResult<const oatpp::provider::ResourceHandle<Resource> &> getAsync() override { class GetCoroutine : public oatpp::async::CoroutineWithResult<GetCoroutine, const oatpp::provider::ResourceHandle<Resource>&> { private: Provider* m_provider; public: GetCoroutine(Provider* provider) : m_provider(provider) {} Action act() override { return _return(oatpp::provider::ResourceHandle<Resource>(std::make_shared<Resource>(), m_provider->m_invalidator)); } }; return GetCoroutine::startForResult(this); } void stop() override { OATPP_LOGD("Provider", "stop()"); } }; struct AcquisitionProxy : public oatpp::provider::AcquisitionProxy<Resource, AcquisitionProxy> { AcquisitionProxy(const oatpp::provider::ResourceHandle<Resource>& resource, const std::shared_ptr<PoolInstance>& pool) : oatpp::provider::AcquisitionProxy<Resource, AcquisitionProxy>(resource, pool) {} }; struct Pool : public oatpp::provider::PoolTemplate<Resource, AcquisitionProxy> { Pool(const std::shared_ptr<Provider>& provider, v_int64 maxResources, v_int64 maxResourceTTL, const std::chrono::duration<v_int64, std::micro>& timeout) : oatpp::provider::PoolTemplate<Resource, AcquisitionProxy>(provider, maxResources, maxResourceTTL, timeout) {} static oatpp::provider::ResourceHandle<Resource> get(const std::shared_ptr<PoolTemplate>& _this) { return oatpp::provider::PoolTemplate<Resource, AcquisitionProxy>::get(_this); } static async::CoroutineStarterForResult<const oatpp::provider::ResourceHandle<Resource>&> getAsync(const std::shared_ptr<PoolTemplate>& _this) { return oatpp::provider::PoolTemplate<Resource, AcquisitionProxy>::getAsync(_this); } static std::shared_ptr<PoolTemplate> createShared(const std::shared_ptr<Provider>& provider, v_int64 maxResources, const std::chrono::duration<v_int64, std::micro>& maxResourceTTL, const std::chrono::duration<v_int64, std::micro>& timeout) { auto ptr = std::make_shared<Pool>(provider, maxResources, maxResourceTTL.count(), timeout); startCleanupTask(ptr); return ptr; } }; class ClientCoroutine : public oatpp::async::Coroutine<ClientCoroutine> { private: std::shared_ptr<oatpp::provider::PoolTemplate<Resource, AcquisitionProxy>> m_pool; std::promise<oatpp::provider::ResourceHandle<Resource>>* m_promise; public: ClientCoroutine(const std::shared_ptr<oatpp::provider::PoolTemplate<Resource, AcquisitionProxy>>& pool, std::promise<oatpp::provider::ResourceHandle<Resource>>* promise) : m_pool(pool) , m_promise(promise) {} Action act() override { return Pool::getAsync(m_pool).callbackTo(&ClientCoroutine::onGet); } Action onGet(const oatpp::provider::ResourceHandle<Resource>& resource) { m_promise->set_value(resource); return finish(); } }; } void PoolTemplateTest::onRun() { const auto provider = std::make_shared<Provider>(); const v_int64 maxResources = 1; { OATPP_LOGD(TAG, "Synchronously with timeout"); auto poolTemplate = Pool::createShared(provider, maxResources, std::chrono::seconds(10), std::chrono::milliseconds(500)); oatpp::provider::ResourceHandle<Resource> resource = Pool::get(poolTemplate); OATPP_ASSERT(resource != nullptr); OATPP_ASSERT(Pool::get(poolTemplate) == nullptr); poolTemplate->stop(); OATPP_ASSERT(Pool::get(poolTemplate) == nullptr); } { OATPP_LOGD(TAG, "Synchronously without timeout"); auto poolTemplate = Pool::createShared(provider, maxResources, std::chrono::seconds(10), std::chrono::milliseconds::zero()); oatpp::provider::ResourceHandle<Resource> resource = Pool::get(poolTemplate); OATPP_ASSERT(resource != nullptr); std::future<oatpp::provider::ResourceHandle<Resource>> futureResource = std::async(std::launch::async, [&poolTemplate]() { return Pool::get(poolTemplate); }); OATPP_ASSERT(futureResource.wait_for(std::chrono::seconds(1)) == std::future_status::timeout); poolTemplate->stop(); OATPP_ASSERT(Pool::get(poolTemplate) == nullptr); } { OATPP_LOGD(TAG, "Asynchronously with timeout"); oatpp::async::Executor executor(1, 1, 1); auto poolTemplate = Pool::createShared(provider, maxResources, std::chrono::seconds(10), std::chrono::milliseconds(500)); oatpp::provider::ResourceHandle<Resource> resourceHandle; { std::promise<oatpp::provider::ResourceHandle<Resource>> promise; auto future = promise.get_future(); executor.execute<ClientCoroutine>(poolTemplate, &promise); resourceHandle = future.get(); OATPP_ASSERT(resourceHandle != nullptr); OATPP_ASSERT(resourceHandle.object != nullptr) OATPP_ASSERT(resourceHandle.invalidator != nullptr) } { std::promise<oatpp::provider::ResourceHandle<Resource>> promise; auto future = promise.get_future(); executor.execute<ClientCoroutine>(poolTemplate, &promise); resourceHandle = future.get(); OATPP_ASSERT(resourceHandle == nullptr); OATPP_ASSERT(resourceHandle.object == nullptr) OATPP_ASSERT(resourceHandle.invalidator == nullptr) } poolTemplate->stop(); executor.stop(); executor.join(); } { OATPP_LOGD(TAG, "Asynchronously without timeout"); oatpp::async::Executor executor(1, 1, 1); auto poolTemplate = Pool::createShared(provider, maxResources, std::chrono::seconds(10), std::chrono::milliseconds::zero()); oatpp::provider::ResourceHandle<Resource> resource = Pool::get(poolTemplate); OATPP_ASSERT(resource != nullptr); std::promise<oatpp::provider::ResourceHandle<Resource>> promise; auto future = promise.get_future(); executor.execute<ClientCoroutine>(poolTemplate, &promise); OATPP_ASSERT(future.wait_for(std::chrono::seconds(1)) == std::future_status::timeout); poolTemplate->stop(); executor.stop(); executor.join(); } } }}}}
vincent-in-black-sesame/oat
test/oatpp/core/provider/PoolTemplateTest.cpp
C++
apache-2.0
7,899
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>, * Matthias Haselmaier <mhaselmaier@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_provider_PoolTemplateTest_hpp #define oatpp_test_provider_PoolTemplateTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace provider { class PoolTemplateTest : public UnitTest{ public: PoolTemplateTest():UnitTest("TEST[provider::PoolTemplateTest]"){} void onRun() override; }; }}}} #endif //oatpp_test_provider_PoolTemplateTest_hpp
vincent-in-black-sesame/oat
test/oatpp/core/provider/PoolTemplateTest.hpp
C++
apache-2.0
1,459
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "PoolTest.hpp" #include "oatpp/core/provider/Pool.hpp" #include "oatpp/core/async/Executor.hpp" #include <thread> namespace oatpp { namespace test { namespace core { namespace provider { namespace { class Resource { public: virtual ~Resource() = default; virtual v_int64 myId() = 0; }; class MyResource : public Resource { private: v_int64 m_id; public: MyResource(v_int64 number) : m_id(number) {} v_int64 myId() override { return m_id; } }; class Provider : public oatpp::provider::Provider<Resource> { private: class ResourceInvalidator : public oatpp::provider::Invalidator<Resource> { public: void invalidate(const std::shared_ptr<Resource>& resource) override { (void) resource; } }; private: std::shared_ptr<ResourceInvalidator> m_invalidator = std::make_shared<ResourceInvalidator>(); std::atomic<v_int64> m_id; public: oatpp::provider::ResourceHandle<Resource> get() override { return oatpp::provider::ResourceHandle<Resource>( std::make_shared<MyResource>(++m_id), m_invalidator ); } async::CoroutineStarterForResult<const oatpp::provider::ResourceHandle<Resource> &> getAsync() override { class GetCoroutine : public oatpp::async::CoroutineWithResult<GetCoroutine, const oatpp::provider::ResourceHandle<Resource>&> { private: Provider* m_provider; public: GetCoroutine(Provider* provider) : m_provider(provider) {} Action act() override { return _return(oatpp::provider::ResourceHandle<Resource>( std::make_shared<MyResource>(++ m_provider->m_id), m_provider->m_invalidator )); } }; return GetCoroutine::startForResult(this); } void stop() override { OATPP_LOGD("Provider", "stop()"); } v_int64 getIdCounter() { return m_id; } }; struct AcquisitionProxy : public oatpp::provider::AcquisitionProxy<Resource, AcquisitionProxy> { AcquisitionProxy(const oatpp::provider::ResourceHandle<Resource>& resource, const std::shared_ptr<PoolInstance>& pool) : oatpp::provider::AcquisitionProxy<Resource, AcquisitionProxy>(resource, pool) {} v_int64 myId() override { return _handle.object->myId(); } }; typedef oatpp::provider::Pool<oatpp::provider::Provider<Resource>, Resource, AcquisitionProxy> Pool; class ClientCoroutine : public oatpp::async::Coroutine<ClientCoroutine> { private: std::shared_ptr<Pool> m_pool; oatpp::provider::ResourceHandle<Resource> m_resource; bool m_invalidate; public: ClientCoroutine(const std::shared_ptr<Pool>& pool, bool invalidate) : m_pool(pool) , m_invalidate(invalidate) {} Action act() override { return m_pool->getAsync().callbackTo(&ClientCoroutine::onGet); } Action onGet(const oatpp::provider::ResourceHandle<Resource>& resource) { m_resource = resource; return waitFor(std::chrono::milliseconds(100)).next(yieldTo(&ClientCoroutine::onUse)); } Action onUse() { if(m_invalidate) { m_resource.invalidator->invalidate(m_resource.object); } return finish(); } }; void clientMethod(std::shared_ptr<Pool> pool, bool invalidate) { auto resource = pool->get(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); if(invalidate) { resource.invalidator->invalidate(resource.object); } } } void PoolTest::onRun() { oatpp::async::Executor executor(10, 1, 1); auto provider = std::make_shared<Provider>(); auto pool = Pool::createShared(provider, 10, std::chrono::seconds(2)); std::list<std::thread> threads; OATPP_LOGD(TAG, "Run 1"); for(v_int32 i = 0; i < 100; i ++ ) { threads.push_back(std::thread(clientMethod, pool, false)); executor.execute<ClientCoroutine>(pool, false); } std::this_thread::sleep_for(std::chrono::milliseconds (200)); OATPP_LOGD(TAG, "1) pool->getCounter() == %d", pool->getCounter()); OATPP_ASSERT(pool->getCounter() == 10); OATPP_LOGD(TAG, "Waiting..."); std::this_thread::sleep_for(std::chrono::seconds(10)); OATPP_LOGD(TAG, "Pool counter=%d", pool->getCounter()); OATPP_ASSERT(pool->getCounter() == 0); OATPP_LOGD(TAG, "Run 2"); for(v_int32 i = 0; i < 100; i ++ ) { threads.push_back(std::thread(clientMethod, pool, false)); executor.execute<ClientCoroutine>(pool, false); } std::this_thread::sleep_for(std::chrono::milliseconds (200)); OATPP_LOGD(TAG, "2) pool->getCounter() == %d", pool->getCounter()); OATPP_ASSERT(pool->getCounter() == 10); OATPP_LOGD(TAG, "Waiting..."); std::this_thread::sleep_for(std::chrono::seconds(10)); OATPP_LOGD(TAG, "Pool counter=%d", pool->getCounter()); OATPP_ASSERT(pool->getCounter() == 0); for(std::thread& thread : threads) { thread.join(); } executor.waitTasksFinished(); OATPP_LOGD(TAG, "counter=%d", provider->getIdCounter()); OATPP_ASSERT(provider->getIdCounter() == 20); pool->stop(); executor.stop(); executor.join(); /* wait pool cleanup task exit */ std::this_thread::sleep_for(std::chrono::milliseconds(200)); } }}}}
vincent-in-black-sesame/oat
test/oatpp/core/provider/PoolTest.cpp
C++
apache-2.0
6,074
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_provider_PoolTest_hpp #define oatpp_test_provider_PoolTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace core { namespace provider { class PoolTest : public UnitTest{ public: PoolTest():UnitTest("TEST[provider::PoolTest]"){} void onRun() override; }; }}}} #endif //oatpp_test_provider_PoolTest_hpp
vincent-in-black-sesame/oat
test/oatpp/core/provider/PoolTest.hpp
C++
apache-2.0
1,363
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "Base64Test.hpp" #include "oatpp/encoding/Base64.hpp" namespace oatpp { namespace test { namespace encoding { void Base64Test::onRun() { oatpp::String message = "oat++ web framework"; oatpp::String messageEncoded = "b2F0Kysgd2ViIGZyYW1ld29yaw=="; { oatpp::String encoded = oatpp::encoding::Base64::encode(message); OATPP_LOGV(TAG, "encoded='%s'", encoded->c_str()); OATPP_ASSERT(encoded == messageEncoded); oatpp::String decoded = oatpp::encoding::Base64::decode(encoded); OATPP_ASSERT(message == decoded); } { oatpp::String encoded = oatpp::encoding::Base64::encode(message, oatpp::encoding::Base64::ALPHABET_BASE64_URL_SAFE); OATPP_LOGV(TAG, "encoded='%s'", encoded->c_str()); oatpp::String decoded = oatpp::encoding::Base64::decode(encoded, oatpp::encoding::Base64::ALPHABET_BASE64_URL_SAFE_AUXILIARY_CHARS); OATPP_ASSERT(message == decoded); } } }}}
vincent-in-black-sesame/oat
test/oatpp/encoding/Base64Test.cpp
C++
apache-2.0
1,923
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_encoding_Base64Test_hpp #define oatpp_test_encoding_Base64Test_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace encoding { class Base64Test : public UnitTest{ public: Base64Test():UnitTest("TEST[encoding::Base64Test]"){} void onRun() override; }; }}} #endif /* oatpp_test_encoding_Base64Test_hpp */
vincent-in-black-sesame/oat
test/oatpp/encoding/Base64Test.hpp
C++
apache-2.0
1,362
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "UnicodeTest.hpp" #include "oatpp/encoding/Hex.hpp" #include "oatpp/encoding/Unicode.hpp" namespace oatpp { namespace test { namespace encoding { namespace { void writeBinaryInt(v_int32 value){ v_char8 buff [37]; buff[36] = '\0'; v_int32 index = 0; for(v_int32 i = 0; i < 36; i++){ if((i + 1) % 9 == 0){ buff[i] = ','; } else { v_int32 unit = 1 << index; if((unit & value) == 0){ buff[i] = '0'; } else { buff[i] = '1'; } index++; } } OATPP_LOGV("bin", "value='%s'", (const char*) &buff); } } // 38327 void UnicodeTest::onRun(){ v_char8 buff[128]; v_buff_size cnt; // 2 byte test for(v_int32 c = 128; c < 2048; c ++){ auto size = oatpp::encoding::Unicode::decodeUtf8Char(c, buff); OATPP_ASSERT(size == 2); auto code = oatpp::encoding::Unicode::encodeUtf8Char((const char*) buff, cnt); OATPP_ASSERT(cnt == 2); OATPP_ASSERT(code == c); } // 3 byte test for(v_int32 c = 2048; c < 65536; c ++){ auto size = oatpp::encoding::Unicode::decodeUtf8Char(c, buff); OATPP_ASSERT(size == 3); auto code = oatpp::encoding::Unicode::encodeUtf8Char((const char*) buff, cnt); OATPP_ASSERT(cnt == 3); OATPP_ASSERT(code == c); } // 4 byte test for(v_int32 c = 65536; c < 2097152; c ++){ auto size = oatpp::encoding::Unicode::decodeUtf8Char(c, buff); OATPP_ASSERT(size == 4); auto code = oatpp::encoding::Unicode::encodeUtf8Char((const char*) buff, cnt); OATPP_ASSERT(cnt == 4); OATPP_ASSERT(code == c); } // 5 byte test for(v_int32 c = 2097152; c < 67108864; c ++){ auto size = oatpp::encoding::Unicode::decodeUtf8Char(c, buff); OATPP_ASSERT(size == 5); auto code = oatpp::encoding::Unicode::encodeUtf8Char((const char*) buff, cnt); OATPP_ASSERT(cnt == 5); OATPP_ASSERT(code == c); } // 6 byte test for (v_int64 c = 67108864; c < 2147483647; c = c + 100) { auto size = oatpp::encoding::Unicode::decodeUtf8Char((v_int32) c, buff); OATPP_ASSERT(size == 6); auto code = oatpp::encoding::Unicode::encodeUtf8Char((const char*) buff, cnt); OATPP_ASSERT(cnt == 6); OATPP_ASSERT(code == c); } // */ const char* sequence = "𐐷"; auto code = oatpp::encoding::Unicode::encodeUtf8Char(sequence, cnt); v_int16 high; v_int16 low; oatpp::encoding::Unicode::codeToUtf16SurrogatePair(code, high, low); auto check = oatpp::encoding::Unicode::utf16SurrogatePairToCode(high, low); writeBinaryInt(code); writeBinaryInt(check); OATPP_ASSERT(code == check); for(v_int32 c = 0x010000; c <= 0x10FFFF; c++) { oatpp::encoding::Unicode::codeToUtf16SurrogatePair(code, high, low); check = oatpp::encoding::Unicode::utf16SurrogatePairToCode(high, low); OATPP_ASSERT(code == check); } } }}}
vincent-in-black-sesame/oat
test/oatpp/encoding/UnicodeTest.cpp
C++
apache-2.0
3,857
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_encoding_UnicodeTest_hpp #define oatpp_test_encoding_UnicodeTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace encoding { class UnicodeTest : public UnitTest{ public: UnicodeTest():UnitTest("TEST[encoding::UnicodeTest]"){} void onRun() override; }; }}} #endif /* oatpp_test_encoding_UnicodeTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/encoding/UnicodeTest.hpp
C++
apache-2.0
1,369
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "ConnectionPoolTest.hpp" #include "oatpp/network/ConnectionPool.hpp" #include "oatpp/core/async/Executor.hpp" namespace oatpp { namespace test { namespace network { namespace { typedef oatpp::provider::Pool< oatpp::network::ConnectionProvider, oatpp::data::stream::IOStream, oatpp::network::ConnectionAcquisitionProxy > ConnectionPool; class StubStream : public oatpp::data::stream::IOStream, public oatpp::base::Countable { public: v_io_size write(const void *buff, v_buff_size count, async::Action& actions) override { throw std::runtime_error("It's a stub!"); } v_io_size read(void *buff, v_buff_size count, async::Action& action) override { throw std::runtime_error("It's a stub!"); } void setOutputStreamIOMode(oatpp::data::stream::IOMode ioMode) override { throw std::runtime_error("It's a stub!"); } oatpp::data::stream::IOMode getOutputStreamIOMode() override { throw std::runtime_error("It's a stub!"); } oatpp::data::stream::Context& getOutputStreamContext() override { throw std::runtime_error("It's a stub!"); } void setInputStreamIOMode(oatpp::data::stream::IOMode ioMode) override { throw std::runtime_error("It's a stub!"); } oatpp::data::stream::IOMode getInputStreamIOMode() override { throw std::runtime_error("It's a stub!"); } oatpp::data::stream::Context& getInputStreamContext() override { throw std::runtime_error("It's a stub!"); } }; class StubStreamProvider : public oatpp::network::ConnectionProvider { private: class Invalidator : public oatpp::provider::Invalidator<oatpp::data::stream::IOStream> { public: void invalidate(const std::shared_ptr<oatpp::data::stream::IOStream>& connection) override { (void)connection; // DO Nothing. } }; private: std::shared_ptr<Invalidator> m_invalidator = std::make_shared<Invalidator>(); public: StubStreamProvider() : counter(0) {} std::atomic<v_int64> counter; oatpp::provider::ResourceHandle<oatpp::data::stream::IOStream> get() override { ++ counter; return oatpp::provider::ResourceHandle<oatpp::data::stream::IOStream>( std::make_shared<StubStream>(), m_invalidator ); } oatpp::async::CoroutineStarterForResult<const oatpp::provider::ResourceHandle<oatpp::data::stream::IOStream>&> getAsync() override { class ConnectionCoroutine : public oatpp::async::CoroutineWithResult<ConnectionCoroutine, const oatpp::provider::ResourceHandle<oatpp::data::stream::IOStream>&> { private: std::shared_ptr<Invalidator> m_invalidator; public: ConnectionCoroutine(const std::shared_ptr<Invalidator>& invalidator) : m_invalidator(invalidator) {} Action act() override { return _return(oatpp::provider::ResourceHandle<oatpp::data::stream::IOStream>( std::make_shared<StubStream>(), m_invalidator )); } }; ++ counter; return ConnectionCoroutine::startForResult(m_invalidator); } void stop() override { // DO NOTHING } }; class ClientCoroutine : public oatpp::async::Coroutine<ClientCoroutine> { private: std::shared_ptr<ConnectionPool> m_pool; oatpp::provider::ResourceHandle<oatpp::data::stream::IOStream> m_connection; v_int32 m_repeats; bool m_invalidate; public: ClientCoroutine(const std::shared_ptr<ConnectionPool>& pool, bool invalidate) : m_pool(pool) , m_repeats(0) , m_invalidate(invalidate) {} Action act() override { return m_pool->getAsync().callbackTo(&ClientCoroutine::onConnection); } Action onConnection(const oatpp::provider::ResourceHandle<oatpp::data::stream::IOStream>& connection) { m_connection = connection; return yieldTo(&ClientCoroutine::useConnection); } Action useConnection() { if(m_repeats < 1) { m_repeats ++; return waitFor(std::chrono::milliseconds(100)).next(yieldTo(&ClientCoroutine::useConnection)); } if(m_invalidate) { m_connection.invalidator->invalidate(m_connection.object); } return finish(); } }; void clientMethod(std::shared_ptr<ConnectionPool> pool, bool invalidate) { auto connection = pool->get(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); if(invalidate) { connection.invalidator->invalidate(connection.object); } } } void ConnectionPoolTest::onRun() { oatpp::async::Executor executor(1, 1, 1); auto connectionProvider = std::make_shared<StubStreamProvider>(); auto pool = ConnectionPool::createShared(connectionProvider, 10 /* maxConnections */, std::chrono::seconds(10) /* maxConnectionTTL */); std::list<std::thread> threads; for(v_int32 i = 0; i < 100; i ++ ) { threads.push_back(std::thread(clientMethod, pool, false)); executor.execute<ClientCoroutine>(pool, false); } for(std::thread& thread : threads) { thread.join(); } executor.waitTasksFinished(); OATPP_LOGD(TAG, "connections_counter=%d", connectionProvider->counter.load()); OATPP_ASSERT(connectionProvider->counter <= 10); pool->stop(); executor.stop(); executor.join(); /* wait pool cleanup task exit */ std::this_thread::sleep_for(std::chrono::milliseconds(200)); } }}}
vincent-in-black-sesame/oat
test/oatpp/network/ConnectionPoolTest.cpp
C++
apache-2.0
6,202
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_network_ConnectionPoolTest_hpp #define oatpp_test_network_ConnectionPoolTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace network { class ConnectionPoolTest : public UnitTest { public: ConnectionPoolTest():UnitTest("TEST[network::ConnectionPoolTest]"){} void onRun() override; }; }}} #endif // oatpp_test_network_ConnectionPoolTest_hpp
vincent-in-black-sesame/oat
test/oatpp/network/ConnectionPoolTest.hpp
C++
apache-2.0
1,402
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "UrlTest.hpp" #include "oatpp/network/Url.hpp" #include "oatpp-test/Checker.hpp" namespace oatpp { namespace test { namespace network { void UrlTest::onRun() { typedef oatpp::network::Url Url; { const char* urlText = "http://root@127.0.0.1:8000/path/to/resource/?q1=1&q2=2"; OATPP_LOGV(TAG, "urlText='%s'", urlText); auto url = Url::Parser::parseUrl(urlText); OATPP_ASSERT(url.scheme && url.scheme == "http"); OATPP_ASSERT(url.authority.userInfo && url.authority.userInfo == "root"); OATPP_ASSERT(url.authority.host && url.authority.host == "127.0.0.1"); OATPP_ASSERT(url.authority.port == 8000); OATPP_ASSERT(url.path && url.path == "/path/to/resource/"); OATPP_ASSERT(url.queryParams.getSize() == 2); OATPP_ASSERT(url.queryParams.get("q1") == "1"); OATPP_ASSERT(url.queryParams.get("q2") == "2"); } { const char* urlText = "ftp://root@oatpp.io:8000/path/to/resource?q1=1&q2=2"; OATPP_LOGV(TAG, "urlText='%s'", urlText); auto url = Url::Parser::parseUrl(urlText); OATPP_ASSERT(url.scheme && url.scheme == "ftp"); OATPP_ASSERT(url.authority.userInfo && url.authority.userInfo == "root"); OATPP_ASSERT(url.authority.host && url.authority.host == "oatpp.io"); OATPP_ASSERT(url.authority.port == 8000); OATPP_ASSERT(url.path && url.path == "/path/to/resource"); OATPP_ASSERT(url.queryParams.getSize() == 2); OATPP_ASSERT(url.queryParams.get("q1") == "1"); OATPP_ASSERT(url.queryParams.get("q2") == "2"); } { const char* urlText = "https://oatpp.io/?q1=1&q2=2"; OATPP_LOGV(TAG, "urlText='%s'", urlText); auto url = Url::Parser::parseUrl(urlText); OATPP_ASSERT(url.scheme && url.scheme == "https"); OATPP_ASSERT(url.authority.userInfo == nullptr); OATPP_ASSERT(url.authority.host && url.authority.host == "oatpp.io"); OATPP_ASSERT(url.authority.port == -1); OATPP_ASSERT(url.path && url.path == "/"); OATPP_ASSERT(url.queryParams.getSize() == 2); OATPP_ASSERT(url.queryParams.get("q1") == "1"); OATPP_ASSERT(url.queryParams.get("q2") == "2"); } { const char* urlText = "https://oatpp.io/"; OATPP_LOGV(TAG, "urlText='%s'", urlText); auto url = Url::Parser::parseUrl(urlText); OATPP_ASSERT(url.scheme && url.scheme == "https"); OATPP_ASSERT(url.authority.userInfo == nullptr); OATPP_ASSERT(url.authority.host && url.authority.host == "oatpp.io"); OATPP_ASSERT(url.authority.port == -1); OATPP_ASSERT(url.path && url.path == "/"); OATPP_ASSERT(url.queryParams.getSize() == 0); } { const char* urlText = "https://oatpp.io"; OATPP_LOGV(TAG, "urlText='%s'", urlText); auto url = Url::Parser::parseUrl(urlText); OATPP_ASSERT(url.scheme && url.scheme == "https"); OATPP_ASSERT(url.authority.userInfo == nullptr); OATPP_ASSERT(url.authority.host && url.authority.host == "oatpp.io"); OATPP_ASSERT(url.authority.port == -1); OATPP_ASSERT(url.path == nullptr); OATPP_ASSERT(url.queryParams.getSize() == 0); } { const char* urlText = "oatpp.io"; OATPP_LOGV(TAG, "urlText='%s'", urlText); auto url = Url::Parser::parseUrl(urlText); OATPP_ASSERT(url.scheme == nullptr); OATPP_ASSERT(url.authority.userInfo == nullptr); OATPP_ASSERT(url.authority.host && url.authority.host == "oatpp.io"); OATPP_ASSERT(url.authority.port == -1); OATPP_ASSERT(url.path == nullptr); OATPP_ASSERT(url.queryParams.getSize() == 0); } { const char* urlText = "?key1=value1&key2=value2&key3=value3"; OATPP_LOGV(TAG, "urlText='%s'", urlText); auto params = Url::Parser::parseQueryParams(urlText); OATPP_ASSERT(params.getSize() == 3); OATPP_ASSERT(params.get("key1") == "value1"); OATPP_ASSERT(params.get("key2") == "value2"); OATPP_ASSERT(params.get("key2") == "value2"); } { const char *urlText = "?key1=value1&key2&key3=value3"; OATPP_LOGV(TAG, "urlText='%s'", urlText); auto params = Url::Parser::parseQueryParams(urlText); OATPP_ASSERT(params.getSize() == 3); OATPP_ASSERT(params.get("key1") == "value1"); OATPP_ASSERT(params.get("key2") == ""); OATPP_ASSERT(params.get("key3") == "value3"); } { const char *urlText = "?key1=value1&key2&key3"; OATPP_LOGV(TAG, "urlText='%s'", urlText); auto params = Url::Parser::parseQueryParams(urlText); OATPP_ASSERT(params.getSize() == 3); OATPP_ASSERT(params.get("key1") == "value1"); OATPP_ASSERT(params.get("key2") == ""); OATPP_ASSERT(params.get("key3") == ""); } { const char *urlText = "label?key1=value1&key2=value2&key3=value3"; OATPP_LOGV(TAG, "urlText='%s'", urlText); auto params = Url::Parser::parseQueryParams(urlText); OATPP_ASSERT(params.getSize() == 3); OATPP_ASSERT(params.get("key1") == "value1"); OATPP_ASSERT(params.get("key2") == "value2"); OATPP_ASSERT(params.get("key2") == "value2"); } { const char* urlText = "label?key1=value1&key2&key3=value3"; OATPP_LOGV(TAG, "urlText='%s'", urlText); auto params = Url::Parser::parseQueryParams(urlText); OATPP_ASSERT(params.getSize() == 3); OATPP_ASSERT(params.get("key1") == "value1"); OATPP_ASSERT(params.get("key2") == ""); OATPP_ASSERT(params.get("key3") == "value3"); } { const char* urlText = "label?key1=value1&key2&key3"; OATPP_LOGV(TAG, "urlText='%s'", urlText); auto params = Url::Parser::parseQueryParams(urlText); OATPP_ASSERT(params.getSize() == 3); OATPP_ASSERT(params.get("key1") == "value1"); OATPP_ASSERT(params.get("key2") == ""); OATPP_ASSERT(params.get("key3") == ""); } } }}}
vincent-in-black-sesame/oat
test/oatpp/network/UrlTest.cpp
C++
apache-2.0
6,645
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_network_UrlTest_hpp #define oatpp_test_network_UrlTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace network { class UrlTest : public UnitTest { public: UrlTest():UnitTest("TEST[network::UrlTest]"){} void onRun() override; }; }}} #endif //oatpp_test_network_UrlTest_hpp
vincent-in-black-sesame/oat
test/oatpp/network/UrlTest.hpp
C++
apache-2.0
1,335
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "ConnectionMonitorTest.hpp" #include "oatpp/web/client/HttpRequestExecutor.hpp" #include "oatpp/web/server/AsyncHttpConnectionHandler.hpp" #include "oatpp/web/server/HttpConnectionHandler.hpp" #include "oatpp/web/server/HttpRouter.hpp" #include "oatpp/web/protocol/http/outgoing/StreamingBody.hpp" #include "oatpp/network/monitor/ConnectionMonitor.hpp" #include "oatpp/network/monitor/ConnectionMaxAgeChecker.hpp" #include "oatpp/network/Server.hpp" #include "oatpp/network/tcp/client/ConnectionProvider.hpp" #include "oatpp/network/tcp/server/ConnectionProvider.hpp" #include <thread> namespace oatpp { namespace test { namespace network { namespace monitor { namespace { class ReadCallback : public oatpp::data::stream::ReadCallback { public: v_io_size read(void *buffer, v_buff_size count, async::Action &action) override { OATPP_LOGI("TEST", "read(...)") std::this_thread::sleep_for(std::chrono::milliseconds(100)); char* data = (char*) buffer; data[0] = 'A'; return 1; } }; class StreamingHandler : public oatpp::web::server::HttpRequestHandler { public: std::shared_ptr<OutgoingResponse> handle(const std::shared_ptr<IncomingRequest>& request) override { auto body = std::make_shared<oatpp::web::protocol::http::outgoing::StreamingBody> (std::make_shared<ReadCallback>()); return OutgoingResponse::createShared(Status::CODE_200, body); } }; class AsyncStreamingHandler : public oatpp::web::server::HttpRequestHandler { public: oatpp::async::CoroutineStarterForResult<const std::shared_ptr<OutgoingResponse>&> handleAsync(const std::shared_ptr<IncomingRequest>& request) { class StreamCoroutine : public oatpp::async::CoroutineWithResult<StreamCoroutine, const std::shared_ptr<OutgoingResponse>&> { public: Action act() override { auto body = std::make_shared<oatpp::web::protocol::http::outgoing::StreamingBody> (std::make_shared<ReadCallback>()); return _return(OutgoingResponse::createShared(Status::CODE_200, body)); } }; return StreamCoroutine::startForResult(); } }; std::shared_ptr<oatpp::network::Server> runServer(const std::shared_ptr<oatpp::network::monitor::ConnectionMonitor>& monitor) { auto router = oatpp::web::server::HttpRouter::createShared(); router->route("GET", "/stream", std::make_shared<StreamingHandler>()); auto connectionHandler = oatpp::web::server::HttpConnectionHandler::createShared(router); auto server = std::make_shared<oatpp::network::Server>(monitor, connectionHandler); std::thread t([server, connectionHandler]{ server->run(); OATPP_LOGD("TEST", "server stopped"); connectionHandler->stop(); OATPP_LOGD("TEST", "connectionHandler stopped"); }); t.detach(); return server; } std::shared_ptr<oatpp::network::Server> runAsyncServer(const std::shared_ptr<oatpp::network::monitor::ConnectionMonitor>& monitor) { auto router = oatpp::web::server::HttpRouter::createShared(); router->route("GET", "/stream", std::make_shared<AsyncStreamingHandler>()); auto executor = std::make_shared<oatpp::async::Executor>(); auto connectionHandler = oatpp::web::server::AsyncHttpConnectionHandler::createShared(router, executor); auto server = std::make_shared<oatpp::network::Server>(monitor, connectionHandler); std::thread t([server, connectionHandler, executor]{ server->run(); OATPP_LOGD("TEST_ASYNC", "server stopped"); connectionHandler->stop(); OATPP_LOGD("TEST_ASYNC", "connectionHandler stopped"); executor->waitTasksFinished(); executor->stop(); executor->join(); OATPP_LOGD("TEST_ASYNC", "executor stopped"); }); t.detach(); return server; } void runClient() { auto connectionProvider = oatpp::network::tcp::client::ConnectionProvider::createShared( {"localhost", 8000}); oatpp::web::client::HttpRequestExecutor executor(connectionProvider); auto response = executor.execute("GET", "/stream", oatpp::web::protocol::http::Headers({}), nullptr, nullptr); OATPP_ASSERT(response->getStatusCode() == 200); auto data = response->readBodyToString(); OATPP_ASSERT(data) OATPP_LOGD("TEST", "data->size() == %d", data->size()) OATPP_ASSERT(data->size() < 110) // it should be less than 100. But we put 110 for redundancy } void runAsyncClient() { class ClientCoroutine : public oatpp::async::Coroutine<ClientCoroutine> { private: std::shared_ptr<oatpp::web::client::HttpRequestExecutor> m_executor; std::shared_ptr<oatpp::network::monitor::ConnectionMonitor> m_monitor; public: ClientCoroutine() { auto connectionProvider = oatpp::network::tcp::client::ConnectionProvider::createShared( {"localhost", 8000}); m_monitor = std::make_shared<oatpp::network::monitor::ConnectionMonitor>(connectionProvider); m_monitor->addMetricsChecker( std::make_shared<oatpp::network::monitor::ConnectionMaxAgeChecker>( std::chrono::seconds(5) ) ); m_executor = oatpp::web::client::HttpRequestExecutor::createShared(m_monitor); } Action act() override { return m_executor->executeAsync("GET", "/stream", oatpp::web::protocol::http::Headers({}), nullptr, nullptr) .callbackTo(&ClientCoroutine::onResponse); } Action onResponse(const std::shared_ptr<oatpp::web::protocol::http::incoming::Response>& response) { OATPP_ASSERT(response->getStatusCode() == 200); return response->readBodyToStringAsync().callbackTo(&ClientCoroutine::onBody); } Action onBody(const oatpp::String& data) { OATPP_ASSERT(data) OATPP_LOGD("TEST", "data->size() == %d", data->size()) OATPP_ASSERT(data->size() < 60) // it should be less than 50. But we put 60 for redundancy m_monitor->stop(); return finish(); } }; auto executor = std::make_shared<oatpp::async::Executor>(); executor->execute<ClientCoroutine>(); executor->waitTasksFinished(); OATPP_LOGD("TEST_ASYNC_CLIENT", "task finished") executor->stop(); OATPP_LOGD("TEST_ASYNC_CLIENT", "executor stopped") executor->join(); OATPP_LOGD("TEST_ASYNC_CLIENT", "done") } } void ConnectionMonitorTest::onRun() { auto connectionProvider = oatpp::network::tcp::server::ConnectionProvider::createShared( {"localhost", 8000}); auto monitor = std::make_shared<oatpp::network::monitor::ConnectionMonitor>(connectionProvider); monitor->addMetricsChecker( std::make_shared<oatpp::network::monitor::ConnectionMaxAgeChecker>( std::chrono::seconds(10) ) ); { OATPP_LOGD(TAG, "run simple API test") auto server = runServer(monitor); runClient(); server->stop(); std::this_thread::sleep_for(std::chrono::seconds(5)); } { OATPP_LOGD(TAG, "run Async API test") auto server = runAsyncServer(monitor); runClient(); server->stop(); std::this_thread::sleep_for(std::chrono::seconds(5)); } { OATPP_LOGD(TAG, "run Async Client test") auto server = runServer(monitor); runAsyncClient(); server->stop(); std::this_thread::sleep_for(std::chrono::seconds(5)); } monitor->stop(); } }}}}
vincent-in-black-sesame/oat
test/oatpp/network/monitor/ConnectionMonitorTest.cpp
C++
apache-2.0
8,153
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_network_monitor_ConnectionMonitorTest_hpp #define oatpp_test_network_monitor_ConnectionMonitorTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace network { namespace monitor { class ConnectionMonitorTest : public UnitTest { public: ConnectionMonitorTest():UnitTest("TEST[network::monitor::ConnectionMonitorTest]"){} void onRun() override; }; }}}} #endif // oatpp_test_network_monitor_ConnectionMonitorTest_hpp
vincent-in-black-sesame/oat
test/oatpp/network/monitor/ConnectionMonitorTest.hpp
C++
apache-2.0
1,474
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "InterfaceTest.hpp" #include "oatpp/network/virtual_/Interface.hpp" #include "oatpp/core/data/stream/BufferStream.hpp" #include <thread> #include <list> namespace oatpp { namespace test { namespace network { namespace virtual_ { namespace { typedef oatpp::network::virtual_::Interface Interface; typedef oatpp::network::virtual_::Socket Socket; typedef std::list<std::thread> ThreadList; class ClientTask : public oatpp::base::Countable { private: std::shared_ptr<Interface> m_interface; oatpp::String m_dataSample; public: ClientTask(const std::shared_ptr<Interface>& _interface, const oatpp::String& dataSample) : m_interface(_interface) , m_dataSample(dataSample) {} void run() { auto submission = m_interface->connect(); auto socket = submission->getSocket(); auto res = socket->writeExactSizeDataSimple(m_dataSample->data(), m_dataSample->size()); OATPP_ASSERT(res == m_dataSample->size()); v_char8 buffer[100]; oatpp::data::stream::BufferOutputStream stream; res = oatpp::data::stream::transfer(socket.get(), &stream, 2, buffer, 100); OATPP_ASSERT(res == 2); OATPP_ASSERT(stream.getCurrentPosition() == res); OATPP_ASSERT(stream.toString() == "OK"); //OATPP_LOGV("client", "finished - OK"); } }; class ServerTask : public oatpp::base::Countable { private: std::shared_ptr<Socket> m_socket; oatpp::String m_dataSample; public: ServerTask(const std::shared_ptr<Socket>& socket, const oatpp::String& dataSample) : m_socket(socket) , m_dataSample(dataSample) {} void run() { v_char8 buffer[100]; oatpp::data::stream::BufferOutputStream stream; auto res = oatpp::data::stream::transfer(m_socket.get(), &stream, m_dataSample->size(), buffer, 100); OATPP_ASSERT(res == m_dataSample->size()); OATPP_ASSERT(stream.getCurrentPosition() == res); OATPP_ASSERT(stream.toString() == m_dataSample); res = m_socket->writeExactSizeDataSimple("OK", 2); OATPP_ASSERT(res == 2); } }; class Server : public oatpp::base::Countable { private: std::shared_ptr<Interface> m_interface; oatpp::String m_dataSample; v_int32 m_numTasks; public: Server(const std::shared_ptr<Interface>& _interface, const oatpp::String& dataSample, v_int32 numTasks) : m_interface(_interface) , m_dataSample(dataSample) , m_numTasks(numTasks) {} void run() { ThreadList threadList; for(v_int32 i = 0; i < m_numTasks; i++) { auto socket = m_interface->accept(); threadList.push_back(std::thread(&ServerTask::run, ServerTask(socket, m_dataSample))); } for(auto& thread : threadList) { thread.join(); } } }; } void InterfaceTest::onRun() { oatpp::String dataSample = "1234567890-=][poiuytrewqasdfghjkl;'/.,mnbvcxzzxcvbnm,./';lkjhgfdsaqwertyuiop][=-0987654321"; auto _interface = Interface::obtainShared("virtualhost"); auto bindLock = _interface->bind(); v_int32 numTasks = 100; ThreadList threadList; std::thread server(&Server::run, Server(_interface, dataSample, numTasks)); for(v_int32 i = 0; i < numTasks; i++) { threadList.push_back(std::thread(&ClientTask::run, ClientTask(_interface, dataSample))); } for(auto& thread : threadList) { thread.join(); } server.join(); } }}}}
vincent-in-black-sesame/oat
test/oatpp/network/virtual_/InterfaceTest.cpp
C++
apache-2.0
4,590
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_network_virtual__InterfaceTest_hpp #define oatpp_test_network_virtual__InterfaceTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace network { namespace virtual_ { class InterfaceTest : public UnitTest { public: InterfaceTest():UnitTest("TEST[network::virtual_::InterfaceTest]"){} void onRun() override; }; }}}} #endif /* oatpp_test_network_virtual__InterfaceTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/network/virtual_/InterfaceTest.hpp
C++
apache-2.0
1,435
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "PipeTest.hpp" #include "oatpp/network/virtual_/Pipe.hpp" #include "oatpp/core/data/stream/BufferStream.hpp" #include "oatpp-test/Checker.hpp" #include <iostream> #include <thread> namespace oatpp { namespace test { namespace network { namespace virtual_ { namespace { typedef oatpp::network::virtual_::Pipe Pipe; const char* DATA_CHUNK = "<0123456789/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ>"; const v_buff_size CHUNK_SIZE = std::strlen(DATA_CHUNK); class WriterTask : public oatpp::base::Countable { private: std::shared_ptr<Pipe> m_pipe; v_int64 m_chunksToTransfer; v_buff_size m_position = 0; v_buff_size m_transferedBytes = 0; public: WriterTask(const std::shared_ptr<Pipe>& pipe, v_int64 chunksToTransfer) : m_pipe(pipe) , m_chunksToTransfer(chunksToTransfer) {} void run() { while (m_transferedBytes < CHUNK_SIZE * m_chunksToTransfer) { auto res = m_pipe->getWriter()->writeSimple(&DATA_CHUNK[m_position], CHUNK_SIZE - m_position); if(res > 0) { m_transferedBytes += res; m_position += res; if(m_position == CHUNK_SIZE) { m_position = 0; } } } OATPP_LOGV("WriterTask", "sent %d bytes", m_transferedBytes); } }; class ReaderTask : public oatpp::base::Countable { private: std::shared_ptr<oatpp::data::stream::BufferOutputStream> m_buffer; std::shared_ptr<Pipe> m_pipe; v_int64 m_chunksToTransfer; public: ReaderTask(const std::shared_ptr<oatpp::data::stream::BufferOutputStream> &buffer, const std::shared_ptr<Pipe>& pipe, v_int64 chunksToTransfer) : m_buffer(buffer) , m_pipe(pipe) , m_chunksToTransfer(chunksToTransfer) {} void run() { v_char8 readBuffer[256]; while (m_buffer->getCurrentPosition() < CHUNK_SIZE * m_chunksToTransfer) { auto res = m_pipe->getReader()->readSimple(readBuffer, 256); if(res > 0) { m_buffer->writeSimple(readBuffer, res); } } OATPP_LOGV("ReaderTask", "sent %d bytes", m_buffer->getCurrentPosition()); } }; void runTransfer(const std::shared_ptr<Pipe>& pipe, v_int64 chunksToTransfer, bool writeNonBlock, bool readerNonBlock) { OATPP_LOGV("transfer", "writer-nb: %d, reader-nb: %d", writeNonBlock, readerNonBlock); auto buffer = std::make_shared<oatpp::data::stream::BufferOutputStream>(); { oatpp::test::PerformanceChecker timer("timer"); std::thread writerThread(&WriterTask::run, WriterTask(pipe, chunksToTransfer)); std::thread readerThread(&ReaderTask::run, ReaderTask(buffer, pipe, chunksToTransfer)); writerThread.join(); readerThread.join(); } OATPP_ASSERT(buffer->getCurrentPosition() == chunksToTransfer * CHUNK_SIZE); auto ruleBuffer = std::make_shared<oatpp::data::stream::BufferOutputStream>(); for(v_int32 i = 0; i < chunksToTransfer; i ++) { ruleBuffer->writeSimple(DATA_CHUNK, CHUNK_SIZE); } auto str1 = buffer->toString(); auto str2 = buffer->toString(); OATPP_ASSERT(str1 == str2); } } void PipeTest::onRun() { auto pipe = Pipe::createShared(); v_int64 chunkCount = oatpp::data::buffer::IOBuffer::BUFFER_SIZE * 10 / CHUNK_SIZE; runTransfer(pipe, chunkCount, false, false); runTransfer(pipe, chunkCount, true, false); runTransfer(pipe, chunkCount, false, true); runTransfer(pipe, chunkCount, true, true); } }}}}
vincent-in-black-sesame/oat
test/oatpp/network/virtual_/PipeTest.cpp
C++
apache-2.0
4,602
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_network_virtual__PipeTest_hpp #define oatpp_test_network_virtual__PipeTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace network { namespace virtual_ { class PipeTest : public UnitTest { public: PipeTest():UnitTest("TEST[network::virtual_::PipeTest]"){} void onRun() override; }; }}}} #endif /* oatpp_test_network_virtual__PipeTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/network/virtual_/PipeTest.hpp
C++
apache-2.0
1,405
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "DTOMapperPerfTest.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/parser/json/mapping/Serializer.hpp" #include "oatpp/parser/json/mapping/Deserializer.hpp" #include "oatpp/core/data/stream/BufferStream.hpp" #include "oatpp/core/macro/basic.hpp" #include "oatpp/core/macro/codegen.hpp" #include "oatpp-test/Checker.hpp" namespace oatpp { namespace test { namespace parser { namespace json { namespace mapping { namespace { typedef oatpp::parser::json::mapping::Serializer Serializer; typedef oatpp::parser::json::mapping::Deserializer Deserializer; #include OATPP_CODEGEN_BEGIN(DTO) class Test1 : public oatpp::DTO { DTO_INIT(Test1, DTO) DTO_FIELD(String, field_string); DTO_FIELD(Int32, field_int32); DTO_FIELD(List<Int32>, field_list); static Wrapper createTestInstance(){ auto result = Test1::createShared(); result->field_string = "String Field"; result->field_int32 = 5; result->field_list = List<Int32>::createShared(); result->field_list->push_back(1); result->field_list->push_back(2); result->field_list->push_back(3); return result; } }; #include OATPP_CODEGEN_END(DTO) } void DTOMapperPerfTest::onRun() { v_int32 numIterations = 1000000; auto serializer2 = std::make_shared<oatpp::parser::json::mapping::Serializer>(); auto mapper = oatpp::parser::json::mapping::ObjectMapper::createShared(); auto test1 = Test1::createTestInstance(); auto test1_Text = mapper->writeToString(test1); OATPP_LOGV(TAG, "json='%s'", test1_Text->c_str()); { PerformanceChecker checker("Serializer"); for(v_int32 i = 0; i < numIterations; i ++) { mapper->writeToString(test1); } } { PerformanceChecker checker("Deserializer"); oatpp::parser::Caret caret(test1_Text); for(v_int32 i = 0; i < numIterations; i ++) { caret.setPosition(0); mapper->readFromCaret<oatpp::Object<Test1>>(caret); } } } }}}}}
vincent-in-black-sesame/oat
test/oatpp/parser/json/mapping/DTOMapperPerfTest.cpp
C++
apache-2.0
3,018
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_parser_json_mapping_DTOMapperPerfTest_hpp #define oatpp_test_parser_json_mapping_DTOMapperPerfTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace parser { namespace json { namespace mapping { class DTOMapperPerfTest : public UnitTest{ public: DTOMapperPerfTest():UnitTest("TEST[parser::json::mapping::DTOMapperPerfTest]"){} void onRun() override; }; }}}}} #endif /* oatpp_test_parser_json_mapping_DTOMapperPerfTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/parser/json/mapping/DTOMapperPerfTest.hpp
C++
apache-2.0
1,493
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #include "DTOMapperTest.hpp" #include "oatpp/parser/json/mapping/ObjectMapper.hpp" #include "oatpp/core/data/mapping/type/Object.hpp" #include "oatpp/core/data/mapping/type/List.hpp" #include "oatpp/core/data/mapping/type/Primitive.hpp" #include "oatpp/core/utils/ConversionUtils.hpp" #include "oatpp/core/macro/codegen.hpp" namespace oatpp { namespace test { namespace parser { namespace json { namespace mapping { namespace { #include OATPP_CODEGEN_BEGIN(DTO) class TestChild : public oatpp::DTO { DTO_INIT(TestChild, DTO) DTO_FIELD(String, name) = "Name"; DTO_FIELD(String, secondName) = "Second Name"; public: TestChild() = default; TestChild(const char* pName, const char* pSecondName) : name(pName) , secondName(pSecondName) {} }; class Test : public oatpp::DTO { DTO_INIT(Test, DTO) DTO_FIELD(String, field_string, "string-field-name-qualifier"); DTO_FIELD(Int32, field_int32, "int32-field-name-qualifier"); DTO_FIELD(Int64, field_int64); DTO_FIELD(Float32, field_float32); DTO_FIELD(Float64, field_float64); DTO_FIELD(Boolean, field_boolean); DTO_FIELD(List<String>, field_list_string) = {}; DTO_FIELD(List<Int32>, field_list_int32) = {}; DTO_FIELD(List<Int64>, field_list_int64) = {}; DTO_FIELD(List<Float32>, field_list_float32) = {}; DTO_FIELD(List<Float64>, field_list_float64) = {}; DTO_FIELD(List<Boolean>, field_list_boolean) = {}; DTO_FIELD(List<Object<TestChild>>, field_list_object) = {}; DTO_FIELD(List<List<Object<TestChild>>>, field_list_list_object) = {}; DTO_FIELD(Vector<String>, field_vector); DTO_FIELD(Fields<String>, field_fields); DTO_FIELD(UnorderedFields<String>, field_unordered_fields); DTO_FIELD(Object<Test>, obj1); DTO_FIELD(Object<TestChild>, child1); }; class TestAny : public oatpp::DTO { DTO_INIT(TestAny, DTO) DTO_FIELD(List<Any>, anyList) = List<Any>::createShared(); }; class TestAnyNested : public oatpp::DTO { DTO_INIT(TestAnyNested, DTO) DTO_FIELD(String, f1) = "Field_1"; DTO_FIELD(String, f2) = "Field_2"; }; #include OATPP_CODEGEN_END(DTO) } void DTOMapperTest::onRun(){ auto mapper = oatpp::parser::json::mapping::ObjectMapper::createShared(); mapper->getSerializer()->getConfig()->useBeautifier = true; auto test1 = Test::createShared(); test1->field_string = "string value"; test1->field_int32 = 32; test1->field_int64 = 64; test1->field_float32 = 0.32f; test1->field_float64 = 0.64; test1->field_boolean = true; test1->obj1 = Test::createShared(); test1->obj1->field_string = "inner string"; test1->obj1->field_list_string->push_back("inner str_item_1"); test1->obj1->field_list_string->push_back("inner str_item_2"); test1->obj1->field_list_string->push_back("inner str_item_3"); test1->child1 = TestChild::createShared(); test1->child1->name = "child1_name"; test1->child1->secondName = "child1_second_name"; test1->field_list_string->push_back("str_item_1"); test1->field_list_string->push_back("str_item_2"); test1->field_list_string->push_back("str_item_3"); test1->field_list_int32->push_back(321); test1->field_list_int32->push_back(322); test1->field_list_int32->push_back(323); test1->field_list_int64->push_back(641); test1->field_list_int64->push_back(642); test1->field_list_int64->push_back(643); test1->field_list_float32->push_back(0.321f); test1->field_list_float32->push_back(0.322f); test1->field_list_float32->push_back(0.323f); test1->field_list_float64->push_back(0.641); test1->field_list_float64->push_back(0.642); test1->field_list_float64->push_back(0.643); test1->field_list_boolean->push_back(true); test1->field_list_boolean->push_back(false); test1->field_list_boolean->push_back(true); test1->field_list_object->push_back(TestChild::createShared("child", "1")); test1->field_list_object->push_back(TestChild::createShared("child", "2")); test1->field_list_object->push_back(TestChild::createShared("child", "3")); auto l1 = oatpp::List<oatpp::Object<TestChild>>::createShared(); auto l2 = oatpp::List<oatpp::Object<TestChild>>::createShared(); auto l3 = oatpp::List<oatpp::Object<TestChild>>::createShared(); l1->push_back(TestChild::createShared("list_1", "item_1")); l1->push_back(TestChild::createShared("list_1", "item_2")); l1->push_back(TestChild::createShared("list_1", "item_3")); l2->push_back(TestChild::createShared("list_2", "item_1")); l2->push_back(TestChild::createShared("list_2", "item_2")); l2->push_back(TestChild::createShared("list_2", "item_3")); l3->push_back(TestChild::createShared("list_3", "item_1")); l3->push_back(TestChild::createShared("list_3", "item_2")); l3->push_back(TestChild::createShared("list_3", "item_3")); test1->field_list_list_object->push_back(l1); test1->field_list_list_object->push_back(l2); test1->field_list_list_object->push_back(l3); test1->field_vector = {"vector_item1", "vector_item2", "vector_item3"}; test1->field_fields = { {"key0", "pair_item0"}, {"key1", "pair_item1"}, {"key2", "pair_item2"}, {"key3", "pair_item3"}, {"key4", "pair_item4"}, {"key5", "pair_item5"}, {"key6", "pair_item6"}, {"key7", "pair_item7"}, {"key8", "pair_item8"}, {"key9", "pair_item9"}, {"key10", "pair_item10"}, {"key11", "pair_item11"} }; test1->field_unordered_fields = { {"key0", "map_item0"}, {"key1", "map_item1"}, {"key2", "map_item2"}, {"key3", "map_item3"}, {"key4", "map_item4"}, {"key5", "map_item5"}, {"key6", "map_item6"}, {"key7", "map_item7"}, {"key8", "map_item8"}, {"key9", "map_item9"}, {"key10", "map_item10"}, {"key11", "map_item11"} }; auto result = mapper->writeToString(test1); OATPP_LOGV(TAG, "json='%s'", result->c_str()); OATPP_LOGV(TAG, "..."); OATPP_LOGV(TAG, "..."); OATPP_LOGV(TAG, "..."); oatpp::parser::Caret caret(result); auto obj = mapper->readFromCaret<oatpp::Object<Test>>(caret); OATPP_ASSERT(obj->field_string); OATPP_ASSERT(obj->field_string == test1->field_string); OATPP_ASSERT(obj->field_int32); OATPP_ASSERT(obj->field_int32 == test1->field_int32); OATPP_ASSERT(obj->field_int64); OATPP_ASSERT(obj->field_int64 == test1->field_int64); OATPP_ASSERT(obj->field_float32); OATPP_ASSERT(obj->field_float32 == test1->field_float32); OATPP_ASSERT(obj->field_float64); OATPP_ASSERT(obj->field_float64 == test1->field_float64); OATPP_ASSERT(obj->field_boolean); OATPP_ASSERT(obj->field_boolean == test1->field_boolean); { auto c = obj->field_vector; OATPP_ASSERT(c[0] == "vector_item1"); OATPP_ASSERT(c[1] == "vector_item2"); OATPP_ASSERT(c[2] == "vector_item3"); } { auto c = obj->field_fields; v_int32 i = 0; for(auto& pair : *c) { OATPP_ASSERT(pair.first == "key" + oatpp::utils::conversion::int32ToStr(i)); OATPP_ASSERT(pair.second == "pair_item" + oatpp::utils::conversion::int32ToStr(i)); i++; } } { auto c = obj->field_unordered_fields; OATPP_ASSERT(c["key1"] == "map_item1"); OATPP_ASSERT(c["key2"] == "map_item2"); OATPP_ASSERT(c["key3"] == "map_item3"); } result = mapper->writeToString(obj); OATPP_LOGV(TAG, "json='%s'", result->c_str()); { auto obj = TestAny::createShared(); obj->anyList = { oatpp::String("Hello Any!!!"), oatpp::Int32(32), oatpp::Int64(64), oatpp::Float64(0.64), oatpp::Float64(0.64), TestAnyNested::createShared() }; auto map = oatpp::Fields<Any>::createShared(); map["bool-field"] = oatpp::Boolean(false); map["vector"] = oatpp::Vector<oatpp::String>({"vector_v1", "vector_v2", "vector_v3"}); map["unordered_map"] = oatpp::UnorderedFields<oatpp::String>({{"key1", "value1"}, {"key2", "value2"}}); obj->anyList->push_back(map); auto json = mapper->writeToString(obj); OATPP_LOGV(TAG, "any json='%s'", json->c_str()); auto deserializedAny = mapper->readFromString<oatpp::Fields<oatpp::Any>>(json); auto json2 = mapper->writeToString(deserializedAny); OATPP_LOGV(TAG, "any json='%s'", json2->c_str()); } } #include OATPP_CODEGEN_END(DTO) }}}}}
vincent-in-black-sesame/oat
test/oatpp/parser/json/mapping/DTOMapperTest.cpp
C++
apache-2.0
9,281
/*************************************************************************** * * Project _____ __ ____ _ _ * ( _ ) /__\ (_ _)_| |_ _| |_ * )(_)( /(__)\ )( (_ _)(_ _) * (_____)(__)(__)(__) |_| |_| * * * Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************/ #ifndef oatpp_test_parser_json_mapping_DTOMapperTest_hpp #define oatpp_test_parser_json_mapping_DTOMapperTest_hpp #include "oatpp-test/UnitTest.hpp" namespace oatpp { namespace test { namespace parser { namespace json { namespace mapping { class DTOMapperTest : public UnitTest{ public: DTOMapperTest():UnitTest("TEST[parser::json::mapping::DTOMapperTest]"){} void onRun() override; }; }}}}} #endif /* oatpp_test_parser_json_mapping_DTOMapperTest_hpp */
vincent-in-black-sesame/oat
test/oatpp/parser/json/mapping/DTOMapperTest.hpp
C++
apache-2.0
1,469