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 "ConnectionMonitor.hpp"
#include <chrono>
#include <thread>
namespace oatpp { namespace network { namespace monitor {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ConnectionMonitor::ConnectionInvalidator
void ConnectionMonitor::ConnectionInvalidator::invalidate(const std::shared_ptr<data::stream::IOStream> &connection) {
auto proxy = std::static_pointer_cast<ConnectionProxy>(connection);
proxy->invalidate();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ConnectionMonitor::ConnectionProxy
ConnectionMonitor::ConnectionProxy::ConnectionProxy(const std::shared_ptr<Monitor>& monitor,
const provider::ResourceHandle<data::stream::IOStream>& connectionHandle)
: m_monitor(monitor)
, m_connectionHandle(connectionHandle)
{
m_stats.timestampCreated = base::Environment::getMicroTickCount();
}
ConnectionMonitor::ConnectionProxy::~ConnectionProxy() {
m_monitor->removeConnection((v_uint64) this);
std::lock_guard<std::mutex> lock(m_statsMutex);
m_monitor->freeConnectionStats(m_stats);
if(m_stats.metricsData.size() > 0) {
for(auto& pair : m_stats.metricsData) {
OATPP_LOGE("[oatpp::network::ConnectionMonitor::ConnectionProxy::~ConnectionProxy()]",
"Error. Memory leak. Metric data was not deleted: Metric name - '%s'", pair.first->c_str());
}
}
}
v_io_size ConnectionMonitor::ConnectionProxy::read(void *buffer, v_buff_size count, async::Action& action) {
auto res = m_connectionHandle.object->read(buffer, count, action);
std::lock_guard<std::mutex> lock(m_statsMutex);
m_monitor->onConnectionRead(m_stats, res);
return res;
}
v_io_size ConnectionMonitor::ConnectionProxy::write(const void *data, v_buff_size count, async::Action& action) {
auto res = m_connectionHandle.object->write(data, count, action);
std::lock_guard<std::mutex> lock(m_statsMutex);
m_monitor->onConnectionWrite(m_stats, res);
return res;
}
void ConnectionMonitor::ConnectionProxy::setInputStreamIOMode(data::stream::IOMode ioMode) {
m_connectionHandle.object->setInputStreamIOMode(ioMode);
}
data::stream::IOMode ConnectionMonitor::ConnectionProxy::getInputStreamIOMode() {
return m_connectionHandle.object->getInputStreamIOMode();
}
data::stream::Context& ConnectionMonitor::ConnectionProxy::getInputStreamContext() {
return m_connectionHandle.object->getInputStreamContext();
}
void ConnectionMonitor::ConnectionProxy::setOutputStreamIOMode(data::stream::IOMode ioMode) {
m_connectionHandle.object->setOutputStreamIOMode(ioMode);
}
data::stream::IOMode ConnectionMonitor::ConnectionProxy::getOutputStreamIOMode() {
return m_connectionHandle.object->getOutputStreamIOMode();
}
data::stream::Context& ConnectionMonitor::ConnectionProxy::getOutputStreamContext() {
return m_connectionHandle.object->getOutputStreamContext();
}
void ConnectionMonitor::ConnectionProxy::invalidate() {
m_connectionHandle.invalidator->invalidate(m_connectionHandle.object);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Monitor
void ConnectionMonitor::Monitor::monitorTask(std::shared_ptr<Monitor> monitor) {
while(monitor->m_running) {
{
std::lock_guard<std::mutex> lock(monitor->m_connectionsMutex);
auto currMicroTime = oatpp::base::Environment::getMicroTickCount();
for(auto& caddr : monitor->m_connections) {
auto connection = (ConnectionProxy*) caddr;
std::lock_guard<std::mutex> dataLock(connection->m_statsMutex);
std::lock_guard<std::mutex> analysersLock(monitor->m_checkMutex);
for(auto& a : monitor->m_metricsCheckers) {
bool res = a->check(connection->m_stats, currMicroTime);
if(!res) {
connection->invalidate();
break;
}
}
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
{
std::lock_guard<std::mutex>(monitor->m_runMutex);
monitor->m_stopped = true;
}
monitor->m_runCondition.notify_all();
}
void* ConnectionMonitor::Monitor::createOrGetMetricData(ConnectionStats& stats, const std::shared_ptr<StatCollector>& collector) {
void* data;
auto it = stats.metricsData.find(collector->metricName());
if(it == stats.metricsData.end()) {
data = collector->createMetricData();
stats.metricsData.insert({collector->metricName(), data});
} else {
data = it->second;
}
return data;
}
std::shared_ptr<ConnectionMonitor::Monitor> ConnectionMonitor::Monitor::createShared() {
auto monitor = std::make_shared<Monitor>();
std::thread t([monitor](){
ConnectionMonitor::Monitor::monitorTask(monitor);
});
t.detach();
return monitor;
}
void ConnectionMonitor::Monitor::addConnection(ConnectionProxy* connection) {
std::lock_guard<std::mutex> lock(m_connectionsMutex);
m_connections.insert((v_uint64) connection);
}
void ConnectionMonitor::Monitor::freeConnectionStats(ConnectionStats& stats) {
std::lock_guard<std::mutex> lock(m_checkMutex);
for(auto& metric : stats.metricsData) {
auto it = m_statCollectors.find(metric.first);
if(it != m_statCollectors.end()) {
it->second->deleteMetricData(metric.second);
} else {
OATPP_LOGE("[oatpp::network::ConnectionMonitor::Monitor::freeConnectionStats]",
"Error. Can't free Metric data. Unknown Metric: name - '%s'", it->first->c_str());
}
}
}
void ConnectionMonitor::Monitor::removeConnection(v_uint64 id) {
std::lock_guard<std::mutex> lock(m_connectionsMutex);
m_connections.erase(id);
}
void ConnectionMonitor::Monitor::addStatCollector(const std::shared_ptr<StatCollector>& collector) {
std::lock_guard<std::mutex> lock(m_checkMutex);
m_statCollectors.insert({collector->metricName(), collector});
}
void ConnectionMonitor::Monitor::removeStatCollector(const oatpp::String& metricName) {
std::lock_guard<std::mutex> lock(m_checkMutex);
m_statCollectors.erase(metricName);
}
void ConnectionMonitor::Monitor::addMetricsChecker(const std::shared_ptr<MetricsChecker>& checker) {
std::lock_guard<std::mutex> lock(m_checkMutex);
m_metricsCheckers.push_back(checker);
auto metrics = checker->getMetricsList();
for(auto& m : metrics) {
auto it = m_statCollectors.find(m);
if(it == m_statCollectors.end()) {
m_statCollectors.insert({m, checker->createStatCollector(m)});
}
}
}
void ConnectionMonitor::Monitor::onConnectionRead(ConnectionStats& stats, v_io_size readResult) {
v_int64 currTimestamp = base::Environment::getMicroTickCount();
if(readResult > 0) {
stats.totalRead += readResult;
stats.lastReadSize = readResult;
stats.timestampLastRead = currTimestamp;
}
{
std::lock_guard<std::mutex> lock(m_checkMutex);
for(auto& pair : m_statCollectors) {
pair.second->onRead(createOrGetMetricData(stats, pair.second), readResult, currTimestamp);
}
}
}
void ConnectionMonitor::Monitor::onConnectionWrite(ConnectionStats& stats, v_io_size writeResult) {
v_int64 currTimestamp = base::Environment::getMicroTickCount();
if(writeResult > 0) {
stats.totalWrite += writeResult;
stats.lastWriteSize = writeResult;
stats.timestampLastWrite = currTimestamp;
}
{
std::lock_guard<std::mutex> lock(m_checkMutex);
for(auto& pair : m_statCollectors) {
pair.second->onWrite(createOrGetMetricData(stats, pair.second), writeResult, currTimestamp);
}
}
}
void ConnectionMonitor::Monitor::stop() {
m_running = false;
std::unique_lock<std::mutex> runLock(m_runMutex);
while(!m_stopped) {
m_runCondition.wait(runLock);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ConnectionMonitor
ConnectionMonitor::ConnectionMonitor(const std::shared_ptr<ConnectionProvider>& connectionProvider)
: m_invalidator(std::make_shared<ConnectionInvalidator>())
, m_monitor(Monitor::createShared())
, m_connectionProvider(connectionProvider)
{
}
provider::ResourceHandle<data::stream::IOStream> ConnectionMonitor::get() {
auto connection = m_connectionProvider->get();
if(!connection) {
return nullptr;
}
auto proxy = std::make_shared<ConnectionProxy>(m_monitor, connection);
m_monitor->addConnection(proxy.get());
return provider::ResourceHandle<data::stream::IOStream>(proxy, m_invalidator);
}
async::CoroutineStarterForResult<const provider::ResourceHandle<data::stream::IOStream>&>
ConnectionMonitor::getAsync() {
class GetConnectionCoroutine : public async::CoroutineWithResult<GetConnectionCoroutine, const provider::ResourceHandle<data::stream::IOStream>&> {
private:
std::shared_ptr<Monitor> m_monitor;
std::shared_ptr<ConnectionProvider> m_connectionProvider;
std::shared_ptr<ConnectionInvalidator> m_invalidator;
public:
GetConnectionCoroutine(const std::shared_ptr<Monitor>& monitor,
const std::shared_ptr<ConnectionProvider>& connectionProvider,
const std::shared_ptr<ConnectionInvalidator>& invalidator)
: m_monitor(monitor)
, m_connectionProvider(connectionProvider)
, m_invalidator(invalidator)
{}
Action act() override {
return m_connectionProvider->getAsync().callbackTo(&GetConnectionCoroutine::onConnection);
}
Action onConnection(const provider::ResourceHandle<data::stream::IOStream>& connection) {
if(!connection) {
return _return(nullptr);
}
auto proxy = std::make_shared<ConnectionProxy>(m_monitor, connection);
m_monitor->addConnection(proxy.get());
return _return(provider::ResourceHandle<data::stream::IOStream>(proxy, m_invalidator));
}
};
return GetConnectionCoroutine::startForResult(m_monitor, m_connectionProvider, m_invalidator);
}
void ConnectionMonitor::addStatCollector(const std::shared_ptr<StatCollector>& collector) {
m_monitor->addStatCollector(collector);
}
void ConnectionMonitor::addMetricsChecker(const std::shared_ptr<MetricsChecker>& checker) {
m_monitor->addMetricsChecker(checker);
}
void ConnectionMonitor::stop() {
m_monitor->stop();
}
}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/network/monitor/ConnectionMonitor.cpp
|
C++
|
apache-2.0
| 11,348
|
/***************************************************************************
*
* 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_network_monitor_ConnectionMonitor_hpp
#define oatpp_network_monitor_ConnectionMonitor_hpp
#include "MetricsChecker.hpp"
#include "oatpp/network/ConnectionProvider.hpp"
#include "oatpp/core/data/stream/Stream.hpp"
#include <unordered_set>
#include <condition_variable>
namespace oatpp { namespace network { namespace monitor {
/**
* ConnectionMonitor is a middleman who's able to manage provided connections
* and close those ones that are not satisfy selected rules.
*/
class ConnectionMonitor : public ClientConnectionProvider, public ServerConnectionProvider {
private:
class ConnectionInvalidator : public provider::Invalidator<data::stream::IOStream> {
public:
void invalidate(const std::shared_ptr<data::stream::IOStream>& connection) override;
};
private:
class Monitor; // FWD
class ConnectionProxy : public data::stream::IOStream {
friend Monitor;
private:
std::shared_ptr<Monitor> m_monitor;
provider::ResourceHandle<data::stream::IOStream> m_connectionHandle;
std::mutex m_statsMutex;
ConnectionStats m_stats;
public:
ConnectionProxy(const std::shared_ptr<Monitor>& monitor,
const provider::ResourceHandle<data::stream::IOStream>& connectionHandle);
~ConnectionProxy() override;
v_io_size read(void *buffer, v_buff_size count, async::Action& action) override;
v_io_size write(const void *data, v_buff_size count, async::Action& action) override;
void setInputStreamIOMode(data::stream::IOMode ioMode) override;
data::stream::IOMode getInputStreamIOMode() override;
data::stream::Context& getInputStreamContext() override;
void setOutputStreamIOMode(data::stream::IOMode ioMode) override;
data::stream::IOMode getOutputStreamIOMode() override;
data::stream::Context& getOutputStreamContext() override;
void invalidate();
};
private:
class Monitor : public oatpp::base::Countable {
private:
std::mutex m_runMutex;
std::condition_variable m_runCondition;
std::atomic<bool> m_running {true};
bool m_stopped {false};
std::mutex m_connectionsMutex;
std::unordered_set<v_uint64> m_connections;
std::mutex m_checkMutex;
std::vector<std::shared_ptr<MetricsChecker>> m_metricsCheckers;
std::unordered_map<oatpp::String, std::shared_ptr<StatCollector>> m_statCollectors;
private:
static void monitorTask(std::shared_ptr<Monitor> monitor);
private:
static void* createOrGetMetricData(ConnectionStats& stats, const std::shared_ptr<StatCollector>& collector);
public:
static std::shared_ptr<Monitor> createShared();
void addConnection(ConnectionProxy* connection);
void freeConnectionStats(ConnectionStats& stats);
void removeConnection(v_uint64 id);
void addStatCollector(const std::shared_ptr<StatCollector>& collector);
void removeStatCollector(const oatpp::String& metricName);
void addMetricsChecker(const std::shared_ptr<MetricsChecker>& checker);
void onConnectionRead(ConnectionStats& stats, v_io_size readResult);
void onConnectionWrite(ConnectionStats& stats, v_io_size writeResult);
void stop();
};
private:
std::shared_ptr<ConnectionInvalidator> m_invalidator;
std::shared_ptr<Monitor> m_monitor;
std::shared_ptr<ConnectionProvider> m_connectionProvider;
public:
/**
* Constructor.
* @param connectionProvider - underlying connection provider.
*/
ConnectionMonitor(const std::shared_ptr<ConnectionProvider>& connectionProvider);
provider::ResourceHandle<data::stream::IOStream> get() override;
async::CoroutineStarterForResult<const provider::ResourceHandle<data::stream::IOStream>&> getAsync() override;
void addStatCollector(const std::shared_ptr<StatCollector>& collector);
/**
* Add metrics checker.
* @param checker - &id:oatpp::network::monitor::MetricsChecker;.
*/
void addMetricsChecker(const std::shared_ptr<MetricsChecker>& checker);
void stop() override;
};
}}}
#endif //oatpp_network_monitor_ConnectionMonitor_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/network/monitor/ConnectionMonitor.hpp
|
C++
|
apache-2.0
| 5,028
|
/***************************************************************************
*
* 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_network_monitor_MetricsChecker_hpp
#define oatpp_network_monitor_MetricsChecker_hpp
#include "StatCollector.hpp"
namespace oatpp { namespace network { namespace monitor {
/**
* MetricsChecker checks &id:oatpp::network::monitor::ConnectionStats; if those are satisfy the rule.
*/
class MetricsChecker : public oatpp::base::Countable {
public:
/**
* Default virtual destructor.
*/
virtual ~MetricsChecker() = default;
/**
* Get list of metrics names that are checked by this MetricsChecker.
* @return
*/
virtual std::vector<oatpp::String> getMetricsList() = 0;
/**
* Create &id:oatpp::network::monitor::StatCollector; for given `metricName`.
* This method will be called by &id:oatpp::network::monitor::ConnectionMonitor; only if there is
* no such `StatCollector` registered in the `ConnectionMonitor` yet.
* @param metricName - name of the metric.
* @return - &id:oatpp::network::monitor::StatCollector;.
*/
virtual std::shared_ptr<StatCollector> createStatCollector(const oatpp::String& metricName) = 0;
/**
* Called by &id:oatpp::network::monitor::ConnectionMonitor; on each
* time interval to check if connection satisfies the rule.
* @param stats - &id:oatpp::network::monitor::ConnectionStats;.
* @param currMicroTime - current time microseconds.
* @return - `true` if connection satisfies the rule. `false` if connection should be closed.
*/
virtual bool check(const ConnectionStats& stats, v_int64 currMicroTime) = 0;
};
}}}
#endif //oatpp_network_monitor_MetricsChecker_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/network/monitor/MetricsChecker.hpp
|
C++
|
apache-2.0
| 2,572
|
/***************************************************************************
*
* 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_network_monitor_StatCollector_hpp
#define oatpp_network_monitor_StatCollector_hpp
#include "oatpp/core/Types.hpp"
#include "oatpp/core/IODefinitions.hpp"
namespace oatpp { namespace network { namespace monitor {
/**
* ConnectionStats.
*/
struct ConnectionStats {
/**
* Timestamp created microseconds.
* When connection was created.
*/
v_int64 timestampCreated = 0;
/**
* Total bytes read from the connection.
* Logs all bytes when the `read` method is called.
*/
v_io_size totalRead = 0;
/**
* Total bytes written to the connection.
* Logs all bytes when the `write` method is called.
*/
v_io_size totalWrite = 0;
/**
* Timestamp microseconds when the last successful read was performed on the connection.
*/
v_int64 timestampLastRead = 0;
/**
* Timestamp microseconds when the last successful write was performed on the connection.
*/
v_int64 timestampLastWrite = 0;
/**
* Amount of bytes read during the last successful read.
*/
v_io_size lastReadSize = 0;
/**
* Amount of bytes written during the last successful write.
*/
v_io_size lastWriteSize = 0;
/**
* Data collected by stat-collectors - &l:StatCollector;
*/
std::unordered_map<oatpp::String, void*> metricsData;
};
/**
* StatCollector collects metrics data of the connection.
*/
class StatCollector : public oatpp::base::Countable {
public:
/**
* Default virtual destructor.
*/
virtual ~StatCollector() = default;
/**
* Unique metric name that is collected by this `StatCollector`.
* @return - metricName. &id:oatpp::String;.
*/
virtual oatpp::String metricName() = 0;
/**
* Metric data constructor.
* @return
*/
virtual void* createMetricData() = 0;
/**
* Metric data destructor.
* @param metricData
*/
virtual void deleteMetricData(void* metricData) = 0;
/**
* On connection read event.
* @param metricData - metric data of the given connection.- the one created in the `createMetricData` method.
* @param readResult - result of the connection read method.
* @param timestamp - timestamp microseconds when the connection `read` method was called.
*/
virtual void onRead(void* metricData, v_io_size readResult, v_int64 timestamp) = 0;
/**
* On connection write event.
* @param metricData - metric data of the given connection.- the one created in the `createMetricData` method.
* @param writeResult - result of the connection write method.
* @param timestamp - timestamp microseconds when the connection `write` method was called.
*/
virtual void onWrite(void* metricData, v_io_size writeResult, v_int64 timestamp) = 0;
};
}}}
#endif //oatpp_network_monitor_StatCollector_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/network/monitor/StatCollector.hpp
|
C++
|
apache-2.0
| 3,748
|
/***************************************************************************
*
* 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 "./Connection.hpp"
#if defined(WIN32) || defined(_WIN32)
#include <io.h>
#include <WinSock2.h>
#else
#include <unistd.h>
#include <sys/socket.h>
#endif
#include <thread>
#include <chrono>
#include <fcntl.h>
namespace oatpp { namespace network { namespace tcp {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Connection
oatpp::data::stream::DefaultInitializedContext Connection::DEFAULT_CONTEXT(data::stream::StreamType::STREAM_INFINITE);
Connection::Connection(v_io_handle handle)
: m_handle(handle)
{
#if defined(WIN32) || defined(_WIN32)
// in Windows, there is no reliable method to get if a socket is blocking or not.
// Eevery socket is created blocking in Windows so we assume this state and pray.
setStreamIOMode(data::stream::BLOCKING);
#else
auto flags = fcntl(m_handle, F_GETFL);
if (flags < 0) {
throw std::runtime_error("[oatpp::network::tcp::Connection::Connection()]: Error. Can't get socket flags.");
}
if((flags & O_NONBLOCK) > 0) {
m_mode = data::stream::IOMode::ASYNCHRONOUS;
} else {
m_mode = data::stream::IOMode::BLOCKING;
}
#endif
}
Connection::~Connection(){
close();
}
v_io_size Connection::write(const void *buff, v_buff_size count, async::Action& action){
#if defined(WIN32) || defined(_WIN32)
auto result = ::send(m_handle, (const char*) buff, (int)count, 0);
if(result == SOCKET_ERROR) {
auto e = WSAGetLastError();
if(e == WSAEWOULDBLOCK){
if(m_mode == data::stream::ASYNCHRONOUS) {
action = oatpp::async::Action::createIOWaitAction(m_handle, oatpp::async::Action::IOEventType::IO_EVENT_WRITE);
}
return IOError::RETRY_WRITE; // For async io. In case socket is non-blocking
} else if(e == WSAEINTR) {
return IOError::RETRY_WRITE;
} else if(e == WSAECONNRESET) {
return IOError::BROKEN_PIPE;
} else {
//OATPP_LOGD("Connection", "write errno=%d", e);
return IOError::BROKEN_PIPE; // Consider all other errors as a broken pipe.
}
}
return result;
#else
errno = 0;
v_int32 flags = 0;
#ifdef MSG_NOSIGNAL
flags |= MSG_NOSIGNAL;
#endif
auto result = ::send(m_handle, buff, (size_t)count, flags);
if(result < 0) {
auto e = errno;
if(e == EAGAIN || e == EWOULDBLOCK){
if(m_mode == data::stream::ASYNCHRONOUS) {
action = oatpp::async::Action::createIOWaitAction(m_handle, oatpp::async::Action::IOEventType::IO_EVENT_WRITE);
}
return IOError::RETRY_WRITE; // For async io. In case socket is non-blocking
} else if(e == EINTR) {
return IOError::RETRY_WRITE;
} else if(e == EPIPE) {
return IOError::BROKEN_PIPE;
} else {
//OATPP_LOGD("Connection", "write errno=%d", e);
return IOError::BROKEN_PIPE; // Consider all other errors as a broken pipe.
}
}
return result;
#endif
}
v_io_size Connection::read(void *buff, v_buff_size count, async::Action& action){
#if defined(WIN32) || defined(_WIN32)
auto result = ::recv(m_handle, (char*)buff, (int)count, 0);
if(result == SOCKET_ERROR) {
auto e = WSAGetLastError();
if(e == WSAEWOULDBLOCK){
if(m_mode == data::stream::ASYNCHRONOUS) {
action = oatpp::async::Action::createIOWaitAction(m_handle, oatpp::async::Action::IOEventType::IO_EVENT_READ);
}
return IOError::RETRY_READ; // For async io. In case socket is non-blocking
} else if(e == WSAEINTR) {
return IOError::RETRY_READ;
} else if(e == WSAECONNRESET) {
return IOError::BROKEN_PIPE;
} else {
//OATPP_LOGD("Connection", "write errno=%d", e);
return IOError::BROKEN_PIPE; // Consider all other errors as a broken pipe.
}
}
return result;
#else
errno = 0;
auto result = ::read(m_handle, buff, (size_t)count);
if(result < 0) {
auto e = errno;
if(e == EAGAIN || e == EWOULDBLOCK){
if(m_mode == data::stream::ASYNCHRONOUS) {
action = oatpp::async::Action::createIOWaitAction(m_handle, oatpp::async::Action::IOEventType::IO_EVENT_READ);
}
return IOError::RETRY_READ; // For async io. In case socket is non-blocking
} else if(e == EINTR) {
return IOError::RETRY_READ;
} else if(e == ECONNRESET) {
return IOError::BROKEN_PIPE;
} else {
//OATPP_LOGD("Connection", "write errno=%d", e);
return IOError::BROKEN_PIPE; // Consider all other errors as a broken pipe.
}
}
return result;
#endif
}
#if defined(WIN32) || defined(_WIN32)
void Connection::setStreamIOMode(oatpp::data::stream::IOMode ioMode) {
u_long flags;
switch(ioMode) {
case data::stream::BLOCKING:
flags = 0;
if(NO_ERROR != ioctlsocket(m_handle, FIONBIO, &flags)) {
throw std::runtime_error("[oatpp::network::tcp::Connection::setStreamIOMode()]: Error. Can't set stream I/O mode to IOMode::BLOCKING.");
}
m_mode = data::stream::BLOCKING;
break;
case data::stream::ASYNCHRONOUS:
flags = 1;
if(NO_ERROR != ioctlsocket(m_handle, FIONBIO, &flags)) {
throw std::runtime_error("[oatpp::network::tcp::Connection::setStreamIOMode()]: Error. Can't set stream I/O mode to IOMode::ASYNCHRONOUS.");
}
m_mode = data::stream::ASYNCHRONOUS;
break;
}
}
#else
void Connection::setStreamIOMode(oatpp::data::stream::IOMode ioMode) {
auto flags = fcntl(m_handle, F_GETFL);
if (flags < 0) {
throw std::runtime_error("[oatpp::network::tcp::Connection::setStreamIOMode()]: Error. Can't get socket flags.");
}
switch(ioMode) {
case oatpp::data::stream::IOMode::BLOCKING:
flags = flags & (~O_NONBLOCK);
if (fcntl(m_handle, F_SETFL, flags) < 0) {
throw std::runtime_error("[oatpp::network::tcp::Connection::setStreamIOMode()]: Error. Can't set stream I/O mode to IOMode::BLOCKING.");
}
m_mode = data::stream::BLOCKING;
break;
case oatpp::data::stream::IOMode::ASYNCHRONOUS:
flags = (flags | O_NONBLOCK);
if (fcntl(m_handle, F_SETFL, flags) < 0) {
throw std::runtime_error("[oatpp::network::tcp::Connection::setStreamIOMode()]: Error. Can't set stream I/O mode to IOMode::ASYNCHRONOUS.");
}
m_mode = data::stream::ASYNCHRONOUS;
break;
}
}
#endif
void Connection::setOutputStreamIOMode(oatpp::data::stream::IOMode ioMode) {
setStreamIOMode(ioMode);
}
oatpp::data::stream::IOMode Connection::getOutputStreamIOMode() {
return m_mode;
}
oatpp::data::stream::Context& Connection::getOutputStreamContext() {
return DEFAULT_CONTEXT;
}
void Connection::setInputStreamIOMode(oatpp::data::stream::IOMode ioMode) {
setStreamIOMode(ioMode);
}
oatpp::data::stream::IOMode Connection::getInputStreamIOMode() {
return m_mode;
}
oatpp::data::stream::Context& Connection::getInputStreamContext() {
return DEFAULT_CONTEXT;
}
void Connection::close(){
#if defined(WIN32) || defined(_WIN32)
::closesocket(m_handle);
#else
::close(m_handle);
#endif
}
}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/network/tcp/Connection.cpp
|
C++
|
apache-2.0
| 8,000
|
/***************************************************************************
*
* 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_network_tcp_Connection_hpp
#define oatpp_network_tcp_Connection_hpp
#include "oatpp/core/data/stream/Stream.hpp"
namespace oatpp { namespace network { namespace tcp {
/**
* TCP Connection implementation. Extends &id:oatpp::base::Countable; and &id:oatpp::data::stream::IOStream;.
*/
class Connection : public oatpp::base::Countable, public oatpp::data::stream::IOStream {
private:
static oatpp::data::stream::DefaultInitializedContext DEFAULT_CONTEXT;
private:
v_io_handle m_handle;
data::stream::IOMode m_mode;
private:
void setStreamIOMode(oatpp::data::stream::IOMode ioMode);
public:
/**
* Constructor.
* @param handle - file descriptor (socket handle). See &id:oatpp::v_io_handle;.
*/
Connection(v_io_handle handle);
public:
/**
* Virtual Destructor (See &id:oatpp::base::Countable;).
* Close socket handle.
*/
~Connection();
/**
* Implementation of &id:oatpp::data::stream::IOStream::write;.
* @param buff - buffer containing data to write.
* @param count - bytes count you want to write.
* @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 amount of bytes written. See &id:oatpp::v_io_size;.
*/
v_io_size write(const void *buff, v_buff_size count, async::Action& action) override;
/**
* Implementation of &id:oatpp::data::stream::IOStream::read;.
* @param buff - buffer to read data to.
* @param count - buffer size.
* @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 amount of bytes read. See &id:oatpp::v_io_size;.
*/
v_io_size read(void *buff, v_buff_size count, async::Action& action) override;
/**
* Set OutputStream I/O mode.
* @param ioMode
*/
void setOutputStreamIOMode(oatpp::data::stream::IOMode ioMode) override;
/**
* Set OutputStream I/O mode.
* @return
*/
oatpp::data::stream::IOMode getOutputStreamIOMode() override;
/**
* Get output stream context.
* @return - &id:oatpp::data::stream::Context;.
*/
oatpp::data::stream::Context& getOutputStreamContext() override;
/**
* Set InputStream I/O mode.
* @param ioMode
*/
void setInputStreamIOMode(oatpp::data::stream::IOMode ioMode) override;
/**
* Get InputStream I/O mode.
* @return
*/
oatpp::data::stream::IOMode getInputStreamIOMode() override;
/**
* Get input stream context. <br>
* @return - &id:oatpp::data::stream::Context;.
*/
oatpp::data::stream::Context& getInputStreamContext() override;
/**
* Close socket handle.
*/
void close();
/**
* Get socket handle.
* @return - socket handle. &id:oatpp::v_io_handle;.
*/
v_io_handle getHandle(){
return m_handle;
}
};
}}}
#endif /* oatpp_network_tcp_Connection_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/network/tcp/Connection.hpp
|
C++
|
apache-2.0
| 3,962
|
/***************************************************************************
*
* 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 "./ConnectionProvider.hpp"
#include "oatpp/network/tcp/Connection.hpp"
#include "oatpp/core/utils/ConversionUtils.hpp"
#include <fcntl.h>
#if defined(WIN32) || defined(_WIN32)
#include <io.h>
#include <WinSock2.h>
#include <WS2tcpip.h>
#else
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
#endif
namespace oatpp { namespace network { namespace tcp { namespace client {
void ConnectionProvider::ConnectionInvalidator::invalidate(const std::shared_ptr<data::stream::IOStream>& connection) {
/************************************************
* WARNING!!!
*
* shutdown(handle, SHUT_RDWR) <--- DO!
* close(handle); <--- DO NOT!
*
* DO NOT CLOSE file handle here -
* USE shutdown instead.
* Using close prevent FDs popping out of epoll,
* and they'll be stuck there forever.
************************************************/
auto c = std::static_pointer_cast<network::tcp::Connection>(connection);
v_io_handle handle = c->getHandle();
#if defined(WIN32) || defined(_WIN32)
shutdown(handle, SD_BOTH);
#else
shutdown(handle, SHUT_RDWR);
#endif
}
ConnectionProvider::ConnectionProvider(const network::Address& address)
: m_invalidator(std::make_shared<ConnectionInvalidator>())
, m_address(address)
{
setProperty(PROPERTY_HOST, address.host);
setProperty(PROPERTY_PORT, oatpp::utils::conversion::int32ToStr(address.port));
}
provider::ResourceHandle<data::stream::IOStream> ConnectionProvider::get() {
auto portStr = oatpp::utils::conversion::int32ToStr(m_address.port);
struct addrinfo hints;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = 0;
hints.ai_protocol = 0;
switch(m_address.family) {
case Address::IP_4: hints.ai_family = AF_INET; break;
case Address::IP_6: hints.ai_family = AF_INET6; break;
default:
hints.ai_family = AF_UNSPEC;
}
struct addrinfo* result;
auto res = getaddrinfo(m_address.host->c_str(), portStr->c_str(), &hints, &result);
if (res != 0) {
#if defined(WIN32) || defined(_WIN32)
throw std::runtime_error("[oatpp::network::tcp::client::ConnectionProvider::getConnection()]. "
"Error. Call to getaddrinfo() failed with code " + std::to_string(res));
#else
std::string errorString = "[oatpp::network::tcp::client::ConnectionProvider::getConnection()]. Error. Call to getaddrinfo() failed: ";
throw std::runtime_error(errorString.append(gai_strerror(res)));
#endif
}
if (result == nullptr) {
throw std::runtime_error("[oatpp::network::tcp::client::ConnectionProvider::getConnection()]. Error. Call to getaddrinfo() returned no results.");
}
struct addrinfo* currResult = result;
oatpp::v_io_handle clientHandle = INVALID_IO_HANDLE;
while(currResult != nullptr) {
clientHandle = socket(currResult->ai_family, currResult->ai_socktype, currResult->ai_protocol);
if(clientHandle >= 0) {
if(connect(clientHandle, currResult->ai_addr, (int)currResult->ai_addrlen) == 0) {
break;
} else {
#if defined(WIN32) || defined(_WIN32)
::closesocket(clientHandle);
#else
::close(clientHandle);
#endif
}
}
currResult = currResult->ai_next;
}
freeaddrinfo(result);
if(currResult == nullptr) {
throw std::runtime_error("[oatpp::network::tcp::client::ConnectionProvider::getConnection()]: Error. Can't connect.");
}
#ifdef SO_NOSIGPIPE
int yes = 1;
v_int32 ret = setsockopt(clientHandle, SOL_SOCKET, SO_NOSIGPIPE, &yes, sizeof(int));
if(ret < 0) {
OATPP_LOGD("[oatpp::network::tcp::client::ConnectionProvider::getConnection()]", "Warning. Failed to set %s for socket", "SO_NOSIGPIPE");
}
#endif
return provider::ResourceHandle<data::stream::IOStream>(
std::make_shared<oatpp::network::tcp::Connection>(clientHandle),
m_invalidator
);
}
oatpp::async::CoroutineStarterForResult<const provider::ResourceHandle<data::stream::IOStream>&> ConnectionProvider::getAsync() {
class ConnectCoroutine : public oatpp::async::CoroutineWithResult<ConnectCoroutine, const provider::ResourceHandle<oatpp::data::stream::IOStream>&> {
private:
std::shared_ptr<ConnectionInvalidator> m_connectionInvalidator;
network::Address m_address;
oatpp::v_io_handle m_clientHandle;
private:
struct addrinfo* m_result;
struct addrinfo* m_currentResult;
bool m_isHandleOpened;
public:
ConnectCoroutine(const std::shared_ptr<ConnectionInvalidator>& connectionInvalidator,
const network::Address& address)
: m_connectionInvalidator(connectionInvalidator)
, m_address(address)
, m_result(nullptr)
, m_currentResult(nullptr)
, m_isHandleOpened(false)
{}
~ConnectCoroutine() {
if(m_result != nullptr) {
freeaddrinfo(m_result);
}
}
Action act() override {
auto portStr = oatpp::utils::conversion::int32ToStr(m_address.port);
struct addrinfo hints;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = 0;
hints.ai_protocol = 0;
switch(m_address.family) {
case Address::IP_4: hints.ai_family = AF_INET; break;
case Address::IP_6: hints.ai_family = AF_INET6; break;
default:
hints.ai_family = AF_UNSPEC;
}
// TODO make call to get addrinfo non-blocking !!!
auto res = getaddrinfo(m_address.host->c_str(), portStr->c_str(), &hints, &m_result);
if (res != 0) {
return error<async::Error>(
"[oatpp::network::tcp::client::ConnectionProvider::getConnectionAsync()]. Error. Call to getaddrinfo() failed.");
}
m_currentResult = m_result;
if (m_result == nullptr) {
return error<async::Error>(
"[oatpp::network::tcp::client::ConnectionProvider::getConnectionAsync()]. Error. Call to getaddrinfo() returned no results.");
}
return yieldTo(&ConnectCoroutine::iterateAddrInfoResults);
}
Action iterateAddrInfoResults() {
/*
* Close previously opened socket here.
* Don't ever close socket in the method which returns action ioWait or ioRepeat
*/
if(m_isHandleOpened) {
m_isHandleOpened = false;
#if defined(WIN32) || defined(_WIN32)
::closesocket(m_clientHandle);
#else
::close(m_clientHandle);
#endif
}
if(m_currentResult != nullptr) {
m_clientHandle = socket(m_currentResult->ai_family, m_currentResult->ai_socktype, m_currentResult->ai_protocol);
#if defined(WIN32) || defined(_WIN32)
if (m_clientHandle == INVALID_SOCKET) {
m_currentResult = m_currentResult->ai_next;
return repeat();
}
u_long flags = 1;
ioctlsocket(m_clientHandle, FIONBIO, &flags);
#else
if (m_clientHandle < 0) {
m_currentResult = m_currentResult->ai_next;
return repeat();
}
fcntl(m_clientHandle, F_SETFL, O_NONBLOCK);
#endif
#ifdef SO_NOSIGPIPE
int yes = 1;
v_int32 ret = setsockopt(m_clientHandle, SOL_SOCKET, SO_NOSIGPIPE, &yes, sizeof(int));
if(ret < 0) {
OATPP_LOGD("[oatpp::network::tcp::client::ConnectionProvider::getConnectionAsync()]", "Warning. Failed to set %s for socket", "SO_NOSIGPIPE");
}
#endif
m_isHandleOpened = true;
return yieldTo(&ConnectCoroutine::doConnect);
}
return error<Error>("[oatpp::network::tcp::client::ConnectionProvider::getConnectionAsync()]: Error. Can't connect.");
}
Action doConnect() {
errno = 0;
auto res = connect(m_clientHandle, m_currentResult->ai_addr, (int)m_currentResult->ai_addrlen);
#if defined(WIN32) || defined(_WIN32)
auto error = WSAGetLastError();
if(res == 0 || error == WSAEISCONN) {
return _return(provider::ResourceHandle<data::stream::IOStream>(
std::make_shared<oatpp::network::tcp::Connection>(m_clientHandle),
m_connectionInvalidator
));
}
if(error == WSAEWOULDBLOCK || error == WSAEINPROGRESS) {
return ioWait(m_clientHandle, oatpp::async::Action::IOEventType::IO_EVENT_WRITE);
} else if(error == WSAEINTR || error == WSAEALREADY) {
return ioRepeat(m_clientHandle, oatpp::async::Action::IOEventType::IO_EVENT_WRITE);
} else if(error == WSAEINVAL) {
return AbstractCoroutine::error(new async::Error(
"[oatpp::network::tcp::client::ConnectionProvider::doConnect()]: Error. The parameter m_clientHandle is a listening socket."));
}
#else
if(res == 0 || errno == EISCONN) {
return _return(provider::ResourceHandle<data::stream::IOStream>(
std::make_shared<oatpp::network::tcp::Connection>(m_clientHandle),
m_connectionInvalidator
));
}
if(errno == EALREADY || errno == EINPROGRESS) {
return ioWait(m_clientHandle, oatpp::async::Action::IOEventType::IO_EVENT_WRITE);
} else if(errno == EINTR) {
return ioRepeat(m_clientHandle, oatpp::async::Action::IOEventType::IO_EVENT_WRITE);
}
#endif
m_currentResult = m_currentResult->ai_next;
return yieldTo(&ConnectCoroutine::iterateAddrInfoResults);
}
};
return ConnectCoroutine::startForResult(m_invalidator, m_address);
}
}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/network/tcp/client/ConnectionProvider.cpp
|
C++
|
apache-2.0
| 10,437
|
/***************************************************************************
*
* 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_netword_tcp_client_ConnectionProvider_hpp
#define oatpp_netword_tcp_client_ConnectionProvider_hpp
#include "oatpp/network/Address.hpp"
#include "oatpp/network/ConnectionProvider.hpp"
#include "oatpp/core/provider/Invalidator.hpp"
#include "oatpp/core/Types.hpp"
namespace oatpp { namespace network { namespace tcp { namespace client {
/**
* Simple provider of clinet TCP connections.
*/
class ConnectionProvider : public ClientConnectionProvider {
private:
class ConnectionInvalidator : public provider::Invalidator<data::stream::IOStream> {
public:
void invalidate(const std::shared_ptr<data::stream::IOStream>& connection) override;
};
private:
std::shared_ptr<ConnectionInvalidator> m_invalidator;
protected:
network::Address m_address;
public:
/**
* Constructor.
* @param address - &id:oatpp::network::Address;.
*/
ConnectionProvider(const network::Address& address);
public:
/**
* Create shared client ConnectionProvider.
* @param address - &id:oatpp::network::Address;.
* @return - `std::shared_ptr` to ConnectionProvider.
*/
static std::shared_ptr<ConnectionProvider> createShared(const network::Address& address){
return std::make_shared<ConnectionProvider>(address);
}
/**
* Implements &id:oatpp::provider::Provider::stop;. Here does nothing.
*/
void stop() override {
// DO NOTHING
}
/**
* Get connection.
* @return - `std::shared_ptr` to &id:oatpp::data::stream::IOStream;.
*/
provider::ResourceHandle<data::stream::IOStream> get() override;
/**
* Get connection in asynchronous manner.
* @return - &id:oatpp::async::CoroutineStarterForResult;.
*/
oatpp::async::CoroutineStarterForResult<const provider::ResourceHandle<data::stream::IOStream>&> getAsync() override;
/**
* Get address - &id:oatpp::network::Address;.
* @return
*/
const network::Address& getAddress() const {
return m_address;
}
};
}}}}
#endif /* oatpp_netword_tcp_client_ConnectionProvider_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/network/tcp/client/ConnectionProvider.hpp
|
C++
|
apache-2.0
| 3,016
|
/***************************************************************************
*
* 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 "./ConnectionProvider.hpp"
#include "oatpp/core/utils/ConversionUtils.hpp"
#include <fcntl.h>
#if defined(WIN32) || defined(_WIN32)
#include <io.h>
#include <WinSock2.h>
#include <WS2tcpip.h>
#else
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
#include <unistd.h>
#if defined(__FreeBSD__)
#include <netinet/in.h>
#endif
#endif
// Workaround for MinGW from: https://www.mail-archive.com/users@ipv6.org/msg02107.html
#if defined(__MINGW32__) && _WIN32_WINNT < 0x0600
const char * inet_ntop (int af, const void *src, char *dst, socklen_t cnt) {
if (af == AF_INET) {
struct sockaddr_in in;
memset (&in, 0, sizeof(in));
in.sin_family = AF_INET;
memcpy (&in.sin_addr, src, sizeof(struct in_addr));
getnameinfo ((struct sockaddr *)&in, sizeof (struct sockaddr_in), dst, cnt, NULL, 0, NI_NUMERICHOST);
return dst;
} else if (af == AF_INET6) {
struct sockaddr_in6 in;
memset (&in, 0, sizeof(in));
in.sin6_family = AF_INET6;
memcpy (&in.sin6_addr, src, sizeof(struct in_addr6));
getnameinfo ((struct sockaddr *)&in, sizeof (struct sockaddr_in6), dst, cnt, NULL, 0, NI_NUMERICHOST);
return dst;
}
return NULL;
}
#endif
namespace oatpp { namespace network { namespace tcp { namespace server {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ExtendedConnection
const char* const ConnectionProvider::ExtendedConnection::PROPERTY_PEER_ADDRESS = "peer_address";
const char* const ConnectionProvider::ExtendedConnection::PROPERTY_PEER_ADDRESS_FORMAT = "peer_address_format";
const char* const ConnectionProvider::ExtendedConnection::PROPERTY_PEER_PORT = "peer_port";
ConnectionProvider::ExtendedConnection::ExtendedConnection(v_io_handle handle, data::stream::Context::Properties&& properties)
: Connection(handle)
, m_context(data::stream::StreamType::STREAM_INFINITE, std::forward<data::stream::Context::Properties>(properties))
{}
oatpp::data::stream::Context& ConnectionProvider::ExtendedConnection::getOutputStreamContext() {
return m_context;
}
oatpp::data::stream::Context& ConnectionProvider::ExtendedConnection::getInputStreamContext() {
return m_context;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ConnectionProvider::ConnectionInvalidator
void ConnectionProvider::ConnectionInvalidator::invalidate(const std::shared_ptr<data::stream::IOStream>& connection) {
/************************************************
* WARNING!!!
*
* shutdown(handle, SHUT_RDWR) <--- DO!
* close(handle); <--- DO NOT!
*
* DO NOT CLOSE file handle here -
* USE shutdown instead.
* Using close prevent FDs popping out of epoll,
* and they'll be stuck there forever.
************************************************/
auto c = std::static_pointer_cast<network::tcp::Connection>(connection);
v_io_handle handle = c->getHandle();
#if defined(WIN32) || defined(_WIN32)
shutdown(handle, SD_BOTH);
#else
shutdown(handle, SHUT_RDWR);
#endif
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ConnectionProvider
ConnectionProvider::ConnectionProvider(const network::Address& address, bool useExtendedConnections)
: m_invalidator(std::make_shared<ConnectionInvalidator>())
, m_address(address)
, m_closed(false)
, m_useExtendedConnections(useExtendedConnections)
{
setProperty(PROPERTY_HOST, m_address.host);
setProperty(PROPERTY_PORT, oatpp::utils::conversion::int32ToStr(m_address.port));
m_serverHandle = instantiateServer();
}
ConnectionProvider::~ConnectionProvider() {
stop();
}
void ConnectionProvider::stop() {
if(!m_closed) {
m_closed = true;
#if defined(WIN32) || defined(_WIN32)
::closesocket(m_serverHandle);
#else
::close(m_serverHandle);
#endif
}
}
#if defined(WIN32) || defined(_WIN32)
oatpp::v_io_handle ConnectionProvider::instantiateServer(){
SOCKET serverHandle = INVALID_SOCKET;
struct addrinfo *result = nullptr;
struct addrinfo hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = 0;
hints.ai_flags = AI_PASSIVE;
switch(m_address.family) {
case Address::IP_4: hints.ai_family = AF_INET; break;
case Address::IP_6: hints.ai_family = AF_INET6; break;
default:
hints.ai_family = AF_UNSPEC;
}
auto portStr = oatpp::utils::conversion::int32ToStr(m_address.port);
const int iResult = getaddrinfo(m_address.host->c_str(), portStr->c_str(), &hints, &result);
if (iResult != 0) {
OATPP_LOGE("[oatpp::network::tcp::server::ConnectionProvider::instantiateServer()]", "Error. Call to getaddrinfo() failed with result=%d", iResult);
throw std::runtime_error("[oatpp::network::tcp::server::ConnectionProvider::instantiateServer()]: Error. Call to getaddrinfo() failed.");
}
struct addrinfo* currResult = result;
while(currResult != nullptr) {
serverHandle = socket(currResult->ai_family, currResult->ai_socktype, currResult->ai_protocol);
if (serverHandle != INVALID_SOCKET) {
int no = 0;
if (hints.ai_family == AF_UNSPEC || hints.ai_family == Address::IP_6) {
if (setsockopt(serverHandle, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&no, sizeof( int ) ) != 0 ) {
OATPP_LOGW("[oatpp::network::tcp::server::ConnectionProvider::instantiateServer()]",
"Warning. Failed to set %s for accepting socket: %s", "IPV6_V6ONLY",
strerror(errno));
}
}
if (bind(serverHandle, currResult->ai_addr, (int) currResult->ai_addrlen) != SOCKET_ERROR &&
listen(serverHandle, SOMAXCONN) != SOCKET_ERROR)
{
break;
}
closesocket(serverHandle);
}
currResult = currResult->ai_next;
}
freeaddrinfo(result);
if (currResult == nullptr) {
OATPP_LOGE("[oatpp::network::tcp::server::ConnectionProvider::instantiateServer()]",
"Error. Couldn't bind. WSAGetLastError=%ld", WSAGetLastError());
throw std::runtime_error("[oatpp::network::tcp::server::ConnectionProvider::instantiateServer()]: "
"Error. Couldn't bind ");
}
u_long flags = 1;
if(NO_ERROR != ioctlsocket(serverHandle, FIONBIO, &flags)) {
throw std::runtime_error("[oatpp::network::tcp::server::ConnectionProvider::instantiateServer()]: Error. Call to ioctlsocket failed.");
}
// Update port after binding (typicaly in case of port = 0)
struct ::sockaddr_in s_in;
::memset(&s_in, 0, sizeof(s_in));
::socklen_t s_in_len = sizeof(s_in);
::getsockname(serverHandle, (struct sockaddr *)&s_in, &s_in_len);
setProperty(PROPERTY_PORT, oatpp::utils::conversion::int32ToStr(ntohs(s_in.sin_port)));
return serverHandle;
}
#else
oatpp::v_io_handle ConnectionProvider::instantiateServer(){
oatpp::v_io_handle serverHandle;
v_int32 ret;
int yes = 1;
struct addrinfo *result = NULL;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = 0;
hints.ai_flags = AI_PASSIVE;
switch(m_address.family) {
case Address::IP_4: hints.ai_family = AF_INET; break;
case Address::IP_6: hints.ai_family = AF_INET6; break;
default:
hints.ai_family = AF_UNSPEC;
}
auto portStr = oatpp::utils::conversion::int32ToStr(m_address.port);
ret = getaddrinfo(m_address.host->c_str(), portStr->c_str(), &hints, &result);
if (ret != 0) {
OATPP_LOGE("[oatpp::network::tcp::server::ConnectionProvider::instantiateServer()]", "Error. Call to getaddrinfo() failed with result=%d: %s", ret, strerror(errno));
throw std::runtime_error("[oatpp::network::tcp::server::ConnectionProvider::instantiateServer()]: Error. Call to getaddrinfo() failed.");
}
struct addrinfo* currResult = result;
while(currResult != nullptr) {
serverHandle = socket(currResult->ai_family, currResult->ai_socktype, currResult->ai_protocol);
if (serverHandle >= 0) {
if (setsockopt(serverHandle, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) != 0) {
OATPP_LOGW("[oatpp::network::tcp::server::ConnectionProvider::instantiateServer()]",
"Warning. Failed to set %s for accepting socket: %s", "SO_REUSEADDR", strerror(errno));
}
if (bind(serverHandle, currResult->ai_addr, (int) currResult->ai_addrlen) == 0 &&
listen(serverHandle, 10000) == 0)
{
break;
}
::close(serverHandle);
}
currResult = currResult->ai_next;
}
freeaddrinfo(result);
if (currResult == nullptr) {
std::string err = strerror(errno);
OATPP_LOGE("[oatpp::network::tcp::server::ConnectionProvider::instantiateServer()]",
"Error. Couldn't bind. %s", err.c_str());
throw std::runtime_error("[oatpp::network::tcp::server::ConnectionProvider::instantiateServer()]: "
"Error. Couldn't bind " + err);
}
fcntl(serverHandle, F_SETFL, O_NONBLOCK);
// Update port after binding (typicaly in case of port = 0)
struct ::sockaddr_in s_in;
::memset(&s_in, 0, sizeof(s_in));
::socklen_t s_in_len = sizeof(s_in);
::getsockname(serverHandle, (struct sockaddr *)&s_in, &s_in_len);
setProperty(PROPERTY_PORT, oatpp::utils::conversion::int32ToStr(ntohs(s_in.sin_port)));
return serverHandle;
}
#endif
bool ConnectionProvider::prepareConnectionHandle(oatpp::v_io_handle handle) {
if (handle < 0) {
v_int32 error = errno;
if(error == EAGAIN || error == EWOULDBLOCK){
return false;
} else {
if(!m_closed) { // m_serverHandle==0 if ConnectionProvider was closed. Not an error.
OATPP_LOGD("[oatpp::network::tcp::server::ConnectionProvider::prepareConnectionHandle()]", "Error. %d", error);
}
return false;
}
}
#ifdef SO_NOSIGPIPE
int yes = 1;
v_int32 ret = setsockopt(handle, SOL_SOCKET, SO_NOSIGPIPE, &yes, sizeof(int));
if(ret < 0) {
OATPP_LOGD("[oatpp::network::tcp::server::ConnectionProvider::prepareConnectionHandle()]", "Warning. Failed to set %s for socket", "SO_NOSIGPIPE");
}
#endif
return true;
}
provider::ResourceHandle<data::stream::IOStream> ConnectionProvider::getDefaultConnection() {
oatpp::v_io_handle handle = accept(m_serverHandle, nullptr, nullptr);
if(!oatpp::isValidIOHandle(handle)) {
return nullptr;
}
if(prepareConnectionHandle(handle)) {
return provider::ResourceHandle<data::stream::IOStream>(
std::make_shared<Connection>(handle),
m_invalidator
);
}
return nullptr;
}
provider::ResourceHandle<data::stream::IOStream> ConnectionProvider::getExtendedConnection() {
struct sockaddr_storage clientAddress;
socklen_t clientAddressSize = sizeof(clientAddress);
data::stream::Context::Properties properties;
oatpp::v_io_handle handle = accept(m_serverHandle, (struct sockaddr*) &clientAddress, &clientAddressSize);
if(!oatpp::isValidIOHandle(handle)) {
return nullptr;
}
if (clientAddress.ss_family == AF_INET) {
char strIp[INET_ADDRSTRLEN];
struct sockaddr_in* sockAddress = (struct sockaddr_in*) &clientAddress;
inet_ntop(AF_INET, &sockAddress->sin_addr, strIp, INET_ADDRSTRLEN);
properties.put_LockFree(ExtendedConnection::PROPERTY_PEER_ADDRESS, oatpp::String((const char*) strIp));
properties.put_LockFree(ExtendedConnection::PROPERTY_PEER_ADDRESS_FORMAT, "ipv4");
properties.put_LockFree(ExtendedConnection::PROPERTY_PEER_PORT, oatpp::utils::conversion::int32ToStr(sockAddress->sin_port));
} else if (clientAddress.ss_family == AF_INET6) {
char strIp[INET6_ADDRSTRLEN];
struct sockaddr_in6* sockAddress = (struct sockaddr_in6*) &clientAddress;
inet_ntop(AF_INET6, &sockAddress->sin6_addr, strIp, INET6_ADDRSTRLEN);
properties.put_LockFree(ExtendedConnection::PROPERTY_PEER_ADDRESS, oatpp::String((const char*) strIp));
properties.put_LockFree(ExtendedConnection::PROPERTY_PEER_ADDRESS_FORMAT, "ipv6");
properties.put_LockFree(ExtendedConnection::PROPERTY_PEER_PORT, oatpp::utils::conversion::int32ToStr(sockAddress->sin6_port));
} else {
#if defined(WIN32) || defined(_WIN32)
::closesocket(handle);
#else
::close(handle);
#endif
OATPP_LOGE("[oatpp::network::tcp::server::ConnectionProvider::getExtendedConnection()]", "Error. Unknown address family.");
return nullptr;
}
if(prepareConnectionHandle(handle)) {
return provider::ResourceHandle<data::stream::IOStream>(
std::make_shared<ExtendedConnection>(handle, std::move(properties)),
m_invalidator
);
}
return nullptr;
}
provider::ResourceHandle<oatpp::data::stream::IOStream> ConnectionProvider::get() {
fd_set set;
struct timeval timeout;
FD_ZERO(&set);
FD_SET(m_serverHandle, &set);
timeout.tv_sec = 1;
timeout.tv_usec = 0;
while(!m_closed) {
auto res = select(int(m_serverHandle + 1), &set, nullptr, nullptr, &timeout);
if (res >= 0) {
break;
}
}
if(m_useExtendedConnections) {
return getExtendedConnection();
}
return getDefaultConnection();
}
}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/network/tcp/server/ConnectionProvider.cpp
|
C++
|
apache-2.0
| 14,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_netword_tcp_server_ConnectionProvider_hpp
#define oatpp_netword_tcp_server_ConnectionProvider_hpp
#include "oatpp/network/Address.hpp"
#include "oatpp/network/ConnectionProvider.hpp"
#include "oatpp/network/tcp/Connection.hpp"
#include "oatpp/core/Types.hpp"
namespace oatpp { namespace network { namespace tcp { namespace server {
/**
* Simple provider of TCP connections.
*/
class ConnectionProvider : public ServerConnectionProvider {
private:
class ConnectionInvalidator : public provider::Invalidator<data::stream::IOStream> {
public:
void invalidate(const std::shared_ptr<data::stream::IOStream>& connection) override;
};
public:
/**
* Connection with extra data - ex.: peer address.
*/
class ExtendedConnection : public oatpp::network::tcp::Connection {
public:
static const char* const PROPERTY_PEER_ADDRESS;
static const char* const PROPERTY_PEER_ADDRESS_FORMAT;
static const char* const PROPERTY_PEER_PORT;
protected:
data::stream::DefaultInitializedContext m_context;
public:
/**
* Constructor.
* @param handle - &id:oatpp::v_io_handle;.
* @param properties - &id:oatpp::data::stream::Context::Properties;.
*/
ExtendedConnection(v_io_handle handle, data::stream::Context::Properties&& properties);
/**
* Get output stream context.
* @return - &id:oatpp::data::stream::Context;.
*/
oatpp::data::stream::Context& getOutputStreamContext() override;
/**
* Get input stream context. <br>
* @return - &id:oatpp::data::stream::Context;.
*/
oatpp::data::stream::Context& getInputStreamContext() override;
};
private:
std::shared_ptr<ConnectionInvalidator> m_invalidator;
network::Address m_address;
std::atomic<bool> m_closed;
oatpp::v_io_handle m_serverHandle;
bool m_useExtendedConnections;
private:
oatpp::v_io_handle instantiateServer();
private:
bool prepareConnectionHandle(oatpp::v_io_handle handle);
provider::ResourceHandle<data::stream::IOStream> getDefaultConnection();
provider::ResourceHandle<data::stream::IOStream> getExtendedConnection();
public:
/**
* Constructor.
* @param address - &id:oatpp::network::Address;.
* @param useExtendedConnections - set `true` to use &l:ConnectionProvider::ExtendedConnection;.
* `false` to use &id:oatpp::network::tcp::Connection;.
*/
ConnectionProvider(const network::Address& address, bool useExtendedConnections = false);
public:
/**
* Create shared ConnectionProvider.
* @param address - &id:oatpp::network::Address;.
* @param useExtendedConnections - set `true` to use &l:ConnectionProvider::ExtendedConnection;.
* `false` to use &id:oatpp::network::tcp::Connection;.
* @return - `std::shared_ptr` to ConnectionProvider.
*/
static std::shared_ptr<ConnectionProvider> createShared(const network::Address& address, bool useExtendedConnections = false){
return std::make_shared<ConnectionProvider>(address, useExtendedConnections);
}
/**
* Virtual destructor.
*/
~ConnectionProvider();
/**
* Close accept-socket.
*/
void stop() override;
/**
* Get incoming connection.
* @return &id:oatpp::data::stream::IOStream;.
*/
provider::ResourceHandle<data::stream::IOStream> get() override;
/**
* No need to implement this.<br>
* For Asynchronous IO in oatpp it is considered to be a good practice
* to accept connections in a seperate thread with the blocking accept()
* and then process connections in Asynchronous manner with non-blocking read/write.
* <br>
* *It may be implemented later*
*/
oatpp::async::CoroutineStarterForResult<const provider::ResourceHandle<data::stream::IOStream>&> getAsync() override {
/*
* No need to implement this.
* For Asynchronous IO in oatpp it is considered to be a good practice
* to accept connections in a seperate thread with the blocking accept()
* and then process connections in Asynchronous manner with non-blocking read/write
*
* It may be implemented later
*/
throw std::runtime_error("[oatpp::network::tcp::server::ConnectionProvider::getAsync()]: Error. Not implemented.");
}
/**
* Get address - &id:oatpp::network::Address;.
* @return
*/
const network::Address& getAddress() const {
return m_address;
}
};
}}}}
#endif /* oatpp_netword_tcp_server_ConnectionProvider_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/network/tcp/server/ConnectionProvider.hpp
|
C++
|
apache-2.0
| 5,422
|
/***************************************************************************
*
* 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 "Interface.hpp"
namespace oatpp { namespace network { namespace virtual_ {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ListenerLock
Interface::ListenerLock::ListenerLock(Interface* _interface)
: m_interface(_interface)
{}
Interface::ListenerLock::~ListenerLock() {
if(m_interface != nullptr) {
m_interface->unbindListener(this);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Interface
std::recursive_mutex Interface::m_registryMutex;
std::unordered_map<oatpp::String, std::weak_ptr<Interface>> Interface::m_registry;
void Interface::registerInterface(const std::shared_ptr<Interface>& _interface) {
std::lock_guard<std::recursive_mutex> lock(m_registryMutex);
auto it = m_registry.find(_interface->getName());
if(it != m_registry.end()) {
throw std::runtime_error
("[oatpp::network::virtual_::Interface::registerInterface()]: Error. Interface with such name already exists - '" + *_interface->getName() + "'.");
}
m_registry.insert({_interface->getName(), _interface});
}
void Interface::unregisterInterface(const oatpp::String& name) {
std::lock_guard<std::recursive_mutex> lock(m_registryMutex);
auto it = m_registry.find(name);
if(it == m_registry.end()) {
throw std::runtime_error
("[oatpp::network::virtual_::Interface::unregisterInterface()]: Error. Interface NOT FOUND - '" + *name + "'.");
}
m_registry.erase(it);
}
Interface::Interface(const oatpp::String& name)
: m_name(name)
, m_listenerLock(nullptr)
{}
Interface::~Interface() {
unregisterInterface(getName());
{
std::lock_guard<std::mutex> lock(m_listenerMutex);
if ((void*)m_listenerLock != nullptr) {
OATPP_LOGE("[oatpp::network::virtual_::Interface::~Interface()]",
"Error! Interface destructor called, but listener is still bonded!!!");
m_listenerLock.load()->m_interface = nullptr;
}
}
dropAllConnection();
}
std::shared_ptr<Interface> Interface::obtainShared(const oatpp::String& name) {
std::lock_guard<std::recursive_mutex> lock(m_registryMutex);
auto it = m_registry.find(name);
if(it != m_registry.end()) {
return it->second.lock();
}
std::shared_ptr<Interface> _interface(new Interface(name));
registerInterface(_interface);
return _interface;
}
void Interface::ConnectionSubmission::invalidate() {
m_valid = false;
m_condition.notify_all();
}
void Interface::ConnectionSubmission::setSocket(const std::shared_ptr<Socket>& socket) {
{
std::lock_guard<std::mutex> lock(m_mutex);
m_socket = socket;
}
m_condition.notify_one();
}
std::shared_ptr<Socket> Interface::ConnectionSubmission::getSocket() {
std::unique_lock<std::mutex> lock(m_mutex);
while (!m_socket && m_valid) {
m_condition.wait(lock);
}
return m_socket;
}
std::shared_ptr<Socket> Interface::ConnectionSubmission::getSocketNonBlocking() {
if(m_valid) {
std::unique_lock<std::mutex> lock(m_mutex, std::try_to_lock);
if(lock.owns_lock()) {
return m_socket;
}
}
return nullptr;
}
bool Interface::ConnectionSubmission::isValid() {
return m_valid;
}
std::shared_ptr<Socket> Interface::acceptSubmission(const std::shared_ptr<ConnectionSubmission>& submission) {
auto pipeIn = Pipe::createShared();
auto pipeOut = Pipe::createShared();
auto serverSocket = Socket::createShared(pipeIn, pipeOut);
auto clientSocket = Socket::createShared(pipeOut, pipeIn);
submission->setSocket(clientSocket);
return serverSocket;
}
std::shared_ptr<Interface::ListenerLock> Interface::bind() {
std::lock_guard<std::mutex> lock(m_listenerMutex);
if((void*)m_listenerLock == nullptr) {
m_listenerLock = new ListenerLock(this);
return std::shared_ptr<ListenerLock>(m_listenerLock.load());
}
throw std::runtime_error(
"[oatpp::network::virtual_::Interface::bind()]: Can't bind to interface '" + *m_name + "'. Listener lock is already acquired");
}
void Interface::unbindListener(ListenerLock* listenerLock) {
std::lock_guard<std::mutex> lock(m_listenerMutex);
if((void*)m_listenerLock && m_listenerLock == listenerLock) {
m_listenerLock = nullptr;
dropAllConnection();
} else {
OATPP_LOGE("[oatpp::network::virtual_::Interface::unbindListener()]", "Error! Unbinding wrong listener!!!");
}
}
std::shared_ptr<Interface::ConnectionSubmission> Interface::connect() {
if((void*)m_listenerLock) {
auto submission = std::make_shared<ConnectionSubmission>(true);
{
std::lock_guard<std::mutex> lock(m_mutex);
m_submissions.push_back(submission);
}
m_condition.notify_one();
return submission;
}
return std::make_shared<ConnectionSubmission>(false);
}
std::shared_ptr<Interface::ConnectionSubmission> Interface::connectNonBlocking() {
if((void*)m_listenerLock) {
std::shared_ptr<ConnectionSubmission> submission;
{
std::unique_lock<std::mutex> lock(m_mutex, std::try_to_lock);
if (lock.owns_lock()) {
submission = std::make_shared<ConnectionSubmission>(true);
m_submissions.push_back(submission);
}
}
if (submission) {
m_condition.notify_one();
}
return submission;
}
return std::make_shared<ConnectionSubmission>(false);
}
std::shared_ptr<Socket> Interface::accept(const bool& waitingHandle,
const std::chrono::duration<v_int64, std::micro>& timeout) {
auto startTime = std::chrono::system_clock::now();
std::unique_lock<std::mutex> lock(m_mutex);
while (waitingHandle && m_submissions.empty() && std::chrono::system_clock::now() - startTime < timeout) {
m_condition.wait_for(lock, std::chrono::milliseconds (100));
}
if(!waitingHandle || m_submissions.empty()) {
return nullptr;
}
const auto submission = m_submissions.front();
m_submissions.pop_front();
return acceptSubmission(submission);
}
std::shared_ptr<Socket> Interface::acceptNonBlocking() {
std::unique_lock<std::mutex> lock(m_mutex, std::try_to_lock);
if(lock.owns_lock() && !m_submissions.empty()) {
const auto submission = m_submissions.front();
m_submissions.pop_front();
return acceptSubmission(submission);
}
return nullptr;
}
void Interface::dropAllConnection() {
std::unique_lock<std::mutex> lock(m_mutex);
for (const auto& submission : m_submissions) {
submission->invalidate();
}
m_submissions.clear();
}
void Interface::notifyAcceptors() {
m_condition.notify_all();
}
}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/network/virtual_/Interface.cpp
|
C++
|
apache-2.0
| 7,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_network_virtual__Interface_hpp
#define oatpp_network_virtual__Interface_hpp
#include "./Socket.hpp"
#include <list>
#include <unordered_map>
#include <chrono>
namespace oatpp { namespace network { namespace virtual_ {
/**
* "Virtual" Interface provides functionality for accepting "virtual" connections.
* "virtual" connection is represented by &id:oatpp::network::virtual_::Socket;.
*/
class Interface : public oatpp::base::Countable {
private:
static std::recursive_mutex m_registryMutex;
static std::unordered_map<oatpp::String, std::weak_ptr<Interface>> m_registry;
private:
static void registerInterface(const std::shared_ptr<Interface>& _interface);
static void unregisterInterface(const oatpp::String& name);
public:
/**
* `ListenerLock` is the Lock object, which represents interface binding ownership.
*/
class ListenerLock {
friend Interface;
private:
Interface* m_interface;
private:
ListenerLock(Interface* _interface);
public:
~ListenerLock();
};
public:
/**
* "Future" for &id:oatpp::network::virtual_::Socket;.
*/
class ConnectionSubmission {
friend Interface;
private:
std::shared_ptr<Socket> m_socket;
std::mutex m_mutex;
std::condition_variable m_condition;
std::atomic<bool> m_valid;
private:
void invalidate();
public:
/**
* Constructor.
*/
ConnectionSubmission(bool valid) : m_valid(valid) {}
/**
* Set socket to be returned in call to &l:Interface::ConnectionSubmission::getSocket ();/&l:Interface::ConnectionSubmission::getSocketNonBlocking ();.
* @param socket - &id:oatpp::network::virtual_::Socket;.
*/
void setSocket(const std::shared_ptr<Socket>& socket);
/**
* Block and wait for socket.
* @return - `std::shared_ptr` to &id:oatpp::network::virtual_::Socket;.
*/
std::shared_ptr<Socket> getSocket();
/**
* Check if socket already available.
* User should repeat call if `(!socket && isPending())`.
* @return - `std::shared_ptr` to &id:oatpp::network::virtual_::Socket;.
*/
std::shared_ptr<Socket> getSocketNonBlocking();
/**
* Check if submission is still valid.
* @return - `true` if still valid.
*/
bool isValid();
};
private:
std::shared_ptr<Socket> acceptSubmission(const std::shared_ptr<ConnectionSubmission>& submission);
void unbindListener(ListenerLock* listenerLock);
private:
oatpp::String m_name;
std::atomic<ListenerLock*> m_listenerLock;
std::mutex m_listenerMutex;
std::mutex m_mutex;
std::condition_variable m_condition;
std::list<std::shared_ptr<ConnectionSubmission>> m_submissions;
private:
Interface(const oatpp::String& name);
Interface(const Interface& other) = delete;
Interface(Interface&& other) = delete;
Interface& operator=(const Interface&) = delete;
Interface& operator=(Interface&&) = delete;
public:
/**
* Destructor.
*/
~Interface();
/**
* Obtain interface for given name.
* @param name - name of the interface.
* @return - `std::shared_ptr` to Interface.
*/
static std::shared_ptr<Interface> obtainShared(const oatpp::String& name);
/**
* Aquire &l:Interface::ListenerLock ;.
* @return - `std::shared_ptr` to &l:Interface::ListenerLock ;.
*/
std::shared_ptr<ListenerLock> bind();
/**
* Connect to interface.
* @return - &l:Interface::ConnectionSubmission;.
*/
std::shared_ptr<ConnectionSubmission> connect();
/**
* Connect to interface.
* @return - &l:Interface::ConnectionSubmission; on success. Empty `std::shared_ptr` on failure.
*/
std::shared_ptr<ConnectionSubmission> connectNonBlocking();
/**
* Block and wait for incloming connection.
* @param waitingHandle - reference to a boolean variable.
* User may set waitingHandle = false and call &l:Interface::notifyAcceptors (); in order to break waiting loop. and exit accept() method.
* @param timeout
* @return - `std::shared_ptr` to &id:oatpp::network::virtual_::Socket;.
*/
std::shared_ptr<Socket> accept(const bool& waitingHandle = true,
const std::chrono::duration<v_int64, std::micro>& timeout = std::chrono::minutes (10));
/**
* Check if incoming connection is available. NonBlocking.
* @return - `std::shared_ptr` to &id:oatpp::network::virtual_::Socket; if available.
* Empty `std::shared_ptr` if no incoming connection is available at the moment.
*/
std::shared_ptr<Socket> acceptNonBlocking();
/**
* Drop all waiting connections.
*/
void dropAllConnection();
/**
* Notify all threads that are waiting on accept().
* Those threads that have waitingHandle changed to false will be unblocked.
*/
void notifyAcceptors();
/**
* Get interface name.
* @return - &id:oatpp::String;.
*/
oatpp::String getName() {
return m_name;
}
};
}}}
#endif /* oatpp_network_virtual__Interface_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/network/virtual_/Interface.hpp
|
C++
|
apache-2.0
| 5,959
|
/***************************************************************************
*
* 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 "Pipe.hpp"
namespace oatpp { namespace network { namespace virtual_ {
data::stream::DefaultInitializedContext Pipe::Reader::DEFAULT_CONTEXT(data::stream::StreamType::STREAM_INFINITE);
void Pipe::Reader::setInputStreamIOMode(oatpp::data::stream::IOMode ioMode) {
m_ioMode = ioMode;
}
oatpp::data::stream::IOMode Pipe::Reader::getInputStreamIOMode() {
return m_ioMode;
}
void Pipe::Reader::setMaxAvailableToRead(v_io_size maxAvailableToRead) {
m_maxAvailableToRead = maxAvailableToRead;
}
v_io_size Pipe::Reader::read(void *data, v_buff_size count, async::Action& action) {
if(m_maxAvailableToRead > -1 && count > m_maxAvailableToRead) {
count = m_maxAvailableToRead;
}
Pipe& pipe = *m_pipe;
oatpp::v_io_size result;
if(m_ioMode == oatpp::data::stream::IOMode::ASYNCHRONOUS) {
std::lock_guard<std::mutex> lock(pipe.m_mutex);
if (pipe.m_fifo.availableToRead() > 0) {
result = pipe.m_fifo.read(data, count);
} else if (pipe.m_open) {
action = async::Action::createWaitListAction(&m_waitList);
result = IOError::RETRY_READ;
} else {
result = IOError::BROKEN_PIPE;
}
} else {
std::unique_lock<std::mutex> lock(pipe.m_mutex);
while (pipe.m_fifo.availableToRead() == 0 && pipe.m_open) {
pipe.m_conditionRead.wait(lock);
}
if (pipe.m_fifo.availableToRead() > 0) {
result = pipe.m_fifo.read(data, count);
} else {
result = IOError::BROKEN_PIPE;
}
}
if(result > 0) {
pipe.m_conditionWrite.notify_one();
pipe.m_writer.notifyWaitList();
}
return result;
}
oatpp::data::stream::Context& Pipe::Reader::getInputStreamContext() {
return DEFAULT_CONTEXT;
}
void Pipe::Reader::notifyWaitList() {
m_waitList.notifyAll();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
data::stream::DefaultInitializedContext Pipe::Writer::DEFAULT_CONTEXT(data::stream::StreamType::STREAM_INFINITE);
void Pipe::Writer::setOutputStreamIOMode(oatpp::data::stream::IOMode ioMode) {
m_ioMode = ioMode;
}
oatpp::data::stream::IOMode Pipe::Writer::getOutputStreamIOMode() {
return m_ioMode;
}
oatpp::data::stream::Context& Pipe::Writer::getOutputStreamContext() {
return DEFAULT_CONTEXT;
}
void Pipe::Writer::setMaxAvailableToWrite(v_io_size maxAvailableToWrite) {
m_maxAvailableToWrtie = maxAvailableToWrite;
}
v_io_size Pipe::Writer::write(const void *data, v_buff_size count, async::Action& action) {
if(m_maxAvailableToWrtie > -1 && count > m_maxAvailableToWrtie) {
count = m_maxAvailableToWrtie;
}
Pipe& pipe = *m_pipe;
oatpp::v_io_size result;
if(m_ioMode == oatpp::data::stream::IOMode::ASYNCHRONOUS) {
std::lock_guard<std::mutex> lock(pipe.m_mutex);
if(pipe.m_open) {
if (pipe.m_fifo.availableToWrite() > 0) {
result = pipe.m_fifo.write(data, count);
} else {
action = async::Action::createWaitListAction(&m_waitList);
result = IOError::RETRY_WRITE;
}
} else {
result = IOError::BROKEN_PIPE;
}
} else {
std::unique_lock<std::mutex> lock(pipe.m_mutex);
while (pipe.m_fifo.availableToWrite() == 0 && pipe.m_open) {
pipe.m_conditionWrite.wait(lock);
}
if (pipe.m_open && pipe.m_fifo.availableToWrite() > 0) {
result = pipe.m_fifo.write(data, count);
} else {
result = IOError::BROKEN_PIPE;
}
}
if(result > 0) {
pipe.m_conditionRead.notify_one();
pipe.m_reader.notifyWaitList();
}
return result;
}
void Pipe::Writer::notifyWaitList() {
m_waitList.notifyAll();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Pipe::Pipe()
: m_open(true)
, m_writer(this)
, m_reader(this)
, m_buffer()
, m_fifo(m_buffer.getData(), m_buffer.getSize())
{}
std::shared_ptr<Pipe> Pipe::createShared(){
return std::make_shared<Pipe>();
}
Pipe::~Pipe() {
close();
}
Pipe::Writer* Pipe::getWriter() {
return &m_writer;
}
Pipe::Reader* Pipe::getReader() {
return &m_reader;
}
void Pipe::close() {
{
std::lock_guard<std::mutex> lock(m_mutex);
m_open = false;
}
m_conditionRead.notify_one();
m_reader.notifyWaitList();
m_conditionWrite.notify_one();
m_writer.notifyWaitList();
}
}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/network/virtual_/Pipe.cpp
|
C++
|
apache-2.0
| 5,348
|
/***************************************************************************
*
* 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_network_virtual__Pipe_hpp
#define oatpp_network_virtual__Pipe_hpp
#include "oatpp/core/async/CoroutineWaitList.hpp"
#include "oatpp/core/data/stream/Stream.hpp"
#include "oatpp/core/data/buffer/FIFOBuffer.hpp"
#include "oatpp/core/data/buffer/IOBuffer.hpp"
#include "oatpp/core/concurrency/SpinLock.hpp"
#include <mutex>
#include <condition_variable>
namespace oatpp { namespace network { namespace virtual_ {
/**
* Virtual pipe implementation. Can be used for unidirectional data transfer between different threads of the same process. <br>
* Under the hood it uses &id:oatpp::data::buffer::SynchronizedFIFOBuffer; over the &id:oatpp::data::buffer::IOBuffer;.
*/
class Pipe : public oatpp::base::Countable {
public:
/**
* Pipe Reader. Extends &id:oatpp::data::stream::InputStream;.
* Provides read interface for the pipe. Can work in both blocking and nonblocking regime.
*/
class Reader : public oatpp::data::stream::InputStream {
friend Pipe;
public:
static data::stream::DefaultInitializedContext DEFAULT_CONTEXT;
private:
class WaitListListener : public oatpp::async::CoroutineWaitList::Listener {
private:
Pipe* m_pipe;
public:
WaitListListener(Pipe* pipe)
: m_pipe(pipe)
{}
void onNewItem(oatpp::async::CoroutineWaitList& list) override {
std::lock_guard<std::mutex> lock(m_pipe->m_mutex);
if (m_pipe->m_fifo.availableToRead() > 0 || !m_pipe->m_open) {
list.notifyAll();
}
}
};
private:
Pipe* m_pipe;
oatpp::data::stream::IOMode m_ioMode;
/*
* this one used for testing purposes only
*/
v_io_size m_maxAvailableToRead;
oatpp::async::CoroutineWaitList m_waitList;
WaitListListener m_waitListListener;
protected:
Reader(Pipe* pipe, oatpp::data::stream::IOMode ioMode = oatpp::data::stream::IOMode::BLOCKING)
: m_pipe(pipe)
, m_ioMode(ioMode)
, m_maxAvailableToRead(-1)
, m_waitListListener(pipe)
{
m_waitList.setListener(&m_waitListListener);
}
public:
/**
* Limit the available amount of bytes to read from pipe.<br>
* This method is used for testing purposes only.<br>
* set to -1 in order to ignore this value.<br>
* @param maxAvailableToRead - maximum available amount of bytes to read.
*/
void setMaxAvailableToRead(v_io_size maxAvailableToRead);
/**
* Implements &id:oatpp::data::stream::InputStream::read; method.
* Read data from pipe.
* @param data - buffer to read data to.
* @param count - max count of bytes to read.
* @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 - &id:oatpp::v_io_size;.
*/
v_io_size read(void *data, v_buff_size count, async::Action& action) override;
/**
* Set InputStream I/O mode.
* @param ioMode
*/
void setInputStreamIOMode(oatpp::data::stream::IOMode ioMode) override;
/**
* Get InputStream I/O mode.
* @return
*/
oatpp::data::stream::IOMode getInputStreamIOMode() override;
/**
* Get stream context.
* @return
*/
oatpp::data::stream::Context& getInputStreamContext() override;
/**
* Notify coroutine wait-list
*/
void notifyWaitList();
};
/**
* Pipe writer. Extends &id:oatpp::data::stream::OutputStream;.
* Provides write interface for the pipe. Can work in both blocking and nonblocking regime.
*/
class Writer : public oatpp::data::stream::OutputStream {
friend Pipe;
public:
static data::stream::DefaultInitializedContext DEFAULT_CONTEXT;
private:
class WaitListListener : public oatpp::async::CoroutineWaitList::Listener {
private:
Pipe* m_pipe;
public:
WaitListListener(Pipe* pipe)
: m_pipe(pipe)
{}
void onNewItem(oatpp::async::CoroutineWaitList& list) override {
std::lock_guard<std::mutex> lock(m_pipe->m_mutex);
if (m_pipe->m_fifo.availableToWrite() > 0 || !m_pipe->m_open) {
list.notifyAll();
}
}
};
private:
Pipe* m_pipe;
oatpp::data::stream::IOMode m_ioMode;
/*
* this one used for testing purposes only
*/
v_io_size m_maxAvailableToWrtie;
oatpp::async::CoroutineWaitList m_waitList;
WaitListListener m_waitListListener;
protected:
Writer(Pipe* pipe, oatpp::data::stream::IOMode ioMode = oatpp::data::stream::IOMode::BLOCKING)
: m_pipe(pipe)
, m_ioMode(ioMode)
, m_maxAvailableToWrtie(-1)
, m_waitListListener(pipe)
{
m_waitList.setListener(&m_waitListListener);
}
public:
/**
* Limit the available space for data writes in pipe.<br>
* This method is used for testing purposes only.<br>
* set to -1 in order to ignore this value.<br>
* @param maxAvailableToWrite - maximum available amount of bytes to write.
*/
void setMaxAvailableToWrite(v_io_size maxAvailableToWrite);
/**
* Implements &id:oatpp::data::stream::OutputStream::write; method.
* Write data to pipe.
* @param data - data to write to pipe.
* @param count - data size.
* @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 - &id:oatpp::v_io_size;.
*/
v_io_size write(const void *data, v_buff_size count, async::Action& action) override;
/**
* Set OutputStream I/O mode.
* @param ioMode
*/
void setOutputStreamIOMode(oatpp::data::stream::IOMode ioMode) override;
/**
* Set OutputStream I/O mode.
* @return
*/
oatpp::data::stream::IOMode getOutputStreamIOMode() override;
/**
* Get stream context.
* @return
*/
oatpp::data::stream::Context& getOutputStreamContext() override;
/**
* Notify coroutine wait-list
*/
void notifyWaitList();
};
private:
bool m_open;
Writer m_writer;
Reader m_reader;
oatpp::data::buffer::IOBuffer m_buffer;
oatpp::data::buffer::SynchronizedFIFOBuffer m_fifo;
std::mutex m_mutex;
std::condition_variable m_conditionRead;
std::condition_variable m_conditionWrite;
public:
/**
* Constructor.
*/
Pipe();
/**
* Create shared pipe.
* @return - `std::shared_ptr` to Pipe.
*/
static std::shared_ptr<Pipe> createShared();
/**
* Virtual destructor.
*/
virtual ~Pipe();
/**
* Get pointer to &l:Pipe::Writer; for this pipe.
* There can be only one &l:Pipe::Writer; per pipe.
* @return - &l:Pipe::Writer;.
*/
Writer* getWriter();
/**
* Get pointer to &l:Pipe::Reader; for this pipe.
* There can be only one &l:Pipe::Reader; per pipe.
* @return - &l:Pipe::Reader;.
*/
Reader* getReader();
/**
* Mark pipe as closed.
*/
void close();
};
}}}
#endif /* oatpp_network_virtual__Pipe_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/network/virtual_/Pipe.hpp
|
C++
|
apache-2.0
| 8,064
|
/***************************************************************************
*
* 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 "Socket.hpp"
namespace oatpp { namespace network { namespace virtual_ {
Socket::Socket(const std::shared_ptr<Pipe>& pipeIn, const std::shared_ptr<Pipe>& pipeOut)
: m_pipeIn(pipeIn)
, m_pipeOut(pipeOut)
{}
Socket::~Socket() {
close();
}
std::shared_ptr<Socket> Socket::createShared(const std::shared_ptr<Pipe>& pipeIn, const std::shared_ptr<Pipe>& pipeOut) {
return std::make_shared<Socket>(pipeIn, pipeOut);
}
void Socket::setMaxAvailableToReadWrtie(v_io_size maxToRead, v_io_size maxToWrite) {
m_pipeIn->getReader()->setMaxAvailableToRead(maxToRead);
m_pipeOut->getWriter()->setMaxAvailableToWrite(maxToWrite);
}
v_io_size Socket::read(void *data, v_buff_size count, async::Action& action) {
return m_pipeIn->getReader()->read(data, count, action);
}
v_io_size Socket::write(const void *data, v_buff_size count, async::Action& action) {
return m_pipeOut->getWriter()->write(data, count, action);
}
void Socket::setOutputStreamIOMode(oatpp::data::stream::IOMode ioMode) {
m_pipeOut->getWriter()->setOutputStreamIOMode(ioMode);
}
oatpp::data::stream::IOMode Socket::getOutputStreamIOMode() {
return m_pipeOut->getWriter()->getOutputStreamIOMode();
}
void Socket::setInputStreamIOMode(oatpp::data::stream::IOMode ioMode) {
m_pipeIn->getReader()->setInputStreamIOMode(ioMode);
}
oatpp::data::stream::IOMode Socket::getInputStreamIOMode() {
return m_pipeIn->getReader()->getInputStreamIOMode();
}
oatpp::data::stream::Context& Socket::getOutputStreamContext() {
return m_pipeOut->getWriter()->getOutputStreamContext();
}
oatpp::data::stream::Context& Socket::getInputStreamContext() {
return m_pipeIn->getReader()->getInputStreamContext();
}
void Socket::close() {
m_pipeIn->close();
m_pipeOut->close();
}
}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/network/virtual_/Socket.cpp
|
C++
|
apache-2.0
| 2,763
|
/***************************************************************************
*
* 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_network_virtual__Socket_hpp
#define oatpp_network_virtual__Socket_hpp
#include "./Pipe.hpp"
namespace oatpp { namespace network { namespace virtual_ {
/**
* Virtual socket implementation. Can be used as a bidirectional data transfer between different threads of the same process. <br>
* Under the hood it uses a pair of &id:oatpp::network::virtual_::Pipe;. One to write data to, and one to read data from.
* Extends &id:oatpp::base::Countable; and &id:oatpp::data::stream::IOStream;.
*/
class Socket : public oatpp::data::stream::IOStream, public oatpp::base::Countable {
private:
std::shared_ptr<Pipe> m_pipeIn;
std::shared_ptr<Pipe> m_pipeOut;
public:
/**
* Constructor.
* @param pipeIn - pipe to read data from.
* @param pipeOut - pipe to write data to.
*/
Socket(const std::shared_ptr<Pipe>& pipeIn, const std::shared_ptr<Pipe>& pipeOut);
public:
/**
* Create shared socket.
* @param pipeIn - pipe to read data from.
* @param pipeOut - pipe to write data to.
* @return - `std::shared_ptr` to Socket.
*/
static std::shared_ptr<Socket> createShared(const std::shared_ptr<Pipe>& pipeIn, const std::shared_ptr<Pipe>& pipeOut);
/**
* Virtual destructor. Close corresponding pipes.
*/
~Socket();
/**
* Limit the available amount of bytes to read from socket and limit the available amount of bytes to write to socket. <br>
* This method is used for testing purposes only.<br>
* @param maxToRead - maximum available amount of bytes to read.
* @param maxToWrite - maximum available amount of bytes to write.
*/
void setMaxAvailableToReadWrtie(v_io_size maxToRead, v_io_size maxToWrite);
/**
* Read data from socket.
* @param data - buffer to read data to.
* @param count - buffer size.
* @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 amount of data read from socket.
*/
v_io_size read(void *data, v_buff_size count, async::Action& action) override;
/**
* Write data to socket.
* @param data - data to write to socket.
* @param count - data size.
* @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 amount of data written to socket.
*/
v_io_size write(const void *data, v_buff_size count, async::Action& action) override;
/**
* Set OutputStream I/O mode.
* @param ioMode
*/
void setOutputStreamIOMode(oatpp::data::stream::IOMode ioMode) override;
/**
* Set OutputStream I/O mode.
* @return
*/
oatpp::data::stream::IOMode getOutputStreamIOMode() override;
/**
* Set InputStream I/O mode.
* @param ioMode
*/
void setInputStreamIOMode(oatpp::data::stream::IOMode ioMode) override;
/**
* Get InputStream I/O mode.
* @return
*/
oatpp::data::stream::IOMode getInputStreamIOMode() override;
/**
* Get output stream context.
* @return
*/
oatpp::data::stream::Context& getOutputStreamContext() override;
/**
* Get input stream context.
* @return
*/
oatpp::data::stream::Context& getInputStreamContext() override;
/**
* Close socket pipes.
*/
void close();
};
}}}
#endif /* oatpp_network_virtual__Socket_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/network/virtual_/Socket.hpp
|
C++
|
apache-2.0
| 4,392
|
/***************************************************************************
*
* 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 "ConnectionProvider.hpp"
namespace oatpp { namespace network { namespace virtual_ { namespace client {
void ConnectionProvider::ConnectionInvalidator::invalidate(const std::shared_ptr<data::stream::IOStream>& connection) {
auto socket = std::static_pointer_cast<Socket>(connection);
socket->close();
}
ConnectionProvider::ConnectionProvider(const std::shared_ptr<virtual_::Interface>& _interface)
: m_invalidator(std::make_shared<ConnectionInvalidator>())
, m_interface(_interface)
, m_maxAvailableToRead(-1)
, m_maxAvailableToWrite(-1)
{
setProperty(PROPERTY_HOST, m_interface->getName());
setProperty(PROPERTY_PORT, "0");
}
std::shared_ptr<ConnectionProvider> ConnectionProvider::createShared(const std::shared_ptr<virtual_::Interface>& _interface) {
return std::make_shared<ConnectionProvider>(_interface);
}
void ConnectionProvider::stop() {
}
provider::ResourceHandle<data::stream::IOStream> ConnectionProvider::get() {
auto submission = m_interface->connect();
if(submission->isValid()) {
auto socket = submission->getSocket();
if (socket) {
socket->setOutputStreamIOMode(oatpp::data::stream::IOMode::BLOCKING);
socket->setInputStreamIOMode(oatpp::data::stream::IOMode::BLOCKING);
socket->setMaxAvailableToReadWrtie(m_maxAvailableToRead, m_maxAvailableToWrite);
return provider::ResourceHandle<data::stream::IOStream>(socket, m_invalidator);
}
}
throw std::runtime_error("[oatpp::network::virtual_::client::getConnection()]: Error. Can't connect. " + *m_interface->getName());
}
oatpp::async::CoroutineStarterForResult<const provider::ResourceHandle<data::stream::IOStream>&>
ConnectionProvider::getAsync() {
class ConnectCoroutine : public oatpp::async::CoroutineWithResult<ConnectCoroutine, const provider::ResourceHandle<oatpp::data::stream::IOStream>&> {
private:
std::shared_ptr<ConnectionInvalidator> m_invalidator;
std::shared_ptr<virtual_::Interface> m_interface;
v_io_size m_maxAvailableToRead;
v_io_size m_maxAvailableToWrite;
std::shared_ptr<virtual_::Interface::ConnectionSubmission> m_submission;
public:
ConnectCoroutine(const std::shared_ptr<ConnectionInvalidator>& invalidator,
const std::shared_ptr<virtual_::Interface>& _interface,
v_io_size maxAvailableToRead,
v_io_size maxAvailableToWrite)
: m_invalidator(invalidator)
, m_interface(_interface)
, m_maxAvailableToRead(maxAvailableToRead)
, m_maxAvailableToWrite(maxAvailableToWrite)
{}
Action act() override {
m_submission = m_interface->connectNonBlocking();
if(m_submission){
return yieldTo(&ConnectCoroutine::obtainSocket);
}
return waitRepeat(std::chrono::milliseconds(100));
}
Action obtainSocket() {
if(m_submission->isValid()) {
auto socket = m_submission->getSocketNonBlocking();
if(socket) {
socket->setOutputStreamIOMode(oatpp::data::stream::IOMode::ASYNCHRONOUS);
socket->setInputStreamIOMode(oatpp::data::stream::IOMode::ASYNCHRONOUS);
socket->setMaxAvailableToReadWrtie(m_maxAvailableToRead, m_maxAvailableToWrite);
return _return(provider::ResourceHandle<data::stream::IOStream>(socket, m_invalidator));
}
return waitRepeat(std::chrono::milliseconds(100));
}
return error<Error>("[oatpp::network::virtual_::client::ConnectionProvider::getConnectionAsync()]: Error. Can't connect.");
}
};
return ConnectCoroutine::startForResult(m_invalidator, m_interface, m_maxAvailableToRead, m_maxAvailableToWrite);
}
}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/network/virtual_/client/ConnectionProvider.cpp
|
C++
|
apache-2.0
| 4,674
|
/***************************************************************************
*
* 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_network_virtual__client_ConnectionProvider_hpp
#define oatpp_network_virtual__client_ConnectionProvider_hpp
#include "oatpp/network/virtual_/Interface.hpp"
#include "oatpp/network/ConnectionProvider.hpp"
namespace oatpp { namespace network { namespace virtual_ { namespace client {
/**
* Provider of "virtual" connections for client.
* See &id:oatpp::network::virtual_::Interface;, &id:oatpp::network::virtual_::Socket; <br>
* Extends &id:oatpp::network::ClientConnectionProvider;.
*/
class ConnectionProvider : public oatpp::network::ClientConnectionProvider {
private:
class ConnectionInvalidator : public provider::Invalidator<data::stream::IOStream> {
public:
void invalidate(const std::shared_ptr<data::stream::IOStream>& connection) override;
};
private:
std::shared_ptr<ConnectionInvalidator> m_invalidator;
private:
std::shared_ptr<virtual_::Interface> m_interface;
v_io_size m_maxAvailableToRead;
v_io_size m_maxAvailableToWrite;
public:
/**
* Constructor.
* @param interface - &id:oatpp::network::virtual_::Interface;.
*/
ConnectionProvider(const std::shared_ptr<virtual_::Interface>& _interface);
/**
* Create shared ConnectionProvider.
* @param interface - &id:oatpp::network::virtual_::Interface;.
* @return - `std::shared_ptr` to ConnectionProvider.
*/
static std::shared_ptr<ConnectionProvider> createShared(const std::shared_ptr<virtual_::Interface>& _interface);
/**
* Limit the available amount of bytes to read from socket and limit the available amount of bytes to write to socket. <br>
* This method is used for testing purposes only.<br>
* @param maxToRead - maximum available amount of bytes to read.
* @param maxToWrite - maximum available amount of bytes to write.
*/
void setSocketMaxAvailableToReadWrtie(v_io_size maxToRead, v_io_size maxToWrite) {
m_maxAvailableToRead = maxToRead;
m_maxAvailableToWrite = maxToWrite;
}
/**
* Implementation of &id:oatpp::provider::Provider::Stop; method.
*/
void stop() override;
/**
* Get connection.
* @return - `std::shared_ptr` to &id:oatpp::data::stream::IOStream;.
*/
provider::ResourceHandle<data::stream::IOStream> get() override;
/**
* Get connection in asynchronous manner.
* @return - &id:oatpp::async::CoroutineStarterForResult;.
*/
oatpp::async::CoroutineStarterForResult<const provider::ResourceHandle<data::stream::IOStream>&> getAsync() override;
};
}}}}
#endif /* oatpp_network_virtual__client_ConnectionProvider_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/network/virtual_/client/ConnectionProvider.hpp
|
C++
|
apache-2.0
| 3,543
|
/***************************************************************************
*
* 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 "ConnectionProvider.hpp"
#include <chrono>
namespace oatpp { namespace network { namespace virtual_ { namespace server {
void ConnectionProvider::ConnectionInvalidator::invalidate(const std::shared_ptr<data::stream::IOStream>& connection) {
auto socket = std::static_pointer_cast<Socket>(connection);
socket->close();
}
ConnectionProvider::ConnectionProvider(const std::shared_ptr<virtual_::Interface>& _interface)
: m_invalidator(std::make_shared<ConnectionInvalidator>())
, m_interface(_interface)
, m_listenerLock(_interface->bind())
, m_open(true)
, m_maxAvailableToRead(-1)
, m_maxAvailableToWrite(-1)
{
setProperty(PROPERTY_HOST, m_interface->getName());
setProperty(PROPERTY_PORT, "0");
}
std::shared_ptr<ConnectionProvider> ConnectionProvider::createShared(const std::shared_ptr<virtual_::Interface>& _interface) {
return std::make_shared<ConnectionProvider>(_interface);
}
void ConnectionProvider::setSocketMaxAvailableToReadWrtie(v_io_size maxToRead, v_io_size maxToWrite) {
m_maxAvailableToRead = maxToRead;
m_maxAvailableToWrite = maxToWrite;
}
void ConnectionProvider::stop() {
m_open = false;
m_listenerLock.reset();
m_interface->notifyAcceptors();
}
provider::ResourceHandle<data::stream::IOStream> ConnectionProvider::get() {
auto socket = m_interface->accept(m_open, std::chrono::milliseconds(500));
if(socket) {
socket->setMaxAvailableToReadWrtie(m_maxAvailableToRead, m_maxAvailableToWrite);
}
return provider::ResourceHandle<data::stream::IOStream>(socket, m_invalidator);
}
}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/network/virtual_/server/ConnectionProvider.cpp
|
C++
|
apache-2.0
| 2,558
|
/***************************************************************************
*
* 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_network_virtual__server_ConnectionProvider_hpp
#define oatpp_network_virtual__server_ConnectionProvider_hpp
#include "oatpp/network/virtual_/Interface.hpp"
#include "oatpp/network/ConnectionProvider.hpp"
namespace oatpp { namespace network { namespace virtual_ { namespace server {
/**
* Provider of "virtual" connections.
* See &id:oatpp::network::virtual_::Interface;, &id:oatpp::network::virtual_::Socket; <br>
* Extends &id:oatpp::network::ServerConnectionProvider;.
*/
class ConnectionProvider : public oatpp::network::ServerConnectionProvider {
private:
class ConnectionInvalidator : public provider::Invalidator<data::stream::IOStream> {
public:
void invalidate(const std::shared_ptr<data::stream::IOStream>& connection) override;
};
private:
std::shared_ptr<ConnectionInvalidator> m_invalidator;
std::shared_ptr<virtual_::Interface> m_interface;
std::shared_ptr<virtual_::Interface::ListenerLock> m_listenerLock;
bool m_open;
v_io_size m_maxAvailableToRead;
v_io_size m_maxAvailableToWrite;
public:
/**
* Constructor.
* @param interface - &id:oatpp::network::virtual_::Interface;.
*/
ConnectionProvider(const std::shared_ptr<virtual_::Interface>& _interface);
/**
* Create shared ConnectionProvider.
* @param interface - &id:oatpp::network::virtual_::Interface;.
* @return - `std::shared_ptr` to ConnectionProvider.
*/
static std::shared_ptr<ConnectionProvider> createShared(const std::shared_ptr<virtual_::Interface>& _interface);
/**
* Limit the available amount of bytes to read from socket and limit the available amount of bytes to write to socket. <br>
* This method is used for testing purposes only.<br>
* @param maxToRead - maximum available amount of bytes to read.
* @param maxToWrite - maximum available amount of bytes to write.
*/
void setSocketMaxAvailableToReadWrtie(v_io_size maxToRead, v_io_size maxToWrite);
/**
* Break accepting loop.
*/
void stop() override;
/**
* Get incoming connection.
* @return &id:oatpp::data::stream::IOStream;.
*/
provider::ResourceHandle<data::stream::IOStream> get() override;
/**
* **NOT IMPLEMENTED!**<br>
* No need to implement this.<br>
* For Asynchronous IO in oatpp it is considered to be a good practice
* to accept connections in a seperate thread with the blocking accept()
* and then process connections in Asynchronous manner with non-blocking read/write.
* <br>
* *It may be implemented later.*
*/
oatpp::async::CoroutineStarterForResult<const provider::ResourceHandle<data::stream::IOStream>&> getAsync() override {
/*
* No need to implement this.
* For Asynchronous IO in oatpp it is considered to be a good practice
* to accept connections in a seperate thread with the blocking accept()
* and then process connections in Asynchronous manner with non-blocking read/write
*
* It may be implemented later
*/
throw std::runtime_error("[oatpp::network::virtual_::server::ConnectionProvider::getConnectionAsync()]: Error. Not implemented.");
}
};
}}}}
#endif /* oatpp_network_virtual__server_ConnectionProvider_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/network/virtual_/server/ConnectionProvider.hpp
|
C++
|
apache-2.0
| 4,189
|
/***************************************************************************
*
* 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_orm_Connection_hpp
#define oatpp_orm_Connection_hpp
#include "oatpp/core/base/Countable.hpp"
namespace oatpp { namespace orm {
/**
* Abstract database connection.
*/
class Connection : public base::Countable {
public:
/**
* Virtual destructor.
*/
virtual ~Connection() = default;
};
}}
#endif // oatpp_orm_Connection_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/orm/Connection.hpp
|
C++
|
apache-2.0
| 1,350
|
/***************************************************************************
*
* 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 "DbClient.hpp"
#include "oatpp/core/data/stream/BufferStream.hpp"
namespace oatpp { namespace orm {
DbClient::DbClient(const std::shared_ptr<Executor>& executor)
: m_executor(executor)
, m_typeResolver(executor->createTypeResolver())
{}
provider::ResourceHandle<Connection> DbClient::getConnection() {
return m_executor->getConnection();
}
void DbClient::setEnabledInterpretations(const std::vector<std::string>& enabledInterpretations) {
m_typeResolver->setEnabledInterpretations(enabledInterpretations);
}
std::shared_ptr<const data::mapping::TypeResolver> DbClient::getTypeResolver() {
return m_typeResolver;
}
data::share::StringTemplate DbClient::parseQueryTemplate(const oatpp::String& name,
const oatpp::String& text,
const Executor::ParamsTypeMap& paramsTypeMap,
bool prepare)
{
return m_executor->parseQueryTemplate(name, text, paramsTypeMap, prepare);
}
std::shared_ptr<QueryResult> DbClient::execute(const data::share::StringTemplate& queryTemplate,
const std::unordered_map<oatpp::String, oatpp::Void>& params,
const provider::ResourceHandle<Connection>& connection)
{
return m_executor->execute(queryTemplate, params, m_typeResolver, connection);
}
std::shared_ptr<QueryResult> DbClient::executeQuery(const oatpp::String& query,
const std::unordered_map<oatpp::String, oatpp::Void>& params,
const provider::ResourceHandle<Connection>& connection)
{
return m_executor->execute(query, params, m_typeResolver, connection);
}
Transaction DbClient::beginTransaction(const provider::ResourceHandle<Connection>& connection) {
return Transaction(m_executor, connection);
}
}}
|
vincent-in-black-sesame/oat
|
src/oatpp/orm/DbClient.cpp
|
C++
|
apache-2.0
| 2,984
|
/***************************************************************************
*
* 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_orm_DbClient_hpp
#define oatpp_orm_DbClient_hpp
#include "Executor.hpp"
#include "Transaction.hpp"
#include "oatpp/core/data/stream/Stream.hpp"
#include "oatpp/core/Types.hpp"
namespace oatpp { namespace orm {
/**
* Database client.
*/
class DbClient {
private:
std::shared_ptr<Executor> m_executor;
protected:
std::shared_ptr<data::mapping::TypeResolver> m_typeResolver;
public:
/**
* Constructor.
* @param executor - &id:oatpp::orm::Executor;.
*/
DbClient(const std::shared_ptr<Executor>& executor);
/**
* Virtual destructor.
*/
virtual ~DbClient() = default;
/**
* Get database connection.
* @return
*/
provider::ResourceHandle<Connection> getConnection();
/**
* Set enabled type interpretations.
* @param enabledInterpretations
*/
void setEnabledInterpretations(const std::vector<std::string>& enabledInterpretations);
/**
* Get type resolver.
* @return - &id:oatpp::data::mapping::TypeResolver;.
*/
std::shared_ptr<const data::mapping::TypeResolver> getTypeResolver();
/**
* Parse query template.
* @param name - template name.
* @param text - template text.
* @param paramsTypeMap - template parameter types.
* @param prepare - `true` if the query should use prepared statement, `false` otherwise.
* @return - &id:oatpp::data::share::StringTemplate;.
*/
data::share::StringTemplate parseQueryTemplate(const oatpp::String& name,
const oatpp::String& text,
const Executor::ParamsTypeMap& paramsTypeMap,
bool prepare = false);
/**
* Execute query using template.
* @param queryTemplate - a query template obtained in a prior call to &l:DbClient::parseQueryTemplate (); method.
* @param params - query parameters.
* @param connection - database connection.
* @return - &id:oatpp::orm::QueryResult;.
*/
std::shared_ptr<QueryResult> execute(const data::share::StringTemplate& queryTemplate,
const std::unordered_map<oatpp::String, oatpp::Void>& params,
const provider::ResourceHandle<Connection>& connection = nullptr);
/**
* Execute arbitrary query.
* @param query - query text.
* @param params - query parameters.
* @param connection - database connection.
* @return - &id:oatpp::orm::QueryResult;.
*/
std::shared_ptr<QueryResult> executeQuery(const oatpp::String& query,
const std::unordered_map<oatpp::String, oatpp::Void>& params,
const provider::ResourceHandle<Connection>& connection = nullptr);
/**
* Begin database transaction.
* @param connection - database connection.
* @return - &id:oatpp::orm::Transaction;.
*/
Transaction beginTransaction(const provider::ResourceHandle<Connection>& connection = nullptr);
};
}}
#endif // oatpp_orm_DbClient_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/orm/DbClient.hpp
|
C++
|
apache-2.0
| 4,052
|
/***************************************************************************
*
* 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 "Executor.hpp"
namespace oatpp { namespace orm {
Executor::Executor()
: m_defaultTypeResolver(std::make_shared<data::mapping::TypeResolver>())
{}
std::shared_ptr<const data::mapping::TypeResolver> Executor::getDefaultTypeResolver() {
return m_defaultTypeResolver;
}
std::shared_ptr<QueryResult> Executor::execute(const oatpp::String& query,
const std::unordered_map<oatpp::String, oatpp::Void>& params,
const std::shared_ptr<const data::mapping::TypeResolver>& typeResolver,
const provider::ResourceHandle<Connection>& connection)
{
const auto& qt = parseQueryTemplate(nullptr, query, ParamsTypeMap(), false);
return execute(qt, params, typeResolver, connection);
}
}}
|
vincent-in-black-sesame/oat
|
src/oatpp/orm/Executor.cpp
|
C++
|
apache-2.0
| 1,828
|
/***************************************************************************
*
* 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_orm_Executor_hpp
#define oatpp_orm_Executor_hpp
#include "Connection.hpp"
#include "QueryResult.hpp"
#include "oatpp/core/data/mapping/TypeResolver.hpp"
#include "oatpp/core/data/mapping/type/Type.hpp"
#include "oatpp/core/data/share/MemoryLabel.hpp"
#include "oatpp/core/data/share/StringTemplate.hpp"
namespace oatpp { namespace orm {
/**
* Database executor.
*/
class Executor {
public:
typedef oatpp::data::share::StringTemplate StringTemplate;
typedef std::unordered_map<data::share::StringKeyLabel, const oatpp::Type*> ParamsTypeMap;
protected:
std::shared_ptr<data::mapping::TypeResolver> m_defaultTypeResolver;
public:
/**
* Default constructor.
*/
Executor();
/**
* Default virtual destructor.
*/
virtual ~Executor() = default;
/**
* Get default type resolver.
* @return
*/
std::shared_ptr<const data::mapping::TypeResolver> getDefaultTypeResolver();
/**
* Create new type resolver.
* @return
*/
virtual std::shared_ptr<data::mapping::TypeResolver> createTypeResolver() = 0;
/**
* Get database connection.
* @return
*/
virtual provider::ResourceHandle<Connection> getConnection() = 0;
/**
* Parse query template.
* @param name - template name.
* @param text - template text.
* @param paramsTypeMap - template parameter types.
* @param prepare - `true` if the query should use prepared statement, `false` otherwise.
* @return - &id:oatpp::data::share::StringTemplate;.
*/
virtual StringTemplate parseQueryTemplate(const oatpp::String& name,
const oatpp::String& text,
const ParamsTypeMap& paramsTypeMap,
bool prepare = false) = 0;
/**
* Execute database query using a query template.
* @param queryTemplate - a query template obtained in a prior call to &l:Executor::parseQueryTemplate (); method.
* @param params - query parameters.
* @param enabledInterpretations - enabled type interpretations.
* @param connection - database connection.
* @return - &id:oatpp::orm::QueryResult;.
*/
virtual std::shared_ptr<QueryResult> execute(const StringTemplate& queryTemplate,
const std::unordered_map<oatpp::String, oatpp::Void>& params,
const std::shared_ptr<const data::mapping::TypeResolver>& typeResolver = nullptr,
const provider::ResourceHandle<Connection>& connection = nullptr) = 0;
/**
* Execute an arbitrary database query. <br>
* In its default implementation it'll call execute with the null-named query template.
* The query template will be created by a call to `parseQueryTemplate(nullptr, query, {}, false)`.
* @param query - query text.
* @param params - query parameters.
* @param enabledInterpretations - enabled type interpretations.
* @param connection - database connection.
* @return - &id:oatpp::orm::QueryResult;.
*/
virtual std::shared_ptr<QueryResult> execute(const oatpp::String& query,
const std::unordered_map<oatpp::String, oatpp::Void>& params,
const std::shared_ptr<const data::mapping::TypeResolver>& typeResolver = nullptr,
const provider::ResourceHandle<Connection>& connection = nullptr);
/**
* Begin database transaction. Should NOT be used directly. Use &id:oatpp::orm::Transaction; instead.
* @param connection - database connection.
* @return - &id:oatpp::orm::QueryResult;.
*/
virtual std::shared_ptr<QueryResult> begin(const provider::ResourceHandle<Connection>& connection = nullptr) = 0;
/**
* Commit database transaction. Should NOT be used directly. Use &id:oatpp::orm::Transaction; instead.
* @param connection
* @return - &id:oatpp::orm::QueryResult;.
*/
virtual std::shared_ptr<QueryResult> commit(const provider::ResourceHandle<Connection>& connection) = 0;
/**
* Rollback database transaction. Should NOT be used directly. Use &id:oatpp::orm::Transaction; instead.
* @param connection
* @return - &id:oatpp::orm::QueryResult;.
*/
virtual std::shared_ptr<QueryResult> rollback(const provider::ResourceHandle<Connection>& connection) = 0;
/**
* Get current database schema version.
* @param suffix - suffix of schema version control table name.
* @param connection - database connection.
* @return - schema version.
*/
virtual v_int64 getSchemaVersion(const oatpp::String& suffix = nullptr,
const provider::ResourceHandle<Connection>& connection = nullptr) = 0;
/**
* Run schema migration script. Should NOT be used directly. Use &id:oatpp::orm::SchemaMigration; instead.
* @param script - script text.
* @param newVersion - schema version corresponding to this script.
* @param suffix - suffix of schema version control table name.
* @param connection - database connection.
*/
virtual void migrateSchema(const oatpp::String& script,
v_int64 newVersion,
const oatpp::String& suffix = nullptr,
const provider::ResourceHandle<Connection>& connection = nullptr) = 0;
};
}}
#endif // oatpp_orm_Executor_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/orm/Executor.hpp
|
C++
|
apache-2.0
| 6,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 "QueryResult.hpp"
namespace oatpp { namespace orm {
}}
|
vincent-in-black-sesame/oat
|
src/oatpp/orm/QueryResult.cpp
|
C++
|
apache-2.0
| 1,063
|
/***************************************************************************
*
* 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_orm_QueryResult_hpp
#define oatpp_orm_QueryResult_hpp
#include "Connection.hpp"
#include "oatpp/core/provider/Provider.hpp"
#include "oatpp/core/Types.hpp"
namespace oatpp { namespace orm {
/**
* Result of DB query.
*/
class QueryResult {
public:
/**
* Virtual destructor.
*/
virtual ~QueryResult() = default;
/**
* Get DB connection associated with this result.
* @return
*/
virtual provider::ResourceHandle<Connection> getConnection() const = 0;
/**
* Check if the query was successful.
* @return
*/
virtual bool isSuccess() const = 0;
/**
* Get error message in case `isSuccess() == false`
* @return
*/
virtual oatpp::String getErrorMessage() const = 0;
/**
* Get result read position.
* @return
*/
virtual v_int64 getPosition() const = 0;
/**
* Get result entries count in the case it's known.
* @return - `[0..N]` - in case known. `-1` - otherwise.
*/
virtual v_int64 getKnownCount() const = 0;
/**
* Check if there is more data to fetch.
* @return
*/
virtual bool hasMoreToFetch() const = 0;
/**
* Fetch result entries.
* @param resultType - wanted output type.
* @param count - how many entries to fetch. Use `-1` to fetch all.
* @return - `oatpp::Void`.
*/
virtual oatpp::Void fetch(const oatpp::Type* const resultType, v_int64 count) = 0;
/**
* Fetch result entries.
* @tparam Wrapper - output type.
* @param count - how many entries to fetch. Use `-1` to fetch all.
* @return - `Wrapper`.
*/
template<class Wrapper>
Wrapper fetch(v_int64 count = -1) {
return fetch(Wrapper::Class::getType(), count).template cast<Wrapper>();
}
};
}}
#endif // oatpp_orm_QueryResult_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/orm/QueryResult.hpp
|
C++
|
apache-2.0
| 2,740
|
/***************************************************************************
*
* 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 "SchemaMigration.hpp"
#include <algorithm>
namespace oatpp { namespace orm {
SchemaMigration::SchemaMigration(const base::ObjectHandle<Executor>& executor, const oatpp::String& suffix)
: m_executor(executor)
, m_suffix(suffix)
{}
void SchemaMigration::addText(v_int64 version, const oatpp::String& script) {
m_scripts.push_back({version, SOURCE_TEXT, script});
}
void SchemaMigration::addFile(v_int64 version, const oatpp::String& filename) {
m_scripts.push_back({version, SOURCE_FILE, filename});
}
void SchemaMigration::migrate() {
if(!m_executor) {
throw std::runtime_error("[oatpp::orm::SchemaMigration::migrate()]: Error. Executor is null.");
}
auto connection = m_executor->getConnection();
if(!connection) {
throw std::runtime_error("[oatpp::orm::SchemaMigration::migrate()]: Error. Can't connect to Database.");
}
v_int64 currVersion = m_executor->getSchemaVersion(m_suffix, connection);
std::sort(m_scripts.begin(), m_scripts.end(), [](const Source& a, const Source& b) {
return a.version < b.version;
});
for(auto& source : m_scripts) {
if(source.version > currVersion) {
oatpp::String script;
switch (source.type) {
case SOURCE_TEXT:
script = source.param;
break;
case SOURCE_FILE:
script = oatpp::String::loadFromFile(source.param->c_str());
break;
default:
throw std::runtime_error("[oatpp::orm::SchemaMigration::migrate()]: Error. Unknown source type.");
}
m_executor->migrateSchema(script, source.version, m_suffix, connection);
}
}
}
v_int64 SchemaMigration::getSchemaVersion() {
return m_executor->getSchemaVersion(m_suffix);
}
}}
|
vincent-in-black-sesame/oat
|
src/oatpp/orm/SchemaMigration.cpp
|
C++
|
apache-2.0
| 2,726
|
/***************************************************************************
*
* 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_orm_SchemaMigration_hpp
#define oatpp_orm_SchemaMigration_hpp
#include "Executor.hpp"
namespace oatpp { namespace orm {
/**
* Database schema migration helper.
*/
class SchemaMigration {
private:
static constexpr v_int32 SOURCE_TEXT = 0;
static constexpr v_int32 SOURCE_FILE = 1;
struct Source {
v_int64 version;
v_int32 type;
oatpp::String param;
};
private:
base::ObjectHandle<Executor> m_executor;
oatpp::String m_suffix;
std::vector<Source> m_scripts;
public:
/**
* Constructor.
* @param executor - &id:oatpp::orm::Executor;.
* @param suffix - suffix of schema version control table.
*/
SchemaMigration(const base::ObjectHandle<Executor>& executor, const oatpp::String& suffix = nullptr);
/**
* Default virtual destructor.
*/
virtual ~SchemaMigration() = default;
/**
* Add migration script as text.
* @param version - schema version corresponding to this script.
* @param script - script text.
*/
void addText(v_int64 version, const oatpp::String& script);
/**
* Add migration script file.
* @param version - schema version corresponding to this script.
* @param script - path to script file.
*/
void addFile(v_int64 version, const oatpp::String& filename);
/**
* Run database schema migration.
*/
void migrate();
/**
* Get current database schema version.
* @return - schema version.
*/
v_int64 getSchemaVersion();
};
}}
#endif // oatpp_orm_SchemaMigration_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/orm/SchemaMigration.hpp
|
C++
|
apache-2.0
| 2,501
|
/***************************************************************************
*
* 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 "Transaction.hpp"
namespace oatpp { namespace orm {
Transaction::Transaction(const base::ObjectHandle<Executor>& executor, const provider::ResourceHandle<Connection>& connection)
: m_executor(executor)
, m_open(true)
{
auto res = executor->begin(connection);
if(res->isSuccess()) {
m_connection = res->getConnection();
} else {
m_open = false;
throw std::runtime_error("[oatpp::orm::Transaction::Transaction()]: "
"Error. Can't begin transaction - " + *res->getErrorMessage());
}
}
Transaction::Transaction(Transaction&& other)
: m_executor(std::move(other.m_executor))
, m_open(other.m_open)
, m_connection(std::move(other.m_connection))
{
other.m_open = false;
}
Transaction::~Transaction() {
if(m_open) {
try {
rollback();
} catch (...) {
// DO NOTHING
}
}
}
Transaction& Transaction::operator=(Transaction&& other) {
m_executor = std::move(other.m_executor);
m_open = other.m_open;
m_connection = std::move(other.m_connection);
other.m_open = false;
return *this;
}
provider::ResourceHandle<Connection> Transaction::getConnection() const {
return m_connection;
}
std::shared_ptr<QueryResult> Transaction::commit() {
if(m_open) {
m_open = false;
return m_executor->commit(m_connection);
} else {
throw std::runtime_error("[oatpp::orm::Transaction::commit()]: Error. The transaction is already closed.");
}
}
std::shared_ptr<QueryResult> Transaction::rollback() {
if(m_open) {
m_open = false;
return m_executor->rollback(m_connection);
} else {
throw std::runtime_error("[oatpp::orm::Transaction::commit()]: Error. The transaction is already closed.");
}
}
}}
|
vincent-in-black-sesame/oat
|
src/oatpp/orm/Transaction.cpp
|
C++
|
apache-2.0
| 2,717
|
/***************************************************************************
*
* 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_orm_Transaction_hpp
#define oatpp_orm_Transaction_hpp
#include "Executor.hpp"
namespace oatpp { namespace orm {
/**
* Database transaction.
*/
class Transaction {
private:
base::ObjectHandle<Executor> m_executor;
bool m_open;
private:
provider::ResourceHandle<Connection> m_connection;
public:
/**
* Constructor.
* @param executor - &id:oatpp::orm::Executor;.
* @param connection - database connection.
*/
Transaction(const base::ObjectHandle<Executor>& executor, const provider::ResourceHandle<Connection>& connection = nullptr);
/**
* Copy constructor.
* @param other
*/
Transaction(const Transaction& other) = delete;
/**
* Move constructor.
* @param other
*/
Transaction(Transaction&& other);
/**
* Virtual destructor. <br>
* Will automatically call &l:Transaction::rollback (); if there was no prior call to &l:Transaction::commit (); method.
*/
virtual ~Transaction();
Transaction& operator=(const Transaction& other) = delete;
Transaction& operator=(Transaction&& other);
/**
* Get the database connection associated with the transaction. <br>
* **Note:** all database queries within the transaction MUST be called on this connection.
* @return
*/
provider::ResourceHandle<Connection> getConnection() const;
/**
* Commit transaction.
* @return
*/
std::shared_ptr<QueryResult> commit();
/**
* Rollback transaction.
* @return
*/
std::shared_ptr<QueryResult> rollback();
};
}}
#endif // oatpp_orm_Transaction_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/orm/Transaction.hpp
|
C++
|
apache-2.0
| 2,550
|
/***************************************************************************
*
* 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 "Beautifier.hpp"
#include "oatpp/core/data/stream/BufferStream.hpp"
namespace oatpp { namespace parser { namespace json {
Beautifier::Beautifier(ConsistentOutputStream* outputStream, const oatpp::String& indent, const oatpp::String& newLine)
: m_outputStream(outputStream)
, m_indent(indent)
, m_newLine(newLine)
, m_level(0)
, m_wantIndent(false)
, m_isCharEscaped(false)
, m_isInString(false)
{}
void Beautifier::writeIndent(ConsistentOutputStream* outputStream) {
outputStream->writeSimple(m_newLine->data(), m_newLine->size());
for(v_int32 i = 0; i < m_level; i ++ ) {
outputStream->writeSimple(m_indent->data(), m_indent->size());
}
}
v_io_size Beautifier::write(const void *data, v_buff_size count, async::Action& action) {
(void) action;
oatpp::data::stream::BufferOutputStream buffer(count);
for(v_buff_size i = 0; i < count; i ++) {
v_char8 c = ((p_char8) data) [i];
if(m_isCharEscaped) {
m_isCharEscaped = false;
buffer.writeCharSimple(c);
continue;
}
if(m_isInString) {
if(c == '\\') {
m_isCharEscaped = true;
} else if(c == '"') {
m_isInString = false;
}
buffer.writeCharSimple(c);
continue;
}
switch(c) {
case '{': {
if(m_wantIndent) {
writeIndent(&buffer);
}
m_level ++;
m_wantIndent = true;
buffer.writeCharSimple('{');
break;
}
case '}': {
m_level --;
if(!m_wantIndent) {
writeIndent(&buffer);
}
buffer.writeCharSimple('}');
m_wantIndent = false;
break;
}
case '[': {
if(m_wantIndent) {
writeIndent(&buffer);
}
m_level ++;
m_wantIndent = true;
buffer.writeCharSimple('[');
break;
}
case ']': {
m_level --;
if(!m_wantIndent) {
writeIndent(&buffer);
}
buffer.writeCharSimple(']');
m_wantIndent = false;
break;
}
case ',': {
m_wantIndent = true;
buffer.writeCharSimple(',');
break;
}
case '"': {
if(m_wantIndent) {
writeIndent(&buffer);
}
buffer.writeCharSimple('"');
m_wantIndent = false;
m_isInString = true;
break;
}
case ':': {
buffer.writeSimple(": ", 2);
break;
}
default:
if(m_wantIndent) {
writeIndent(&buffer);
m_wantIndent = false;
}
buffer.writeCharSimple(c);
}
}
return m_outputStream->writeSimple(buffer.getData(), buffer.getCurrentPosition());
}
void Beautifier::setOutputStreamIOMode(IOMode ioMode) {
return m_outputStream->setOutputStreamIOMode(ioMode);
}
Beautifier::IOMode Beautifier::getOutputStreamIOMode() {
return m_outputStream->getOutputStreamIOMode();
}
Beautifier::Context& Beautifier::getOutputStreamContext() {
return m_outputStream->getOutputStreamContext();
}
}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/parser/json/Beautifier.cpp
|
C++
|
apache-2.0
| 4,038
|
/***************************************************************************
*
* 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_parser_json_Beautifier_hpp
#define oatpp_parser_json_Beautifier_hpp
#include "oatpp/core/data/stream/Stream.hpp"
namespace oatpp { namespace parser { namespace json {
/**
* JSON output stream beautifier.
*/
class Beautifier : public oatpp::data::stream::ConsistentOutputStream {
public:
typedef oatpp::data::stream::ConsistentOutputStream ConsistentOutputStream;
typedef oatpp::data::stream::IOMode IOMode;
typedef oatpp::data::stream::Context Context;
private:
ConsistentOutputStream* m_outputStream;
oatpp::String m_indent;
oatpp::String m_newLine;
private:
v_int32 m_level;
bool m_wantIndent;
bool m_isCharEscaped;
bool m_isInString;
private:
void writeIndent(ConsistentOutputStream* outputStream);
public:
/**
* Constructor.
* @param outputStream - destination output stream.
* @param indent
* @param newLine
*/
Beautifier(ConsistentOutputStream* outputStream, const oatpp::String& indent, const oatpp::String& newLine);
/**
* Write `count` of bytes to stream.
* @param data - data to write.
* @param count - number of bytes to write.
* @param action
* @return - actual number of bytes written. &id:oatpp::v_io_size;.
*/
v_io_size write(const void *data, v_buff_size count, async::Action& action) override;
/**
* Set stream I/O mode.
* @throws
*/
void setOutputStreamIOMode(IOMode ioMode) override;
/**
* Get stream I/O mode.
* @return
*/
IOMode getOutputStreamIOMode() override;
/**
* Get stream context.
* @return
*/
Context& getOutputStreamContext() override;
};
}}}
#endif // oatpp_parser_json_Beautifier_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/parser/json/Beautifier.hpp
|
C++
|
apache-2.0
| 2,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.
*
***************************************************************************/
#include "Utils.hpp"
#include "oatpp/encoding/Unicode.hpp"
#include "oatpp/encoding/Hex.hpp"
namespace oatpp { namespace parser { namespace json{
v_buff_size Utils::calcEscapedStringSize(const char* data, v_buff_size size, v_buff_size& safeSize, v_uint32 flags) {
v_buff_size result = 0;
v_buff_size i = 0;
safeSize = size;
while (i < size) {
v_char8 a = data[i];
if(a < 32) {
i ++;
switch (a) {
case '\b':
case '\f':
case '\n':
case '\r':
case '\t': result += 2; break; // '\n'
default:
result += 6; // '\uFFFF' - 6 chars
break;
}
} else if(a < 128){
i ++;
switch (a) {
case '\"':
case '\\': result += 2; break; // '\/'
case '/':
result ++;
if((flags & FLAG_ESCAPE_SOLIDUS) > 0) result ++;
break;
default:
result ++;
break;
}
} else {
v_buff_size charSize = oatpp::encoding::Unicode::getUtf8CharSequenceLength(a);
if(charSize != 0) {
if(i + charSize > size) {
safeSize = i;
}
i += charSize;
if(charSize < 4) {
result += 6; // '\uFFFF' - 6 chars
} else if(charSize == 4) {
result += 12; // '\uFFFF\uFFFF' - 12 chars surrogate pair
} else {
result += 11; // '\u+FFFFFFFF' - 11 chars NOT JSON standard case
}
} else {
// invalid char
i ++;
result ++;
}
}
}
return result;
}
v_buff_size Utils::calcUnescapedStringSize(const char* data, v_buff_size size, v_int64& errorCode, v_buff_size& errorPosition) {
errorCode = 0;
v_buff_size result = 0;
v_buff_size i = 0;
while (i < size) {
v_char8 a = data[i];
if(a == '\\'){
if(i + 1 == size){
errorCode = ERROR_CODE_INVALID_ESCAPED_CHAR;
errorPosition = i;
return 0;
}
v_char8 b = data[i + 1];
if(b == '"' || b == '\\' || b == '/' || b == 'b' || b == 'f' || b == 'n' || b == 'r' || b == 't'){
result += 1;
i += 2;
} else if(b == 'u'){
if(i + 6 > size){
errorCode = ERROR_CODE_INVALID_ESCAPED_CHAR;
errorPosition = i;
return 0;
}
if(data[i + 2] == '+') { // not JSON standard case
if(i + 11 > size){
errorCode = ERROR_CODE_INVALID_ESCAPED_CHAR;
errorPosition = i;
return 0;
}
v_uint32 code;
errorCode = encoding::Hex::readUInt32(&data[i + 3], code);
if(errorCode != 0){
errorPosition = i + 3;
return 0;
}
i += 11;
result += encoding::Unicode::getUtf8CharSequenceLengthForCode(code);
} else {
v_uint16 code;
errorCode = encoding::Hex::readUInt16(&data[i + 2], code);
if(errorCode != 0){
errorPosition = i + 2;
return 0;
}
if(code >= 0xD800 && code <= 0xDBFF){
if(i + 12 > size){
errorCode = ERROR_CODE_INVALID_SURROGATE_PAIR;
errorPosition = i;
return 0;
}
v_uint16 low;
errorCode = encoding::Hex::readUInt16(&data[i + 8], low);
if(errorCode != 0){
errorPosition = i + 8;
return 0;
}
if(low >= 0xDC00 && low <= 0xDFFF){
v_uint32 bigCode = encoding::Unicode::utf16SurrogatePairToCode(code, low);
i += 12;
result += encoding::Unicode::getUtf8CharSequenceLengthForCode(bigCode);
} else {
errorCode = ERROR_CODE_INVALID_SURROGATE_PAIR;
errorPosition = i;
return 0;
}
} else {
i += 6;
result += encoding::Unicode::getUtf8CharSequenceLengthForCode(code);
}
}
} else {
errorCode = ERROR_CODE_INVALID_ESCAPED_CHAR;
errorPosition = i;
return 0;
}
} else {
i ++;
result ++;
}
}
return result;
}
v_buff_size Utils::escapeUtf8Char(const char* sequence, p_char8 buffer){
v_buff_size length;
v_int32 code = oatpp::encoding::Unicode::encodeUtf8Char(sequence, length);
if(code < 0x00010000) {
buffer[0] = '\\';
buffer[1] = 'u';
oatpp::encoding::Hex::writeUInt16(v_uint16(code), &buffer[2]);
return 6;
} else if(code < 0x00200000) {
v_int16 high;
v_int16 low;
oatpp::encoding::Unicode::codeToUtf16SurrogatePair(code, high, low);
buffer[0] = '\\';
buffer[1] = 'u';
oatpp::encoding::Hex::writeUInt16(high, &buffer[2]);
buffer[6] = '\\';
buffer[7] = 'u';
oatpp::encoding::Hex::writeUInt16(low, &buffer[8]);
return 12;
} else {
buffer[0] = '\\';
buffer[1] = 'u';
buffer[2] = '+';
oatpp::encoding::Hex::writeUInt32(code, &buffer[2]);
return 11;
}
}
oatpp::String Utils::escapeString(const char* data, v_buff_size size, v_uint32 flags) {
v_buff_size safeSize;
v_buff_size escapedSize = calcEscapedStringSize(data, size, safeSize, flags);
if(escapedSize == size) {
return String((const char*)data, size);
}
auto result = String(escapedSize);
p_char8 resultData = (p_char8) result->data();
v_buff_size pos = 0;
{
v_buff_size i = 0;
while (i < safeSize) {
v_char8 a = data[i];
if (a < 32) {
switch (a) {
case '\b': resultData[pos] = '\\'; resultData[pos + 1] = 'b'; pos += 2; break;
case '\f': resultData[pos] = '\\'; resultData[pos + 1] = 'f'; pos += 2; break;
case '\n': resultData[pos] = '\\'; resultData[pos + 1] = 'n'; pos += 2; break;
case '\r': resultData[pos] = '\\'; resultData[pos + 1] = 'r'; pos += 2; break;
case '\t': resultData[pos] = '\\'; resultData[pos + 1] = 't'; pos += 2; break;
default:
resultData[pos] = '\\';
resultData[pos + 1] = 'u';
oatpp::encoding::Hex::writeUInt16(a, &resultData[pos + 2]);
pos += 6;
break;
}
i++;
}
else if (a < 128) {
switch (a) {
case '\"': resultData[pos] = '\\'; resultData[pos + 1] = '"'; pos += 2; break;
case '\\': resultData[pos] = '\\'; resultData[pos + 1] = '\\'; pos += 2; break;
case '/':
if((flags & FLAG_ESCAPE_SOLIDUS) > 0) {
resultData[pos] = '\\';
resultData[pos + 1] = '/';
pos += 2;
} else {
resultData[pos] = data[i];
pos++;
}
break;
default:
resultData[pos] = data[i];
pos++;
break;
}
i++;
}
else {
v_buff_size charSize = oatpp::encoding::Unicode::getUtf8CharSequenceLength(a);
if (charSize != 0) {
pos += escapeUtf8Char(&data[i], &resultData[pos]);
i += charSize;
}
else {
// invalid char
resultData[pos] = data[i];
i++;
pos++;
}
}
}
}
if(size > safeSize){
for(v_buff_size i = pos; i < result->size(); i ++){
resultData[i] = '?';
}
}
return result;
}
void Utils::unescapeStringToBuffer(const char* data, v_buff_size size, p_char8 resultData){
v_buff_size i = 0;
v_buff_size pos = 0;
while (i < size) {
v_char8 a = data[i];
if(a == '\\'){
v_char8 b = data[i + 1];
if(b != 'u'){
switch (b) {
case '"': resultData[pos] = '"'; pos ++; break;
case '\\': resultData[pos] = '\\'; pos ++; break;
case '/': resultData[pos] = '/'; pos ++; break;
case 'b': resultData[pos] = '\b'; pos ++; break;
case 'f': resultData[pos] = '\f'; pos ++; break;
case 'n': resultData[pos] = '\n'; pos ++; break;
case 'r': resultData[pos] = '\r'; pos ++; break;
case 't': resultData[pos] = '\t'; pos ++; break;
}
i += 2;
} else {
if(data[i + 2] == '+'){ // Not JSON standard case
v_uint32 code;
encoding::Hex::readUInt32(&data[i + 3], code);
i += 11;
pos += encoding::Unicode::decodeUtf8Char(code, &resultData[pos]);
} else {
v_uint16 code;
encoding::Hex::readUInt16(&data[i + 2], code);
if(code >= 0xD800 && code <= 0xDBFF){
v_uint16 low;
encoding::Hex::readUInt16(&data[i + 8], low);
v_uint32 bigCode = encoding::Unicode::utf16SurrogatePairToCode(code, low);
pos += encoding::Unicode::decodeUtf8Char(bigCode, &resultData[pos]);
i += 12;
} else {
pos += encoding::Unicode::decodeUtf8Char(code, &resultData[pos]);
i += 6;
}
}
}
} else {
resultData[pos] = a;
pos ++;
i++;
}
}
}
oatpp::String Utils::unescapeString(const char* data, v_buff_size size, v_int64& errorCode, v_buff_size& errorPosition) {
v_buff_size unescapedSize = calcUnescapedStringSize(data, size, errorCode, errorPosition);
if(errorCode != 0){
return nullptr;
}
auto result = String(unescapedSize);
if(unescapedSize == size) {
std::memcpy((void*) result->data(), data, size);
} else {
unescapeStringToBuffer(data, size, (p_char8) result->data());
}
return result;
}
std::string Utils::unescapeStringToStdString(const char* data, v_buff_size size, v_int64& errorCode, v_buff_size& errorPosition){
v_buff_size unescapedSize = calcUnescapedStringSize(data, size, errorCode, errorPosition);
if(errorCode != 0){
return "";
}
std::string result;
result.resize(unescapedSize);
if(unescapedSize == size) {
std::memcpy((p_char8) result.data(), data, size);
} else {
unescapeStringToBuffer(data, size, (p_char8) result.data());
}
return result;
}
const char* Utils::preparseString(ParsingCaret& caret, v_buff_size& size){
if(caret.canContinueAtChar('"', 1)){
const char* data = caret.getData();
v_buff_size pos = caret.getPosition();
v_buff_size pos0 = pos;
v_buff_size length = caret.getDataSize();
while (pos < length) {
v_char8 a = data[pos];
if(a == '"'){
size = pos - pos0;
return &data[pos0];
} else if(a == '\\') {
pos += 2;
} else {
pos ++;
}
}
caret.setPosition(caret.getDataSize());
caret.setError("[oatpp::parser::json::Utils::preparseString()]: Error. '\"' - expected", ERROR_CODE_PARSER_QUOTE_EXPECTED);
} else {
caret.setError("[oatpp::parser::json::Utils::preparseString()]: Error. '\"' - expected", ERROR_CODE_PARSER_QUOTE_EXPECTED);
}
return nullptr;
}
oatpp::String Utils::parseString(ParsingCaret& caret) {
v_buff_size size;
const char* data = preparseString(caret, size);
if(data != nullptr) {
v_buff_size pos = caret.getPosition();
v_int64 errorCode;
v_buff_size errorPosition;
auto result = unescapeString(data, size, errorCode, errorPosition);
if(errorCode != 0){
caret.setError("[oatpp::parser::json::Utils::parseString()]: Error. Call to unescapeString() failed", errorCode);
caret.setPosition(pos + errorPosition);
} else {
caret.setPosition(pos + size + 1);
}
return result;
}
return nullptr;
}
std::string Utils::parseStringToStdString(ParsingCaret& caret){
v_buff_size size;
auto data = preparseString(caret, size);
if(data != nullptr) {
v_buff_size pos = caret.getPosition();
v_int64 errorCode;
v_buff_size errorPosition;
const std::string& result = unescapeStringToStdString(data, size, errorCode, errorPosition);
if(errorCode != 0){
caret.setError("[oatpp::parser::json::Utils::parseStringToStdString()]: Error. Call to unescapeStringToStdString() failed", errorCode);
caret.setPosition(pos + errorPosition);
} else {
caret.setPosition(pos + size + 1);
}
return result;
}
return "";
}
bool Utils::findDecimalSeparatorInCurrentNumber(ParsingCaret& caret) {
parser::Caret::StateSaveGuard stateGuard(caret);
// search until a decimal separator is found or no more digits/sign are found or no more data available
while(caret.canContinue()) {
if (caret.isAtChar(JSON_DECIMAL_SEPARATOR)) {
return true;
}
if (!caret.isAtDigitChar() && !caret.isAtChar('-')) {
return false;
}
caret.inc();
}
return false;
}
}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/parser/json/Utils.cpp
|
C++
|
apache-2.0
| 13,781
|
/***************************************************************************
*
* 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_parser_json_Utils_hpp
#define oatpp_parser_json_Utils_hpp
#include "oatpp/core/parser/Caret.hpp"
#include "oatpp/core/Types.hpp"
#include <string>
namespace oatpp { namespace parser { namespace json {
/**
* Utility class for json serializer/deserializer.
* Used by &id:oatpp::parser::json::mapping::Serializer;, &id:oatpp::parser::json::mapping::Deserializer;.
*/
class Utils {
public:
static constexpr v_uint32 FLAG_ESCAPE_SOLIDUS = 1;
static constexpr v_uint32 FLAG_ESCAPE_ALL = FLAG_ESCAPE_SOLIDUS;
public:
/**
* ERROR_CODE_INVALID_ESCAPED_CHAR
*/
static constexpr v_int64 ERROR_CODE_INVALID_ESCAPED_CHAR = 1;
/**
* ERROR_CODE_INVALID_SURROGATE_PAIR
*/
static constexpr v_int64 ERROR_CODE_INVALID_SURROGATE_PAIR = 2;
/**
* '\\' - EXPECTED"
* ERROR_CODE_PARSER_QUOTE_EXPECTED
*/
static constexpr v_int64 ERROR_CODE_PARSER_QUOTE_EXPECTED = 3;
/**
* Character that is used as decimal separator in floating point string representations.
*/
static constexpr v_char8 JSON_DECIMAL_SEPARATOR = '.';
public:
typedef oatpp::String String;
typedef oatpp::parser::Caret ParsingCaret;
private:
static v_buff_size escapeUtf8Char(const char* sequence, p_char8 buffer);
static v_buff_size calcEscapedStringSize(const char* data, v_buff_size size, v_buff_size& safeSize, v_uint32 flags);
static v_buff_size calcUnescapedStringSize(const char* data, v_buff_size size, v_int64& errorCode, v_buff_size& errorPosition);
static void unescapeStringToBuffer(const char* data, v_buff_size size, p_char8 resultData);
static const char* preparseString(ParsingCaret& caret, v_buff_size& size);
public:
/**
* Escape string as for json standard. <br>
* *Note:* if(copyAsOwnData == false && escapedString == initialString) then result string will point to initial data.
* @param data - pointer to string to escape.
* @param size - data size.
* @param flags - escape flags.
* @return - &id:oatpp::String;.
*/
static String escapeString(const char* data, v_buff_size size, v_uint32 flags = FLAG_ESCAPE_ALL);
/**
* Unescape string as for json standard.
* @param data - pointer to string to unescape.
* @param size - data size.
* @param errorCode - out parameter. Error code <br>
* *One of:*<br>
* <ul>
* <li>&l:Utils::ERROR_CODE_INVALID_ESCAPED_CHAR;</li>
* <li>&l:Utils::ERROR_CODE_INVALID_SURROGATE_PAIR;</li>
* <li>&l:Utils::ERROR_CODE_PARSER_QUOTE_EXPECTED;</li>
* </ul>
* @param errorPosition - out parameter. Error position in data.
* @return - &id:oatpp::String;.
*/
static String unescapeString(const char* data, v_buff_size size, v_int64& errorCode, v_buff_size& errorPosition);
/**
* Same as &l:Utils::unescapeString (); but return `std::string`.
* @param data - pointer to string to unescape.
* @param size - data size.
* @param errorCode - out parameter. Error code <br>
* *One of:*<br>
* <ul>
* <li>&l:Utils::ERROR_CODE_INVALID_ESCAPED_CHAR;</li>
* <li>&l:Utils::ERROR_CODE_INVALID_SURROGATE_PAIR;</li>
* <li>&l:Utils::ERROR_CODE_PARSER_QUOTE_EXPECTED;</li>
* </ul>
* @param errorPosition - out parameter. Error position in data.
* @return - &id:oatpp::String;.
*/
static std::string unescapeStringToStdString(const char* data, v_buff_size size, v_int64& errorCode, v_buff_size& errorPosition);
/**
* Parse string enclosed in `"<string>"`.
* @param caret - &id:oatpp::parser::Caret;.
* @return - &id:oatpp::String;.
*/
static String parseString(ParsingCaret& caret);
/**
* Parse string enclosed in `"<string>"`.
* @param caret - &id:oatpp::parser::Caret;.
* @return - `std::string`.
*/
static std::string parseStringToStdString(ParsingCaret& caret);
/**
* Search for a decimal separator in the to analyze number string.
* @param caret - buffer to search for the decimal separator.
* @return - if the analyzed word has been identified as floating point number.
*/
static bool findDecimalSeparatorInCurrentNumber(ParsingCaret& caret);
};
}}}
#endif /* oatpp_parser_json_Utils_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/parser/json/Utils.hpp
|
C++
|
apache-2.0
| 5,133
|
/***************************************************************************
*
* 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 "Deserializer.hpp"
#include "oatpp/core/utils/ConversionUtils.hpp"
namespace oatpp { namespace parser { namespace json { namespace mapping {
Deserializer::Deserializer(const std::shared_ptr<Config>& config)
: m_config(config)
{
m_methods.resize(data::mapping::type::ClassId::getClassCount(), nullptr);
setDeserializerMethod(data::mapping::type::__class::String::CLASS_ID, &Deserializer::deserializeString);
setDeserializerMethod(data::mapping::type::__class::Any::CLASS_ID, &Deserializer::deserializeAny);
setDeserializerMethod(data::mapping::type::__class::Int8::CLASS_ID, &Deserializer::deserializeInt<oatpp::Int8>);
setDeserializerMethod(data::mapping::type::__class::UInt8::CLASS_ID, &Deserializer::deserializeUInt<oatpp::UInt8>);
setDeserializerMethod(data::mapping::type::__class::Int16::CLASS_ID, &Deserializer::deserializeInt<oatpp::Int16>);
setDeserializerMethod(data::mapping::type::__class::UInt16::CLASS_ID, &Deserializer::deserializeUInt<oatpp::UInt16>);
setDeserializerMethod(data::mapping::type::__class::Int32::CLASS_ID, &Deserializer::deserializeInt<oatpp::Int32>);
setDeserializerMethod(data::mapping::type::__class::UInt32::CLASS_ID, &Deserializer::deserializeUInt<oatpp::UInt32>);
setDeserializerMethod(data::mapping::type::__class::Int64::CLASS_ID, &Deserializer::deserializeInt<oatpp::Int64>);
setDeserializerMethod(data::mapping::type::__class::UInt64::CLASS_ID, &Deserializer::deserializeUInt<oatpp::UInt64>);
setDeserializerMethod(data::mapping::type::__class::Float32::CLASS_ID, &Deserializer::deserializeFloat32);
setDeserializerMethod(data::mapping::type::__class::Float64::CLASS_ID, &Deserializer::deserializeFloat64);
setDeserializerMethod(data::mapping::type::__class::Boolean::CLASS_ID, &Deserializer::deserializeBoolean);
setDeserializerMethod(data::mapping::type::__class::AbstractObject::CLASS_ID, &Deserializer::deserializeObject);
setDeserializerMethod(data::mapping::type::__class::AbstractEnum::CLASS_ID, &Deserializer::deserializeEnum);
setDeserializerMethod(data::mapping::type::__class::AbstractVector::CLASS_ID, &Deserializer::deserializeCollection);
setDeserializerMethod(data::mapping::type::__class::AbstractList::CLASS_ID, &Deserializer::deserializeCollection);
setDeserializerMethod(data::mapping::type::__class::AbstractUnorderedSet::CLASS_ID, &Deserializer::deserializeCollection);
setDeserializerMethod(data::mapping::type::__class::AbstractPairList::CLASS_ID, &Deserializer::deserializeMap);
setDeserializerMethod(data::mapping::type::__class::AbstractUnorderedMap::CLASS_ID, &Deserializer::deserializeMap);
}
void Deserializer::setDeserializerMethod(const data::mapping::type::ClassId& classId, DeserializerMethod method) {
const v_uint32 id = classId.id;
if(id >= m_methods.size()) {
m_methods.resize(id + 1, nullptr);
}
m_methods[id] = method;
}
void Deserializer::skipScope(oatpp::parser::Caret& caret, v_char8 charOpen, v_char8 charClose){
const char* data = caret.getData();
v_buff_size size = caret.getDataSize();
v_buff_size pos = caret.getPosition();
v_int32 scopeCounter = 0;
bool isInString = false;
while(pos < size){
v_char8 a = data[pos];
if(a == charOpen){
if(!isInString){
scopeCounter ++;
}
} else if(a == charClose){
if(!isInString){
scopeCounter --;
if(scopeCounter == 0){
caret.setPosition(pos + 1);
return;
}
}
} else if(a == '"') {
isInString = !isInString;
} else if(a == '\\'){
pos ++;
}
pos ++;
}
}
void Deserializer::skipString(oatpp::parser::Caret& caret){
const char* data = caret.getData();
v_buff_size size = caret.getDataSize();
v_buff_size pos = caret.getPosition();
v_int32 scopeCounter = 0;
while(pos < size){
v_char8 a = data[pos];
if(a == '"'){
scopeCounter ++;
if(scopeCounter == 2) {
caret.setPosition(pos + 1);
return;
}
} else if(a == '\\'){
pos ++;
}
pos ++;
}
}
void Deserializer::skipToken(oatpp::parser::Caret& caret){
const char* data = caret.getData();
v_buff_size size = caret.getDataSize();
v_buff_size pos = caret.getPosition();
while(pos < size){
v_char8 a = data[pos];
if(a == ' ' || a == '\t' || a == '\n' || a == '\r' || a == '\b' || a == '\f' ||
a == '}' || a == ',' || a == ']') {
caret.setPosition(pos);
return;
}
pos ++;
}
}
void Deserializer::skipValue(oatpp::parser::Caret& caret){
if(caret.isAtChar('{')){
skipScope(caret, '{', '}');
} else if(caret.isAtChar('[')){
skipScope(caret, '[', ']');
} else if(caret.isAtChar('"')){
skipString(caret);
} else {
skipToken(caret);
}
}
oatpp::Void Deserializer::deserializeFloat32(Deserializer* deserializer, parser::Caret& caret, const Type* const type) {
(void) deserializer;
(void) type;
if(caret.isAtText("null", true)){
return oatpp::Void(Float32::Class::getType());
} else {
return Float32(caret.parseFloat32());
}
}
oatpp::Void Deserializer::deserializeFloat64(Deserializer* deserializer, parser::Caret& caret, const Type* const type) {
(void) deserializer;
(void) type;
if(caret.isAtText("null", true)){
return oatpp::Void(Float64::Class::getType());
} else {
return Float64(caret.parseFloat64());
}
}
oatpp::Void Deserializer::deserializeBoolean(Deserializer* deserializer, parser::Caret& caret, const Type* const type) {
(void) deserializer;
(void) type;
if(caret.isAtText("null", true)){
return oatpp::Void(Boolean::Class::getType());
} else {
if(caret.isAtText("true", true)) {
return Boolean(true);
} else if(caret.isAtText("false", true)) {
return Boolean(false);
} else {
caret.setError("[oatpp::parser::json::mapping::Deserializer::readBooleanValue()]: Error. 'true' or 'false' - expected.", ERROR_CODE_VALUE_BOOLEAN);
return oatpp::Void(Boolean::Class::getType());
}
}
}
oatpp::Void Deserializer::deserializeString(Deserializer* deserializer, parser::Caret& caret, const Type* const type) {
(void) deserializer;
(void) type;
if(caret.isAtText("null", true)){
return oatpp::Void(String::Class::getType());
} else {
return oatpp::Void(oatpp::parser::json::Utils::parseString(caret).getPtr(), String::Class::getType());
}
}
const data::mapping::type::Type* Deserializer::guessNumberType(oatpp::parser::Caret& caret) {
if (!Utils::findDecimalSeparatorInCurrentNumber(caret)) {
if (*caret.getCurrData() == '-') {
return Int64::Class::getType();
} else {
return UInt64::Class::getType();
}
}
return Float64::Class::getType();
}
const data::mapping::type::Type* Deserializer::guessType(oatpp::parser::Caret& caret) {
{
parser::Caret::StateSaveGuard stateGuard(caret);
v_char8 c = *caret.getCurrData();
switch (c) {
case '"':
return String::Class::getType();
case '{':
return oatpp::Fields<Any>::Class::getType();
case '[':
return oatpp::List<Any>::Class::getType();
case 't':
if(caret.isAtText("true")) return Boolean::Class::getType();
break;
case 'f':
if(caret.isAtText("false")) return Boolean::Class::getType();
break;
default:
if (c == '-' || caret.isAtDigitChar()) {
return guessNumberType(caret);
}
}
}
caret.setError("[oatpp::parser::json::mapping::Deserializer::guessType()]: Error. Can't guess type for oatpp::Any.");
return nullptr;
}
oatpp::Void Deserializer::deserializeAny(Deserializer* deserializer, parser::Caret& caret, const Type* const type) {
(void) type;
if(caret.isAtText("null", true)){
return oatpp::Void(Any::Class::getType());
} else {
const Type* const fieldType = guessType(caret);
if(fieldType != nullptr) {
auto fieldValue = deserializer->deserialize(caret, fieldType);
auto anyHandle = std::make_shared<data::mapping::type::AnyHandle>(fieldValue.getPtr(), fieldValue.getValueType());
return oatpp::Void(anyHandle, Any::Class::getType());
}
}
return oatpp::Void(Any::Class::getType());
}
oatpp::Void Deserializer::deserializeEnum(Deserializer* deserializer, parser::Caret& caret, const Type* const type) {
auto polymorphicDispatcher = static_cast<const data::mapping::type::__class::AbstractEnum::PolymorphicDispatcher*>(
type->polymorphicDispatcher
);
data::mapping::type::EnumInterpreterError e = data::mapping::type::EnumInterpreterError::OK;
const auto& value = deserializer->deserialize(caret, polymorphicDispatcher->getInterpretationType());
if(caret.hasError()) {
return nullptr;
}
const auto& result = polymorphicDispatcher->fromInterpretation(value, e);
if(e == data::mapping::type::EnumInterpreterError::OK) {
return result;
}
switch(e) {
case data::mapping::type::EnumInterpreterError::CONSTRAINT_NOT_NULL:
caret.setError("[oatpp::parser::json::mapping::Deserializer::deserializeEnum()]: Error. Enum constraint violated - 'NotNull'.");
break;
default:
caret.setError("[oatpp::parser::json::mapping::Deserializer::deserializeEnum()]: Error. Can't deserialize Enum.");
}
return nullptr;
}
oatpp::Void Deserializer::deserializeCollection(Deserializer* deserializer, parser::Caret& caret, const Type* type) {
if(caret.isAtText("null", true)){
return oatpp::Void(type);
}
if(caret.canContinueAtChar('[', 1)) {
auto dispatcher = static_cast<const data::mapping::type::__class::Collection::PolymorphicDispatcher*>(type->polymorphicDispatcher);
auto collection = dispatcher->createObject();
auto itemType = dispatcher->getItemType();
caret.skipBlankChars();
while(!caret.isAtChar(']') && caret.canContinue()){
caret.skipBlankChars();
auto item = deserializer->deserialize(caret, itemType);
if(caret.hasError()){
return nullptr;
}
dispatcher->addItem(collection, item);
caret.skipBlankChars();
caret.canContinueAtChar(',', 1);
}
if(!caret.canContinueAtChar(']', 1)){
if(!caret.hasError()){
caret.setError("[oatpp::parser::json::mapping::Deserializer::deserializeCollection()]: Error. ']' - expected", ERROR_CODE_ARRAY_SCOPE_CLOSE);
}
return nullptr;
};
return collection;
} else {
caret.setError("[oatpp::parser::json::mapping::Deserializer::deserializeCollection()]: Error. '[' - expected", ERROR_CODE_ARRAY_SCOPE_OPEN);
return nullptr;
}
}
oatpp::Void Deserializer::deserializeMap(Deserializer* deserializer, parser::Caret& caret, const Type* const type) {
if(caret.isAtText("null", true)){
return oatpp::Void(type);
}
if(caret.canContinueAtChar('{', 1)) {
auto dispatcher = static_cast<const data::mapping::type::__class::Map::PolymorphicDispatcher*>(type->polymorphicDispatcher);
auto map = dispatcher->createObject();
auto keyType = dispatcher->getKeyType();
if(keyType->classId != oatpp::String::Class::CLASS_ID){
throw std::runtime_error("[oatpp::parser::json::mapping::Deserializer::deserializeMap()]: Invalid json map key. Key should be String");
}
auto valueType = dispatcher->getValueType();
caret.skipBlankChars();
while (!caret.isAtChar('}') && caret.canContinue()) {
caret.skipBlankChars();
auto key = Utils::parseString(caret);
if(caret.hasError()){
return nullptr;
}
caret.skipBlankChars();
if(!caret.canContinueAtChar(':', 1)){
caret.setError("[oatpp::parser::json::mapping::Deserializer::deserializeMap()]: Error. ':' - expected", ERROR_CODE_OBJECT_SCOPE_COLON_MISSING);
return nullptr;
}
caret.skipBlankChars();
auto item = deserializer->deserialize(caret, valueType);
if(caret.hasError()){
return nullptr;
}
dispatcher->addItem(map, key, item);
caret.skipBlankChars();
caret.canContinueAtChar(',', 1);
}
if(!caret.canContinueAtChar('}', 1)){
if(!caret.hasError()){
caret.setError("[oatpp::parser::json::mapping::Deserializer::deserializeMap()]: Error. '}' - expected", ERROR_CODE_OBJECT_SCOPE_CLOSE);
}
return nullptr;
}
return map;
} else {
caret.setError("[oatpp::parser::json::mapping::Deserializer::deserializeMap()]: Error. '{' - expected", ERROR_CODE_OBJECT_SCOPE_OPEN);
}
return nullptr;
}
oatpp::Void Deserializer::deserializeObject(Deserializer* deserializer, parser::Caret& caret, const Type* const type) {
if(caret.isAtText("null", true)){
return oatpp::Void(type);
}
if(caret.canContinueAtChar('{', 1)) {
auto dispatcher = static_cast<const oatpp::data::mapping::type::__class::AbstractObject::PolymorphicDispatcher*>(type->polymorphicDispatcher);
auto object = dispatcher->createObject();
const auto& fieldsMap = dispatcher->getProperties()->getMap();
caret.skipBlankChars();
std::vector<std::pair<oatpp::BaseObject::Property*, oatpp::String>> polymorphs;
while (!caret.isAtChar('}') && caret.canContinue()) {
caret.skipBlankChars();
auto key = Utils::parseStringToStdString(caret);
if(caret.hasError()){
return nullptr;
}
auto fieldIterator = fieldsMap.find(key);
if(fieldIterator != fieldsMap.end()){
caret.skipBlankChars();
if(!caret.canContinueAtChar(':', 1)){
caret.setError("[oatpp::parser::json::mapping::Deserializer::readObject()]: Error. ':' - expected", ERROR_CODE_OBJECT_SCOPE_COLON_MISSING);
return nullptr;
}
caret.skipBlankChars();
auto field = fieldIterator->second;
if(field->info.typeSelector && field->type == oatpp::Any::Class::getType()) {
auto label = caret.putLabel();
skipValue(caret);
polymorphs.emplace_back(field, label.toString()); // store polymorphs for later processing.
} else {
field->set(static_cast<oatpp::BaseObject *>(object.get()), deserializer->deserialize(caret, field->type));
}
} else if (deserializer->getConfig()->allowUnknownFields) {
caret.skipBlankChars();
if(!caret.canContinueAtChar(':', 1)){
caret.setError("[oatpp::parser::json::mapping::Deserializer::readObject()/if(config->allowUnknownFields){}]: Error. ':' - expected", ERROR_CODE_OBJECT_SCOPE_COLON_MISSING);
return nullptr;
}
caret.skipBlankChars();
skipValue(caret);
} else {
caret.setError("[oatpp::parser::json::mapping::Deserializer::readObject()]: Error. Unknown field", ERROR_CODE_OBJECT_SCOPE_UNKNOWN_FIELD);
return nullptr;
}
caret.skipBlankChars();
caret.canContinueAtChar(',', 1);
}
if(!caret.canContinueAtChar('}', 1)){
if(!caret.hasError()){
caret.setError("[oatpp::parser::json::mapping::Deserializer::readObject()]: Error. '}' - expected", ERROR_CODE_OBJECT_SCOPE_CLOSE);
}
return nullptr;
}
for(auto& p : polymorphs) {
parser::Caret polyCaret(p.second);
auto selectedType = p.first->info.typeSelector->selectType(static_cast<oatpp::BaseObject *>(object.get()));
auto value = deserializer->deserialize(polyCaret, selectedType);
oatpp::Any any(value);
p.first->set(static_cast<oatpp::BaseObject *>(object.get()), oatpp::Void(any.getPtr(), p.first->type));
}
return object;
} else {
caret.setError("[oatpp::parser::json::mapping::Deserializer::readObject()]: Error. '{' - expected", ERROR_CODE_OBJECT_SCOPE_OPEN);
}
return nullptr;
}
oatpp::Void Deserializer::deserialize(parser::Caret& caret, const Type* const type) {
auto id = type->classId.id;
auto& method = m_methods[id];
if(method) {
return (*method)(this, caret, type);
} else {
auto* interpretation = type->findInterpretation(m_config->enabledInterpretations);
if(interpretation) {
return interpretation->fromInterpretation(deserialize(caret, interpretation->getInterpretationType()));
}
throw std::runtime_error("[oatpp::parser::json::mapping::Deserializer::deserialize()]: "
"Error. No deserialize method for type '" + std::string(type->classId.name) + "'");
}
}
const std::shared_ptr<Deserializer::Config>& Deserializer::getConfig() {
return m_config;
}
}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/parser/json/mapping/Deserializer.cpp
|
C++
|
apache-2.0
| 17,409
|
/***************************************************************************
*
* 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_parser_json_mapping_Deserializer_hpp
#define oatpp_parser_json_mapping_Deserializer_hpp
#include "oatpp/parser/json/Utils.hpp"
#include "oatpp/core/parser/Caret.hpp"
#include "oatpp/core/Types.hpp"
#include <vector>
namespace oatpp { namespace parser { namespace json { namespace mapping {
/**
* Json Deserializer.
* Deserialize oatpp DTO object from json. See [Data Transfer Object(DTO) component](https://oatpp.io/docs/components/dto/).
*/
class Deserializer {
public:
typedef oatpp::data::mapping::type::Type Type;
typedef oatpp::data::mapping::type::BaseObject::Property Property;
typedef oatpp::data::mapping::type::BaseObject::Properties Properties;
typedef oatpp::String String;
public:
/**
* "'{' - expected"
*/
static constexpr v_int32 ERROR_CODE_OBJECT_SCOPE_OPEN = 1;
/**
* "'}' - expected"
*/
static constexpr v_int32 ERROR_CODE_OBJECT_SCOPE_CLOSE = 2;
/**
* "Unknown field"
*/
static constexpr v_int32 ERROR_CODE_OBJECT_SCOPE_UNKNOWN_FIELD = 3;
/**
* "':' - expected"
*/
static constexpr v_int32 ERROR_CODE_OBJECT_SCOPE_COLON_MISSING = 4;
/**
* "'[' - expected"
*/
static constexpr v_int32 ERROR_CODE_ARRAY_SCOPE_OPEN = 5;
/**
* "']' - expected"
*/
static constexpr v_int32 ERROR_CODE_ARRAY_SCOPE_CLOSE = 6;
/**
* "'true' or 'false' - expected"
*/
static constexpr v_int32 ERROR_CODE_VALUE_BOOLEAN = 7;
public:
/**
* Deserializer config.
*/
class Config : public oatpp::base::Countable {
public:
/**
* Constructor.
*/
Config()
{}
public:
/**
* Create shared Config.
* @return - `std::shared_ptr` to Config.
*/
static std::shared_ptr<Config> createShared(){
return std::make_shared<Config>();
}
/**
* Do not fail if unknown field is found in json.
* "unknown field" is the one which is not present in DTO object class.
*/
bool allowUnknownFields = true;
/**
* Enable type interpretations.
*/
std::vector<std::string> enabledInterpretations = {};
};
public:
typedef oatpp::Void (*DeserializerMethod)(Deserializer*, parser::Caret&, const Type* const);
private:
static void skipScope(oatpp::parser::Caret& caret, v_char8 charOpen, v_char8 charClose);
static void skipString(oatpp::parser::Caret& caret);
static void skipToken(oatpp::parser::Caret& caret);
static void skipValue(oatpp::parser::Caret& caret);
private:
static const Type* guessNumberType(oatpp::parser::Caret& caret);
static const Type* guessType(oatpp::parser::Caret& caret);
private:
template<class T>
static oatpp::Void deserializeInt(Deserializer* deserializer, parser::Caret& caret, const Type* const type){
(void) deserializer;
(void) type;
if(caret.isAtText("null", true)){
return oatpp::Void(T::Class::getType());
} else {
//TODO: shall we handle overflow cases like
// oatpp::String json = "128";
// auto value = jsonObjectMapper->readFromString<oatpp::Int8>(json); // UInt8 will overflow to -128
return T(static_cast<typename T::UnderlyingType>(caret.parseInt()));
}
}
template<class T>
static oatpp::Void deserializeUInt(Deserializer* deserializer, parser::Caret& caret, const Type* const type){
(void) deserializer;
(void) type;
if(caret.isAtText("null", true)){
return oatpp::Void(T::Class::getType());
} else {
//TODO: shall we handle overflow cases like
// oatpp::String json = "256";
// auto value = jsonObjectMapper->readFromString<oatpp::UInt8>(json); // UInt8 will overflow to 0
return T(static_cast<typename T::UnderlyingType>(caret.parseUnsignedInt()));
}
}
template<class Collection>
static oatpp::Void deserializeKeyValue(Deserializer* deserializer, parser::Caret& caret, const Type* const type) {
if(caret.isAtText("null", true)){
return oatpp::Void(type);
}
if(caret.canContinueAtChar('{', 1)) {
auto polymorphicDispatcher = static_cast<const typename Collection::Class::PolymorphicDispatcher*>(type->polymorphicDispatcher);
auto mapWrapper = polymorphicDispatcher->createObject();
const auto& map = mapWrapper.template cast<Collection>();
auto it = type->params.begin();
auto keyType = *it ++;
if(keyType->classId.id != oatpp::data::mapping::type::__class::String::CLASS_ID.id){
throw std::runtime_error("[oatpp::parser::json::mapping::Deserializer::deserializeKeyValue()]: Invalid json map key. Key should be String");
}
auto valueType = *it;
caret.skipBlankChars();
while (!caret.isAtChar('}') && caret.canContinue()) {
caret.skipBlankChars();
auto key = Utils::parseString(caret);
if(caret.hasError()){
return nullptr;
}
caret.skipBlankChars();
if(!caret.canContinueAtChar(':', 1)){
caret.setError("[oatpp::parser::json::mapping::Deserializer::deserializeKeyValue()]: Error. ':' - expected", ERROR_CODE_OBJECT_SCOPE_COLON_MISSING);
return nullptr;
}
caret.skipBlankChars();
auto item = deserializer->deserialize(caret, valueType);
if(caret.hasError()){
return nullptr;
}
polymorphicDispatcher->addPolymorphicItem(mapWrapper, key, item);
caret.skipBlankChars();
caret.canContinueAtChar(',', 1);
}
if(!caret.canContinueAtChar('}', 1)){
if(!caret.hasError()){
caret.setError("[oatpp::parser::json::mapping::Deserializer::deserializeKeyValue()]: Error. '}' - expected", ERROR_CODE_OBJECT_SCOPE_CLOSE);
}
return nullptr;
}
return oatpp::Void(map.getPtr(), map.getValueType());
} else {
caret.setError("[oatpp::parser::json::mapping::Deserializer::deserializeKeyValue()]: Error. '{' - expected", ERROR_CODE_OBJECT_SCOPE_OPEN);
}
return nullptr;
}
static oatpp::Void deserializeFloat32(Deserializer* deserializer, parser::Caret& caret, const Type* const type);
static oatpp::Void deserializeFloat64(Deserializer* deserializer, parser::Caret& caret, const Type* const type);
static oatpp::Void deserializeBoolean(Deserializer* deserializer, parser::Caret& caret, const Type* const type);
static oatpp::Void deserializeString(Deserializer* deserializer, parser::Caret& caret, const Type* const type);
static oatpp::Void deserializeAny(Deserializer* deserializer, parser::Caret& caret, const Type* const type);
static oatpp::Void deserializeEnum(Deserializer* deserializer, parser::Caret& caret, const Type* const type);
static oatpp::Void deserializeCollection(Deserializer* deserializer, parser::Caret& caret, const Type* type);
static oatpp::Void deserializeMap(Deserializer* deserializer, parser::Caret& caret, const Type* const type);
static oatpp::Void deserializeObject(Deserializer* deserializer, parser::Caret& caret, const Type* const type);
private:
std::shared_ptr<Config> m_config;
std::vector<DeserializerMethod> m_methods;
public:
/**
* Constructor.
* @param config
*/
Deserializer(const std::shared_ptr<Config>& config = std::make_shared<Config>());
/**
* Set deserializer method for type.
* @param classId - &id:oatpp::data::mapping::type::ClassId;.
* @param method - `typedef oatpp::Void (*DeserializerMethod)(Deserializer*, parser::Caret&, const Type* const)`.
*/
void setDeserializerMethod(const data::mapping::type::ClassId& classId, DeserializerMethod method);
/**
* Deserialize text.
* @param caret - &id:oatpp::parser::Caret;.
* @param type - &id:oatpp::data::mapping::type::Type;
* @return - `oatpp::Void` over deserialized object.
*/
oatpp::Void deserialize(parser::Caret& caret, const Type* const type);
/**
* Get deserializer config.
* @return
*/
const std::shared_ptr<Config>& getConfig();
};
}}}}
#endif /* oatpp_parser_json_mapping_Deserializer_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/parser/json/mapping/Deserializer.hpp
|
C++
|
apache-2.0
| 8,960
|
/***************************************************************************
*
* 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 "ObjectMapper.hpp"
namespace oatpp { namespace parser { namespace json { namespace mapping {
ObjectMapper::ObjectMapper(const std::shared_ptr<Serializer::Config>& serializerConfig,
const std::shared_ptr<Deserializer::Config>& deserializerConfig)
: data::mapping::ObjectMapper(getMapperInfo())
, m_serializer(std::make_shared<Serializer>(serializerConfig))
, m_deserializer(std::make_shared<Deserializer>(deserializerConfig))
{}
ObjectMapper::ObjectMapper(const std::shared_ptr<Serializer>& serializer,
const std::shared_ptr<Deserializer>& deserializer)
: data::mapping::ObjectMapper(getMapperInfo())
, m_serializer(serializer)
, m_deserializer(deserializer)
{}
std::shared_ptr<ObjectMapper> ObjectMapper::createShared(const std::shared_ptr<Serializer::Config>& serializerConfig,
const std::shared_ptr<Deserializer::Config>& deserializerConfig){
return std::make_shared<ObjectMapper>(serializerConfig, deserializerConfig);
}
std::shared_ptr<ObjectMapper> ObjectMapper::createShared(const std::shared_ptr<Serializer>& serializer,
const std::shared_ptr<Deserializer>& deserializer){
return std::make_shared<ObjectMapper>(serializer, deserializer);
}
void ObjectMapper::write(data::stream::ConsistentOutputStream* stream,
const oatpp::Void& variant) const {
m_serializer->serializeToStream(stream, variant);
}
oatpp::Void ObjectMapper::read(oatpp::parser::Caret& caret,
const oatpp::data::mapping::type::Type* const type) const {
return m_deserializer->deserialize(caret, type);
}
std::shared_ptr<Serializer> ObjectMapper::getSerializer() {
return m_serializer;
}
std::shared_ptr<Deserializer> ObjectMapper::getDeserializer() {
return m_deserializer;
}
}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/parser/json/mapping/ObjectMapper.cpp
|
C++
|
apache-2.0
| 2,954
|
/***************************************************************************
*
* 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_parser_json_mapping_ObjectMapper_hpp
#define oatpp_parser_json_mapping_ObjectMapper_hpp
#include "./Serializer.hpp"
#include "./Deserializer.hpp"
#include "oatpp/core/data/mapping/ObjectMapper.hpp"
namespace oatpp { namespace parser { namespace json { namespace mapping {
/**
* Json ObjectMapper. Serialized/Deserializes oatpp DTO objects to/from JSON.
* See [Data Transfer Object(DTO) component](https://oatpp.io/docs/components/dto/). <br>
* Extends &id:oatpp::base::Countable;, &id:oatpp::data::mapping::ObjectMapper;.
*/
class ObjectMapper : public oatpp::base::Countable, public oatpp::data::mapping::ObjectMapper {
private:
static Info& getMapperInfo() {
static Info info("application/json");
return info;
}
private:
std::shared_ptr<Serializer> m_serializer;
std::shared_ptr<Deserializer> m_deserializer;
public:
/**
* Constructor.
* @param serializerConfig - &id:oatpp::parser::json::mapping::Serializer::Config;.
* @param deserializerConfig - &id:oatpp::parser::json::mapping::Deserializer::Config;.
*/
ObjectMapper(const std::shared_ptr<Serializer::Config>& serializerConfig,
const std::shared_ptr<Deserializer::Config>& deserializerConfig);
/**
* Constructor.
* @param serializer
* @param deserializer
*/
ObjectMapper(const std::shared_ptr<Serializer>& serializer = std::make_shared<Serializer>(),
const std::shared_ptr<Deserializer>& deserializer = std::make_shared<Deserializer>());
public:
/**
* Create shared ObjectMapper.
* @param serializerConfig - &id:oatpp::parser::json::mapping::Serializer::Config;.
* @param deserializerConfig - &id:oatpp::parser::json::mapping::Deserializer::Config;.
* @return - `std::shared_ptr` to ObjectMapper.
*/
static std::shared_ptr<ObjectMapper>
createShared(const std::shared_ptr<Serializer::Config>& serializerConfig,
const std::shared_ptr<Deserializer::Config>& deserializerConfig);
/**
* Create shared ObjectMapper.
* @param serializer
* @param deserializer
* @return
*/
static std::shared_ptr<ObjectMapper>
createShared(const std::shared_ptr<Serializer>& serializer = std::make_shared<Serializer>(),
const std::shared_ptr<Deserializer>& deserializer = std::make_shared<Deserializer>());
/**
* Implementation of &id:oatpp::data::mapping::ObjectMapper::write;.
* @param stream - stream to write serializerd data to &id:oatpp::data::stream::ConsistentOutputStream;.
* @param variant - object to serialize &id:oatpp::Void;.
*/
void write(data::stream::ConsistentOutputStream* stream, const oatpp::Void& variant) const override;
/**
* Implementation of &id:oatpp::data::mapping::ObjectMapper::read;.
* @param caret - &id:oatpp::parser::Caret;.
* @param type - type of resultant object &id:oatpp::data::mapping::type::Type;.
* @return - &id:oatpp::Void; holding resultant object.
*/
oatpp::Void read(oatpp::parser::Caret& caret, const oatpp::data::mapping::type::Type* const type) const override;
/**
* Get serializer.
* @return
*/
std::shared_ptr<Serializer> getSerializer();
/**
* Get deserializer.
* @return
*/
std::shared_ptr<Deserializer> getDeserializer();
};
}}}}
#endif /* oatpp_parser_json_mapping_ObjectMapper_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/parser/json/mapping/ObjectMapper.hpp
|
C++
|
apache-2.0
| 4,318
|
/***************************************************************************
*
* 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 "Serializer.hpp"
#include "oatpp/parser/json/Utils.hpp"
#include "oatpp/core/data/mapping/type/Any.hpp"
namespace oatpp { namespace parser { namespace json { namespace mapping {
Serializer::Serializer(const std::shared_ptr<Config>& config)
: m_config(config)
{
m_methods.resize(data::mapping::type::ClassId::getClassCount(), nullptr);
setSerializerMethod(data::mapping::type::__class::String::CLASS_ID, &Serializer::serializeString);
setSerializerMethod(data::mapping::type::__class::Any::CLASS_ID, &Serializer::serializeAny);
setSerializerMethod(data::mapping::type::__class::Int8::CLASS_ID, &Serializer::serializePrimitive<oatpp::Int8>);
setSerializerMethod(data::mapping::type::__class::UInt8::CLASS_ID, &Serializer::serializePrimitive<oatpp::UInt8>);
setSerializerMethod(data::mapping::type::__class::Int16::CLASS_ID, &Serializer::serializePrimitive<oatpp::Int16>);
setSerializerMethod(data::mapping::type::__class::UInt16::CLASS_ID, &Serializer::serializePrimitive<oatpp::UInt16>);
setSerializerMethod(data::mapping::type::__class::Int32::CLASS_ID, &Serializer::serializePrimitive<oatpp::Int32>);
setSerializerMethod(data::mapping::type::__class::UInt32::CLASS_ID, &Serializer::serializePrimitive<oatpp::UInt32>);
setSerializerMethod(data::mapping::type::__class::Int64::CLASS_ID, &Serializer::serializePrimitive<oatpp::Int64>);
setSerializerMethod(data::mapping::type::__class::UInt64::CLASS_ID, &Serializer::serializePrimitive<oatpp::UInt64>);
setSerializerMethod(data::mapping::type::__class::Float32::CLASS_ID, &Serializer::serializePrimitive<oatpp::Float32>);
setSerializerMethod(data::mapping::type::__class::Float64::CLASS_ID, &Serializer::serializePrimitive<oatpp::Float64>);
setSerializerMethod(data::mapping::type::__class::Boolean::CLASS_ID, &Serializer::serializePrimitive<oatpp::Boolean>);
setSerializerMethod(data::mapping::type::__class::AbstractObject::CLASS_ID, &Serializer::serializeObject);
setSerializerMethod(data::mapping::type::__class::AbstractEnum::CLASS_ID, &Serializer::serializeEnum);
setSerializerMethod(data::mapping::type::__class::AbstractVector::CLASS_ID, &Serializer::serializeCollection);
setSerializerMethod(data::mapping::type::__class::AbstractList::CLASS_ID, &Serializer::serializeCollection);
setSerializerMethod(data::mapping::type::__class::AbstractUnorderedSet::CLASS_ID, &Serializer::serializeCollection);
setSerializerMethod(data::mapping::type::__class::AbstractPairList::CLASS_ID, &Serializer::serializeMap);
setSerializerMethod(data::mapping::type::__class::AbstractUnorderedMap::CLASS_ID, &Serializer::serializeMap);
}
void Serializer::setSerializerMethod(const data::mapping::type::ClassId& classId, SerializerMethod method) {
const v_uint32 id = classId.id;
if(id >= m_methods.size()) {
m_methods.resize(id + 1, nullptr);
}
m_methods[id] = method;
}
void Serializer::serializeString(data::stream::ConsistentOutputStream* stream, const char* data, v_buff_size size, v_uint32 escapeFlags) {
auto encodedValue = Utils::escapeString(data, size, escapeFlags);
stream->writeCharSimple('\"');
stream->writeSimple(encodedValue);
stream->writeCharSimple('\"');
}
void Serializer::serializeString(Serializer* serializer,
data::stream::ConsistentOutputStream* stream,
const oatpp::Void& polymorph)
{
if(!polymorph) {
stream->writeSimple("null", 4);
return;
}
auto str = static_cast<std::string*>(polymorph.get());
serializeString(stream, str->data(), str->size(), serializer->m_config->escapeFlags);
}
void Serializer::serializeAny(Serializer* serializer,
data::stream::ConsistentOutputStream* stream,
const oatpp::Void& polymorph)
{
if(!polymorph) {
stream->writeSimple("null", 4);
return;
}
auto anyHandle = static_cast<data::mapping::type::AnyHandle*>(polymorph.get());
serializer->serialize(stream, oatpp::Void(anyHandle->ptr, anyHandle->type));
}
void Serializer::serializeEnum(Serializer* serializer,
data::stream::ConsistentOutputStream* stream,
const oatpp::Void& polymorph)
{
auto polymorphicDispatcher = static_cast<const data::mapping::type::__class::AbstractEnum::PolymorphicDispatcher*>(
polymorph.getValueType()->polymorphicDispatcher
);
data::mapping::type::EnumInterpreterError e = data::mapping::type::EnumInterpreterError::OK;
serializer->serialize(stream, polymorphicDispatcher->toInterpretation(polymorph, e));
if(e == data::mapping::type::EnumInterpreterError::OK) {
return;
}
switch(e) {
case data::mapping::type::EnumInterpreterError::CONSTRAINT_NOT_NULL:
throw std::runtime_error("[oatpp::parser::json::mapping::Serializer::serializeEnum()]: Error. Enum constraint violated - 'NotNull'.");
default:
throw std::runtime_error("[oatpp::parser::json::mapping::Serializer::serializeEnum()]: Error. Can't serialize Enum.");
}
}
void Serializer::serializeCollection(Serializer* serializer,
data::stream::ConsistentOutputStream* stream,
const oatpp::Void& polymorph)
{
if(!polymorph) {
stream->writeSimple("null", 4);
return;
}
auto dispatcher = static_cast<const data::mapping::type::__class::Collection::PolymorphicDispatcher*>(
polymorph.getValueType()->polymorphicDispatcher
);
stream->writeCharSimple('[');
bool first = true;
auto iterator = dispatcher->beginIteration(polymorph);
while (!iterator->finished()) {
const auto& value = iterator->get();
if(value || serializer->getConfig()->includeNullFields || serializer->getConfig()->alwaysIncludeNullCollectionElements) {
(first) ? first = false : stream->writeSimple(",", 1);
serializer->serialize(stream, value);
}
iterator->next();
}
stream->writeCharSimple(']');
}
void Serializer::serializeMap(Serializer* serializer,
data::stream::ConsistentOutputStream* stream,
const oatpp::Void& polymorph)
{
if(!polymorph) {
stream->writeSimple("null", 4);
return;
}
auto dispatcher = static_cast<const data::mapping::type::__class::Map::PolymorphicDispatcher*>(
polymorph.getValueType()->polymorphicDispatcher
);
auto keyType = dispatcher->getKeyType();
if(keyType->classId != oatpp::String::Class::CLASS_ID){
throw std::runtime_error("[oatpp::parser::json::mapping::Serializer::serializeMap()]: Invalid json map key. Key should be String");
}
stream->writeCharSimple('{');
bool first = true;
auto iterator = dispatcher->beginIteration(polymorph);
while (!iterator->finished()) {
const auto& value = iterator->getValue();
if(value || serializer->m_config->includeNullFields || serializer->m_config->alwaysIncludeNullCollectionElements) {
(first) ? first = false : stream->writeSimple(",", 1);
const auto& untypedKey = iterator->getKey();
const auto& key = oatpp::String(std::static_pointer_cast<std::string>(untypedKey.getPtr()));
serializeString(stream, key->data(), key->size(), serializer->m_config->escapeFlags);
stream->writeSimple(":", 1);
serializer->serialize(stream, value);
}
iterator->next();
}
stream->writeCharSimple('}');
}
void Serializer::serializeObject(Serializer* serializer,
data::stream::ConsistentOutputStream* stream,
const oatpp::Void& polymorph)
{
if(!polymorph) {
stream->writeSimple("null", 4);
return;
}
stream->writeCharSimple('{');
bool first = true;
auto dispatcher = static_cast<const oatpp::data::mapping::type::__class::AbstractObject::PolymorphicDispatcher*>(
polymorph.getValueType()->polymorphicDispatcher
);
auto fields = dispatcher->getProperties()->getList();
auto object = static_cast<oatpp::BaseObject*>(polymorph.get());
auto config = serializer->m_config;
for (auto const& field : fields) {
oatpp::Void value;
if(field->info.typeSelector && field->type == oatpp::Any::Class::getType()) {
const auto& any = field->get(object).cast<oatpp::Any>();
value = any.retrieve(field->info.typeSelector->selectType(object));
} else {
value = field->get(object);
}
if (value || config->includeNullFields || (field->info.required && config->alwaysIncludeRequired)) {
(first) ? first = false : stream->writeSimple(",", 1);
serializeString(stream, field->name, std::strlen(field->name), serializer->m_config->escapeFlags);
stream->writeSimple(":", 1);
serializer->serialize(stream, value);
}
}
stream->writeCharSimple('}');
}
void Serializer::serialize(data::stream::ConsistentOutputStream* stream,
const oatpp::Void& polymorph)
{
auto id = polymorph.getValueType()->classId.id;
auto& method = m_methods[id];
if(method) {
(*method)(this, stream, polymorph);
} else {
auto* interpretation = polymorph.getValueType()->findInterpretation(m_config->enabledInterpretations);
if(interpretation) {
serialize(stream, interpretation->toInterpretation(polymorph));
} else {
throw std::runtime_error("[oatpp::parser::json::mapping::Serializer::serialize()]: "
"Error. No serialize method for type '" +
std::string(polymorph.getValueType()->classId.name) + "'");
}
}
}
void Serializer::serializeToStream(data::stream::ConsistentOutputStream* stream,
const oatpp::Void& polymorph)
{
if(m_config->useBeautifier) {
json::Beautifier beautifier(stream, " ", "\n");
serialize(&beautifier, polymorph);
} else {
serialize(stream, polymorph);
}
}
const std::shared_ptr<Serializer::Config>& Serializer::getConfig() {
return m_config;
}
}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/parser/json/mapping/Serializer.cpp
|
C++
|
apache-2.0
| 10,998
|
/***************************************************************************
*
* 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_parser_json_mapping_Serializer_hpp
#define oatpp_parser_json_mapping_Serializer_hpp
#include "oatpp/parser/json/Utils.hpp"
#include "oatpp/parser/json/Beautifier.hpp"
#include "oatpp/core/Types.hpp"
#include <vector>
namespace oatpp { namespace parser { namespace json { namespace mapping {
/**
* Json Serializer.
* Serializes oatpp DTO object to json. See [Data Transfer Object(DTO) component](https://oatpp.io/docs/components/dto/).
*/
class Serializer {
public:
typedef oatpp::data::mapping::type::Type Type;
typedef oatpp::data::mapping::type::BaseObject::Property Property;
typedef oatpp::data::mapping::type::BaseObject::Properties Properties;
typedef oatpp::String String;
public:
/**
* Serializer config.
*/
class Config : public oatpp::base::Countable {
public:
/**
* Constructor.
*/
Config()
{}
public:
/**
* Create shared config.
* @return - `std::shared_ptr` to Config.
*/
static std::shared_ptr<Config> createShared(){
return std::make_shared<Config>();
}
/**
* Include fields with value == nullptr into serialized json.
* Field will still be included when field-info `required` is set to true and &id:alwaysIncludeRequired is set to true.
*/
bool includeNullFields = true;
/**
* Always include required fields (set in in DTO_FIELD_INFO) even if they are `value == nullptr`
*/
bool alwaysIncludeRequired = false;
/**
* Always include array or map elements, even if their value is `nullptr`.
*/
bool alwaysIncludeNullCollectionElements = false;
/**
* If `true` - insert string `"<unknown-type>"` in json field value in case unknown field found.
* Fail if `false`.
* Known types for this serializer are:<br>
* (String, Int8, Int16, Int32, Int64, Float32, Float64, Boolean, DTOs, List, Fields).
*/
bool throwOnUnknownTypes = true;
/**
* Use JSON Beautifier.
*/
bool useBeautifier = false;
/**
* Beautifier Indent.
*/
oatpp::String beautifierIndent = " ";
/**
* Beautifier new line.
*/
oatpp::String beautifierNewLine = "\n";
/**
* Enable type interpretations.
*/
std::vector<std::string> enabledInterpretations = {};
/**
* Escape flags.
*/
v_uint32 escapeFlags = json::Utils::FLAG_ESCAPE_ALL;
};
public:
typedef void (*SerializerMethod)(Serializer*,
data::stream::ConsistentOutputStream*,
const oatpp::Void&);
private:
template<class T>
static void serializePrimitive(Serializer* serializer,
data::stream::ConsistentOutputStream* stream,
const oatpp::Void& polymorph){
(void) serializer;
if(polymorph){
stream->writeAsString(* static_cast<typename T::ObjectType*>(polymorph.get()));
} else {
stream->writeSimple("null", 4);
}
}
static void serializeString(oatpp::data::stream::ConsistentOutputStream* stream,
const char* data,
v_buff_size size,
v_uint32 escapeFlags);
static void serializeString(Serializer* serializer,
data::stream::ConsistentOutputStream* stream,
const oatpp::Void& polymorph);
static void serializeAny(Serializer* serializer,
data::stream::ConsistentOutputStream* stream,
const oatpp::Void& polymorph);
static void serializeEnum(Serializer* serializer,
data::stream::ConsistentOutputStream* stream,
const oatpp::Void& polymorph);
static void serializeCollection(Serializer* serializer,
data::stream::ConsistentOutputStream* stream,
const oatpp::Void& polymorph);
static void serializeMap(Serializer* serializer,
data::stream::ConsistentOutputStream* stream,
const oatpp::Void& polymorph);
static void serializeObject(Serializer* serializer,
data::stream::ConsistentOutputStream* stream,
const oatpp::Void& polymorph);
void serialize(data::stream::ConsistentOutputStream* stream, const oatpp::Void& polymorph);
private:
std::shared_ptr<Config> m_config;
std::vector<SerializerMethod> m_methods;
public:
/**
* Constructor.
* @param config - serializer config.
*/
Serializer(const std::shared_ptr<Config>& config = std::make_shared<Config>());
/**
* Set serializer method for type.
* @param classId - &id:oatpp::data::mapping::type::ClassId;.
* @param method - `typedef void (*SerializerMethod)(Serializer*, data::stream::ConsistentOutputStream*, const oatpp::Void&)`.
*/
void setSerializerMethod(const data::mapping::type::ClassId& classId, SerializerMethod method);
/**
* Serialize object to stream.
* @param stream - &id:oatpp::data::stream::ConsistentOutputStream;.
* @param polymorph - DTO as &id:oatpp::Void;.
*/
void serializeToStream(data::stream::ConsistentOutputStream* stream, const oatpp::Void& polymorph);
/**
* Get serializer config.
* @return
*/
const std::shared_ptr<Config>& getConfig();
};
}}}}
#endif /* oatpp_parser_json_mapping_Serializer_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/parser/json/mapping/Serializer.hpp
|
C++
|
apache-2.0
| 6,496
|
/***************************************************************************
*
* 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 "ApiClient.hpp"
#include "oatpp/core/data/stream/BufferStream.hpp"
namespace oatpp { namespace web { namespace client {
std::shared_ptr<RequestExecutor::ConnectionHandle> ApiClient::getConnection() {
return m_requestExecutor->getConnection();
}
oatpp::async::CoroutineStarterForResult<const std::shared_ptr<RequestExecutor::ConnectionHandle>&> ApiClient::getConnectionAsync() {
return m_requestExecutor->getConnectionAsync();
}
void ApiClient::invalidateConnection(const std::shared_ptr<RequestExecutor::ConnectionHandle>& connectionHandle) {
m_requestExecutor->invalidateConnection(connectionHandle);
}
ApiClient::StringTemplate ApiClient::parsePathTemplate(const oatpp::String& name, const oatpp::String& text) {
std::vector<StringTemplate::Variable> variables;
parser::Caret caret(text);
while(caret.canContinue()) {
if(caret.findChar('{')) {
caret.inc();
auto label = caret.putLabel();
caret.findChar('}');
label.end();
StringTemplate::Variable var;
var.posStart = label.getStartPosition() - 1;
var.posEnd = label.getEndPosition();
var.name = label.toString();
variables.push_back(var);
}
}
StringTemplate t(text, std::move(variables));
auto extra = std::make_shared<PathTemplateExtra>();
t.setExtraData(extra);
extra->name = name;
caret.setPosition(0);
extra->hasQueryParams = caret.findChar('?');
return t;
}
oatpp::String ApiClient::formatPath(const StringTemplate& pathTemplate,
const std::unordered_map<oatpp::String, oatpp::String>& pathParams,
const std::unordered_map<oatpp::String, oatpp::String>& queryParams)
{
data::stream::BufferOutputStream stream;
stream << pathTemplate.format(pathParams);
if(queryParams.size() > 0) {
auto extra = std::static_pointer_cast<PathTemplateExtra>(pathTemplate.getExtraData());
bool first = !extra->hasQueryParams;
for(const auto& q : queryParams) {
oatpp::String value = q.second;
if(value && value->size() > 0) {
if (first) {
stream.writeCharSimple('?');
first = false;
} else {
stream.writeCharSimple('&');
}
stream << q.first << "=" << value;
}
}
}
return stream.toString();
}
std::shared_ptr<ApiClient::Response> ApiClient::executeRequest(const oatpp::String& method,
const StringTemplate& pathTemplate,
const Headers& headers,
const std::unordered_map<oatpp::String, oatpp::String>& pathParams,
const std::unordered_map<oatpp::String, oatpp::String>& queryParams,
const std::shared_ptr<RequestExecutor::Body>& body,
const std::shared_ptr<RequestExecutor::ConnectionHandle>& connectionHandle)
{
return m_requestExecutor->execute(method,
formatPath(pathTemplate, pathParams, queryParams),
headers,
body,
connectionHandle);
}
oatpp::async::CoroutineStarterForResult<const std::shared_ptr<ApiClient::Response>&>
ApiClient::executeRequestAsync(const oatpp::String& method,
const StringTemplate& pathTemplate,
const Headers& headers,
const std::unordered_map<oatpp::String, oatpp::String>& pathParams,
const std::unordered_map<oatpp::String, oatpp::String>& queryParams,
const std::shared_ptr<RequestExecutor::Body>& body,
const std::shared_ptr<RequestExecutor::ConnectionHandle>& connectionHandle)
{
return m_requestExecutor->executeAsync(method,
formatPath(pathTemplate, pathParams, queryParams),
headers,
body,
connectionHandle);
}
}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/client/ApiClient.cpp
|
C++
|
apache-2.0
| 5,367
|
/***************************************************************************
*
* 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_client_Client_hpp
#define oatpp_web_client_Client_hpp
#include "./RequestExecutor.hpp"
#include "oatpp/web/protocol/http/incoming/Response.hpp"
#include "oatpp/web/protocol/http/outgoing/BufferBody.hpp"
#include "oatpp/encoding/Base64.hpp"
#include "oatpp/core/data/share/StringTemplate.hpp"
#include "oatpp/core/data/mapping/ObjectMapper.hpp"
#include "oatpp/core/Types.hpp"
#include "oatpp/core/utils/ConversionUtils.hpp"
#include <string>
#include <list>
#include <unordered_map>
namespace oatpp { namespace web { namespace client {
/**
* ApiClient class provides convenient Retrofit-like interface over the oatpp::web::client::RequestExecutor.
*/
class ApiClient : public oatpp::base::Countable {
public:
static constexpr const char* const TAG = "Client";
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;
public:
/**
* 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;
template <class T>
using Enum = oatpp::data::mapping::type::Enum<T>;
template <class T>
using Object = oatpp::Object<T>;
public:
typedef oatpp::data::share::StringTemplate StringTemplate;
/**
* Convenience typedef for &id:oatpp::web::protocol::http::Headers;.
*/
typedef oatpp::web::protocol::http::Headers Headers;
/**
* Convenience typedef for &id:oatpp::web::protocol::http::incoming::Response;.
*/
typedef oatpp::web::protocol::http::incoming::Response Response;
public:
/**
* Convenience typedef for &id:oatpp::web::client::RequestExecutor::AsyncCallback;.
*/
typedef RequestExecutor::AsyncCallback AsyncCallback;
protected:
struct PathTemplateExtra {
oatpp::String name;
bool hasQueryParams;
};
protected:
StringTemplate parsePathTemplate(const oatpp::String& name, const oatpp::String& text);
oatpp::String formatPath(const StringTemplate& pathTemplate,
const std::unordered_map<oatpp::String, oatpp::String>& pathParams,
const std::unordered_map<oatpp::String, oatpp::String>& queryParams);
protected:
std::shared_ptr<RequestExecutor> m_requestExecutor;
std::shared_ptr<oatpp::data::mapping::ObjectMapper> m_objectMapper;
public:
ApiClient(const std::shared_ptr<RequestExecutor>& requestExecutor,
const std::shared_ptr<oatpp::data::mapping::ObjectMapper>& objectMapper)
: m_requestExecutor(requestExecutor)
, m_objectMapper(objectMapper)
{}
public:
static std::shared_ptr<ApiClient> createShared(const std::shared_ptr<RequestExecutor>& requestExecutor,
const std::shared_ptr<data::mapping::ObjectMapper>& objectMapper) {
return std::make_shared<ApiClient>(requestExecutor, objectMapper);
}
public:
/**
* Call &id:oatpp::web::client::RequestExecutor::getConnection;.
* @return - &id:oatpp::web::client::RequestExecutor::ConnectionHandle;.
*/
virtual std::shared_ptr<RequestExecutor::ConnectionHandle> getConnection();
/**
* Call &id:oatpp::web::client::RequestExecutor::getConnectionAsync;.
* @return - &id:oatpp::async::CoroutineStarterForResult;.
*/
virtual oatpp::async::CoroutineStarterForResult<const std::shared_ptr<RequestExecutor::ConnectionHandle>&> getConnectionAsync();
/**
* Invalidate connection.
* @param connectionHandle
*/
void invalidateConnection(const std::shared_ptr<RequestExecutor::ConnectionHandle>& connectionHandle);
virtual std::shared_ptr<Response> executeRequest(const oatpp::String& method,
const StringTemplate& pathTemplate,
const Headers& headers,
const std::unordered_map<oatpp::String, oatpp::String>& pathParams,
const std::unordered_map<oatpp::String, oatpp::String>& queryParams,
const std::shared_ptr<RequestExecutor::Body>& body,
const std::shared_ptr<RequestExecutor::ConnectionHandle>& connectionHandle = nullptr);
virtual oatpp::async::CoroutineStarterForResult<const std::shared_ptr<Response>&>
executeRequestAsync(const oatpp::String& method,
const StringTemplate& pathTemplate,
const Headers& headers,
const std::unordered_map<oatpp::String, oatpp::String>& pathParams,
const std::unordered_map<oatpp::String, oatpp::String>& queryParams,
const std::shared_ptr<RequestExecutor::Body>& body,
const std::shared_ptr<RequestExecutor::ConnectionHandle>& connectionHandle = nullptr);
public:
template<typename T>
struct TypeInterpretation {
static oatpp::String toString(const oatpp::String& typeName, const T& parameter) {
(void) parameter;
OATPP_LOGE("[oatpp::web::client::ApiClient::TypeInterpretation::toString()]",
"Error. No conversion from '%s' to '%s' is defined.", typeName->c_str(), "oatpp::String");
throw std::runtime_error(
"[oatpp::web::client::ApiClient::TypeInterpretation::toString()]: Error. "
"No conversion from '" + *typeName + "' to 'oatpp::String' is defined. "
"Please define type conversion."
);
}
};
};
template<>
struct ApiClient::TypeInterpretation<oatpp::String> {
static oatpp::String toString(const oatpp::String &typeName, const oatpp::String ¶meter) {
(void) typeName;
return parameter;
}
};
template<>
struct ApiClient::TypeInterpretation<oatpp::Int8> {
static oatpp::String toString(const oatpp::String &typeName, const oatpp::Int8 ¶meter) {
(void) typeName;
if (parameter) {
return utils::conversion::int32ToStr(*parameter);
}
return nullptr;
}
};
template<>
struct ApiClient::TypeInterpretation<oatpp::UInt8> {
static oatpp::String toString(const oatpp::String &typeName, const oatpp::UInt8 ¶meter) {
(void) typeName;
if (parameter) {
return utils::conversion::uint32ToStr(*parameter);
}
return nullptr;
}
};
template<>
struct ApiClient::TypeInterpretation<oatpp::Int16> {
static oatpp::String toString(const oatpp::String &typeName, const oatpp::Int16 ¶meter) {
(void) typeName;
if (parameter) {
return utils::conversion::int32ToStr(*parameter);
}
return nullptr;
}
};
template<>
struct ApiClient::TypeInterpretation<oatpp::UInt16> {
static oatpp::String toString(const oatpp::String &typeName, const oatpp::UInt16 ¶meter) {
(void) typeName;
if (parameter) {
return utils::conversion::uint32ToStr(*parameter);
}
return nullptr;
}
};
template<>
struct ApiClient::TypeInterpretation<oatpp::Int32> {
static oatpp::String toString(const oatpp::String &typeName, const oatpp::Int32 ¶meter) {
(void) typeName;
if (parameter) {
return utils::conversion::int32ToStr(*parameter);
}
return nullptr;
}
};
template<>
struct ApiClient::TypeInterpretation<oatpp::UInt32> {
static oatpp::String toString(const oatpp::String &typeName, const oatpp::UInt32 ¶meter) {
(void) typeName;
if (parameter) {
return utils::conversion::uint32ToStr(*parameter);
}
return nullptr;
}
};
template<>
struct ApiClient::TypeInterpretation<oatpp::Int64> {
static oatpp::String toString(const oatpp::String &typeName, const oatpp::Int64 ¶meter) {
(void) typeName;
if (parameter) {
return utils::conversion::int64ToStr(*parameter);
}
return nullptr;
}
};
template<>
struct ApiClient::TypeInterpretation<oatpp::UInt64> {
static oatpp::String toString(const oatpp::String &typeName, const oatpp::UInt64 ¶meter) {
(void) typeName;
if (parameter) {
return utils::conversion::uint64ToStr(*parameter);
}
return nullptr;
}
};
template<>
struct ApiClient::TypeInterpretation<oatpp::Float32> {
static oatpp::String toString(const oatpp::String &typeName, const oatpp::Float32 ¶meter) {
(void) typeName;
if (parameter) {
return utils::conversion::float32ToStr(*parameter);
}
return nullptr;
}
};
template<>
struct ApiClient::TypeInterpretation<oatpp::Float64> {
static oatpp::String toString(const oatpp::String &typeName, const oatpp::Float64 ¶meter) {
(void) typeName;
if (parameter) {
return utils::conversion::float64ToStr(*parameter);
}
return nullptr;
}
};
template<>
struct ApiClient::TypeInterpretation<oatpp::Boolean> {
static oatpp::String toString(const oatpp::String &typeName, const oatpp::Boolean ¶meter) {
(void) typeName;
if(parameter != nullptr) {
return utils::conversion::boolToStr(*parameter);
}
return nullptr;
}
};
template<class T, class I>
struct ApiClient::TypeInterpretation<data::mapping::type::EnumObjectWrapper<T, I>> {
typedef data::mapping::type::EnumObjectWrapper<T, I> EnumOW;
typedef typename I::UnderlyingTypeObjectWrapper UTOW;
static oatpp::String toString(const oatpp::String &typeName, const EnumOW ¶meter) {
data::mapping::type::EnumInterpreterError error = data::mapping::type::EnumInterpreterError::OK;
const auto& value = I::toInterpretation(parameter, error);
switch(error){
case data::mapping::type::EnumInterpreterError::OK: break;
case data::mapping::type::EnumInterpreterError::CONSTRAINT_NOT_NULL:
throw std::runtime_error(
"[oatpp::web::client::ApiClient::TypeInterpretation::toString()]: Error. Enum constraint violation - NotNull."
);
default:
throw std::runtime_error(
"[oatpp::web::client::ApiClient::TypeInterpretation::toString()]: Error. Can't interpret Enum."
);
}
return ApiClient::TypeInterpretation<UTOW>::toString(typeName, value.template cast<UTOW>());
}
};
}}}
#endif /* oatpp_web_client_Client_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/web/client/ApiClient.hpp
|
C++
|
apache-2.0
| 12,514
|
/***************************************************************************
*
* 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 "HttpRequestExecutor.hpp"
#include "oatpp/web/protocol/http/incoming/ResponseHeadersReader.hpp"
#include "oatpp/web/protocol/http/outgoing/Request.hpp"
#include "oatpp/network/tcp/Connection.hpp"
#include "oatpp/core/data/stream/BufferStream.hpp"
#include "oatpp/core/data/stream/StreamBufferedProxy.hpp"
#if defined(WIN32) || defined(_WIN32)
#include <io.h>
#endif
namespace oatpp { namespace web { namespace client {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// HttpRequestExecutor::ConnectionProxy
HttpRequestExecutor::ConnectionProxy::ConnectionProxy(const provider::ResourceHandle<data::stream::IOStream>& connectionHandle)
: m_connectionHandle(connectionHandle)
, m_valid(true)
, m_invalidateOnDestroy(false)
{}
HttpRequestExecutor::ConnectionProxy::~ConnectionProxy() {
if(m_invalidateOnDestroy) {
invalidate();
}
}
v_io_size HttpRequestExecutor::ConnectionProxy::read(void *buffer, v_buff_size count, async::Action& action) {
return m_connectionHandle.object->read(buffer, count, action);
}
v_io_size HttpRequestExecutor::ConnectionProxy::write(const void *data, v_buff_size count, async::Action& action) {
return m_connectionHandle.object->write(data,count, action);
}
void HttpRequestExecutor::ConnectionProxy::setInputStreamIOMode(data::stream::IOMode ioMode) {
m_connectionHandle.object->setInputStreamIOMode(ioMode);
}
data::stream::IOMode HttpRequestExecutor::ConnectionProxy::getInputStreamIOMode() {
return m_connectionHandle.object->getInputStreamIOMode();
}
data::stream::Context& HttpRequestExecutor::ConnectionProxy::getInputStreamContext() {
return m_connectionHandle.object->getInputStreamContext();
}
void HttpRequestExecutor::ConnectionProxy::setOutputStreamIOMode(data::stream::IOMode ioMode) {
return m_connectionHandle.object->setOutputStreamIOMode(ioMode);
}
data::stream::IOMode HttpRequestExecutor::ConnectionProxy::getOutputStreamIOMode() {
return m_connectionHandle.object->getOutputStreamIOMode();
}
data::stream::Context& HttpRequestExecutor::ConnectionProxy::getOutputStreamContext() {
return m_connectionHandle.object->getOutputStreamContext();
}
void HttpRequestExecutor::ConnectionProxy::invalidate() {
if(m_valid) {
m_connectionHandle.invalidator->invalidate(m_connectionHandle.object);
m_valid = false;
}
}
void HttpRequestExecutor::ConnectionProxy::setInvalidateOnDestroy(bool invalidateOnDestroy) {
m_invalidateOnDestroy = invalidateOnDestroy;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// HttpRequestExecutor::HttpConnectionHandle
HttpRequestExecutor::HttpConnectionHandle::HttpConnectionHandle(const std::shared_ptr<ConnectionProxy>& connectionProxy)
: m_connectionProxy(connectionProxy)
{}
std::shared_ptr<HttpRequestExecutor::ConnectionProxy> HttpRequestExecutor::HttpConnectionHandle::getConnection() {
return m_connectionProxy;
}
void HttpRequestExecutor::HttpConnectionHandle::invalidate() {
m_connectionProxy->invalidate();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// HttpRequestExecutor
HttpRequestExecutor::HttpRequestExecutor(const std::shared_ptr<ClientConnectionProvider>& connectionProvider,
const std::shared_ptr<RetryPolicy>& retryPolicy,
const std::shared_ptr<const BodyDecoder>& bodyDecoder)
: RequestExecutor(retryPolicy)
, m_connectionProvider(connectionProvider)
, m_bodyDecoder(bodyDecoder)
{}
std::shared_ptr<HttpRequestExecutor>
HttpRequestExecutor::createShared(const std::shared_ptr<ClientConnectionProvider>& connectionProvider,
const std::shared_ptr<RetryPolicy>& retryPolicy,
const std::shared_ptr<const BodyDecoder>& bodyDecoder)
{
return std::make_shared<HttpRequestExecutor>(connectionProvider, retryPolicy, bodyDecoder);
}
std::shared_ptr<HttpRequestExecutor::ConnectionHandle> HttpRequestExecutor::getConnection() {
auto connection = m_connectionProvider->get();
if(!connection){
throw RequestExecutionError(RequestExecutionError::ERROR_CODE_CANT_CONNECT,
"[oatpp::web::client::HttpRequestExecutor::getConnection()]: ConnectionProvider failed to provide Connection");
}
auto connectionProxy = std::make_shared<ConnectionProxy>(connection);
return std::make_shared<HttpConnectionHandle>(connectionProxy);
}
oatpp::async::CoroutineStarterForResult<const std::shared_ptr<HttpRequestExecutor::ConnectionHandle>&>
HttpRequestExecutor::getConnectionAsync() {
class GetConnectionCoroutine : public oatpp::async::CoroutineWithResult<GetConnectionCoroutine, const std::shared_ptr<ConnectionHandle>&> {
private:
std::shared_ptr<ClientConnectionProvider> m_connectionProvider;
public:
GetConnectionCoroutine(const std::shared_ptr<ClientConnectionProvider>& connectionProvider)
: m_connectionProvider(connectionProvider)
{}
Action act() override {
return m_connectionProvider->getAsync().callbackTo(&GetConnectionCoroutine::onConnectionReady);
}
Action onConnectionReady(const provider::ResourceHandle<oatpp::data::stream::IOStream>& connection) {
auto connectionProxy = std::make_shared<ConnectionProxy>(connection);
return _return(std::make_shared<HttpConnectionHandle>(connectionProxy));
}
};
return GetConnectionCoroutine::startForResult(m_connectionProvider);
}
void HttpRequestExecutor::invalidateConnection(const std::shared_ptr<ConnectionHandle>& connectionHandle) {
if(connectionHandle) {
auto handle = static_cast<HttpConnectionHandle*>(connectionHandle.get());
handle->invalidate();
}
}
std::shared_ptr<HttpRequestExecutor::Response>
HttpRequestExecutor::executeOnce(const String& method,
const String& path,
const Headers& headers,
const std::shared_ptr<Body>& body,
const std::shared_ptr<ConnectionHandle>& connectionHandle) {
std::shared_ptr<ConnectionProxy> connection;
std::shared_ptr<HttpConnectionHandle> httpCH = std::static_pointer_cast<HttpConnectionHandle>(connectionHandle);
if(httpCH) {
connection = httpCH->getConnection();
}
if(!connection){
throw RequestExecutionError(RequestExecutionError::ERROR_CODE_CANT_CONNECT,
"[oatpp::web::client::HttpRequestExecutor::executeOnce()]: Connection is null");
}
connection->setInputStreamIOMode(data::stream::IOMode::BLOCKING);
connection->setOutputStreamIOMode(data::stream::IOMode::BLOCKING);
auto request = oatpp::web::protocol::http::outgoing::Request::createShared(method, path, headers, body);
oatpp::data::stream::BufferOutputStream hostValue;
hostValue << m_connectionProvider->getProperty("host").toString();
auto port = m_connectionProvider->getProperty("port");
if(port) {
hostValue << ":" << port.toString();
}
request->putHeaderIfNotExists_Unsafe(oatpp::web::protocol::http::Header::HOST, hostValue.toString());
request->putHeaderIfNotExists_Unsafe(oatpp::web::protocol::http::Header::CONNECTION, oatpp::web::protocol::http::Header::Value::CONNECTION_KEEP_ALIVE);
oatpp::data::share::MemoryLabel buffer(std::make_shared<std::string>(oatpp::data::buffer::IOBuffer::BUFFER_SIZE, 0));
oatpp::data::stream::OutputStreamBufferedProxy upStream(connection, buffer);
request->send(&upStream);
upStream.flush();
oatpp::web::protocol::http::incoming::ResponseHeadersReader headerReader(buffer, 4096);
oatpp::web::protocol::http::HttpError::Info error;
const auto& result = headerReader.readHeaders(connection, error);
if(error.status.code != 0) {
connection->invalidate();
throw RequestExecutionError(RequestExecutionError::ERROR_CODE_CANT_PARSE_STARTING_LINE,
"[oatpp::web::client::HttpRequestExecutor::executeOnce()]: Failed to parse response. Invalid response headers");
}
if(error.ioStatus < 0) {
connection->invalidate();
throw RequestExecutionError(RequestExecutionError::ERROR_CODE_CANT_PARSE_STARTING_LINE,
"[oatpp::web::client::HttpRequestExecutor::executeOnce()]: Failed to read response.");
}
auto connectionHeader = result.headers.getAsMemoryLabel<oatpp::data::share::StringKeyLabelCI>(Header::CONNECTION);
if (connectionHeader == "close") {
connection->setInvalidateOnDestroy(true);
}
auto bodyStream = oatpp::data::stream::InputStreamBufferedProxy::createShared(connection,
buffer,
result.bufferPosStart,
result.bufferPosEnd,
result.bufferPosStart != result.bufferPosEnd);
return Response::createShared(result.startingLine.statusCode,
result.startingLine.description.toString(),
result.headers, bodyStream, m_bodyDecoder);
}
oatpp::async::CoroutineStarterForResult<const std::shared_ptr<HttpRequestExecutor::Response>&>
HttpRequestExecutor::executeOnceAsync(const String& method,
const String& path,
const Headers& headers,
const std::shared_ptr<Body>& body,
const std::shared_ptr<ConnectionHandle>& connectionHandle) {
typedef protocol::http::incoming::ResponseHeadersReader ResponseHeadersReader;
class ExecutorCoroutine : public oatpp::async::CoroutineWithResult<ExecutorCoroutine, const std::shared_ptr<HttpRequestExecutor::Response>&> {
private:
typedef oatpp::web::protocol::http::outgoing::Request OutgoingRequest;
private:
HttpRequestExecutor* m_this;
String m_method;
String m_path;
Headers m_headers;
std::shared_ptr<Body> m_body;
std::shared_ptr<const BodyDecoder> m_bodyDecoder;
std::shared_ptr<HttpConnectionHandle> m_connectionHandle;
oatpp::data::share::MemoryLabel m_buffer;
ResponseHeadersReader m_headersReader;
std::shared_ptr<oatpp::data::stream::OutputStreamBufferedProxy> m_upstream;
private:
std::shared_ptr<ConnectionProxy> m_connection;
public:
ExecutorCoroutine(HttpRequestExecutor* _this,
const String& method,
const String& path,
const Headers& headers,
const std::shared_ptr<Body>& body,
const std::shared_ptr<const BodyDecoder>& bodyDecoder,
const std::shared_ptr<HttpConnectionHandle>& connectionHandle)
: m_this(_this)
, m_method(method)
, m_path(path)
, m_headers(headers)
, m_body(body)
, m_bodyDecoder(bodyDecoder)
, m_connectionHandle(connectionHandle)
, m_buffer(std::make_shared<std::string>(oatpp::data::buffer::IOBuffer::BUFFER_SIZE, 0))
, m_headersReader(m_buffer, 4096)
{}
Action act() override {
if(m_connectionHandle) {
m_connection = m_connectionHandle->getConnection();
}
if(!m_connection) {
throw RequestExecutionError(RequestExecutionError::ERROR_CODE_CANT_CONNECT,
"[oatpp::web::client::HttpRequestExecutor::executeOnceAsync::ExecutorCoroutine{act()}]: Connection is null");
}
m_connection->setInputStreamIOMode(data::stream::IOMode::ASYNCHRONOUS);
m_connection->setOutputStreamIOMode(data::stream::IOMode::ASYNCHRONOUS);
auto request = OutgoingRequest::createShared(m_method, m_path, m_headers, m_body);
oatpp::data::stream::BufferOutputStream hostValue;
hostValue << m_this->m_connectionProvider->getProperty("host").toString();
auto port = m_this->m_connectionProvider->getProperty("port");
if(port) {
hostValue << ":" << port.toString();
}
request->putHeaderIfNotExists_Unsafe(Header::HOST, hostValue.toString());
request->putHeaderIfNotExists_Unsafe(Header::CONNECTION, Header::Value::CONNECTION_KEEP_ALIVE);
m_upstream = oatpp::data::stream::OutputStreamBufferedProxy::createShared(m_connection, m_buffer);
return OutgoingRequest::sendAsync(request, m_upstream).next(m_upstream->flushAsync()).next(yieldTo(&ExecutorCoroutine::readResponse));
}
Action readResponse() {
return m_headersReader.readHeadersAsync(m_connection).callbackTo(&ExecutorCoroutine::onHeadersParsed);
}
Action onHeadersParsed(const ResponseHeadersReader::Result& result) {
auto connectionHeader = result.headers.getAsMemoryLabel<oatpp::data::share::StringKeyLabelCI>(Header::CONNECTION);
if (connectionHeader == "close") {
m_connection->setInvalidateOnDestroy(true);
}
auto bodyStream = oatpp::data::stream::InputStreamBufferedProxy::createShared(m_connection,
m_buffer,
result.bufferPosStart,
result.bufferPosEnd,
result.bufferPosStart != result.bufferPosEnd);
return _return(Response::createShared(result.startingLine.statusCode,
result.startingLine.description.toString(),
result.headers, bodyStream, m_bodyDecoder));
}
Action handleError(oatpp::async::Error* error) override {
if(m_connection) {
m_connection->invalidate();
}
return error;
}
};
auto httpCH = std::static_pointer_cast<HttpConnectionHandle>(connectionHandle);
return ExecutorCoroutine::startForResult(this, method, path, headers, body, m_bodyDecoder, httpCH);
}
}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/client/HttpRequestExecutor.cpp
|
C++
|
apache-2.0
| 15,516
|
/***************************************************************************
*
* 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_client_HttpRequestExecutor_hpp
#define oatpp_web_client_HttpRequestExecutor_hpp
#include "./RequestExecutor.hpp"
#include "oatpp/web/protocol/http/incoming/SimpleBodyDecoder.hpp"
#include "oatpp/network/ConnectionPool.hpp"
#include "oatpp/network/ConnectionProvider.hpp"
namespace oatpp { namespace web { namespace client {
/**
* Default implementation of &id:oatpp::web::client::RequestExecutor; for making http request.
*/
class HttpRequestExecutor : public oatpp::base::Countable, public RequestExecutor {
private:
typedef oatpp::web::protocol::http::Header Header;
typedef oatpp::network::ClientConnectionProvider ClientConnectionProvider;
typedef oatpp::web::protocol::http::incoming::BodyDecoder BodyDecoder;
protected:
std::shared_ptr<ClientConnectionProvider> m_connectionProvider;
std::shared_ptr<const BodyDecoder> m_bodyDecoder;
public:
class ConnectionProxy : public data::stream::IOStream {
private:
provider::ResourceHandle<data::stream::IOStream> m_connectionHandle;
bool m_valid;
bool m_invalidateOnDestroy;
public:
ConnectionProxy(const provider::ResourceHandle<data::stream::IOStream>& connectionHandle);
~ConnectionProxy() override;
v_io_size read(void *buffer, v_buff_size count, async::Action& action) override;
v_io_size write(const void *data, v_buff_size count, async::Action& action) override;
void setInputStreamIOMode(data::stream::IOMode ioMode) override;
data::stream::IOMode getInputStreamIOMode() override;
data::stream::Context& getInputStreamContext() override;
void setOutputStreamIOMode(data::stream::IOMode ioMode) override;
data::stream::IOMode getOutputStreamIOMode() override;
data::stream::Context& getOutputStreamContext() override;
void invalidate();
void setInvalidateOnDestroy(bool invalidateOnDestroy);
};
public:
/**
* Connection handle for &l:HttpRequestExecutor; <br>
* For more details see &id:oatpp::web::client::RequestExecutor::ConnectionHandle;.
*/
class HttpConnectionHandle : public ConnectionHandle {
private:
std::shared_ptr<ConnectionProxy> m_connectionProxy;
public:
HttpConnectionHandle(const std::shared_ptr<ConnectionProxy>& connectionProxy);
std::shared_ptr<ConnectionProxy> getConnection();
void invalidate();
};
public:
/**
* Constructor.
* @param connectionProvider - &id:oatpp::network::ClientConnectionProvider;.
* @param bodyDecoder - &id:oatpp::web::protocol::http::incoming::BodyDecoder;.
*/
HttpRequestExecutor(const std::shared_ptr<ClientConnectionProvider>& connectionProvider,
const std::shared_ptr<RetryPolicy>& retryPolicy = nullptr,
const std::shared_ptr<const BodyDecoder>& bodyDecoder =
std::make_shared<oatpp::web::protocol::http::incoming::SimpleBodyDecoder>());
public:
/**
* Create shared HttpRequestExecutor.
* @param connectionProvider - &id:oatpp::network::ClientConnectionProvider;.
* @param bodyDecoder - &id:oatpp::web::protocol::http::incoming::BodyDecoder;.
* @return - `std::shared_ptr` to `HttpRequestExecutor`.
*/
static std::shared_ptr<HttpRequestExecutor>
createShared(const std::shared_ptr<ClientConnectionProvider>& connectionProvider,
const std::shared_ptr<RetryPolicy>& retryPolicy = nullptr,
const std::shared_ptr<const BodyDecoder>& bodyDecoder =
std::make_shared<oatpp::web::protocol::http::incoming::SimpleBodyDecoder>());
/**
* Get &id:oatpp::web::client::RequestExecutor::ConnectionHandle;
* @return - ConnectionHandle which is &l:HttpRequestExecutor::HttpConnectionHandle;.
*/
std::shared_ptr<ConnectionHandle> getConnection() override;
/**
* Same as &l:HttpRequestExecutor::getConnection (); but async.
* @return - &id:oatpp::async::CoroutineStarterForResult;.
*/
oatpp::async::CoroutineStarterForResult<const std::shared_ptr<HttpRequestExecutor::ConnectionHandle>&> getConnectionAsync() override;
/**
* Invalidate connection.
* @param connectionHandle
*/
void invalidateConnection(const std::shared_ptr<ConnectionHandle>& connectionHandle) override;
/**
* Execute http request.
* @param method - method ex: ["GET", "POST", "PUT", etc.].
* @param path - path to resource.
* @param headers - headers map &id:oatpp::web::client::RequestExecutor::Headers;.
* @param body - `std::shared_ptr` to &id:oatpp::web::client::RequestExecutor::Body; object.
* @param connectionHandle - ConnectionHandle obtain in call to &l:HttpRequestExecutor::getConnection ();.
* @return - &id:oatpp::web::protocol::http::incoming::Response;.
* @throws - &id:oatpp::web::client::RequestExecutor::RequestExecutionError;
*/
std::shared_ptr<Response> executeOnce(const String& method,
const String& path,
const Headers& headers,
const std::shared_ptr<Body>& body,
const std::shared_ptr<ConnectionHandle>& connectionHandle = nullptr) override;
/**
* Same as &l:HttpRequestExecutor::execute (); but Async.
* @param method - method ex: ["GET", "POST", "PUT", etc.].
* @param path - path to resource.
* @param headers - headers map &id:oatpp::web::client::RequestExecutor::Headers;.
* @param body - `std::shared_ptr` to &id:oatpp::web::client::RequestExecutor::Body; object.
* @param connectionHandle - ConnectionHandle obtain in call to &l:HttpRequestExecutor::getConnection ();.
* @return - &id:oatpp::async::CoroutineStarterForResult;.
*/
oatpp::async::CoroutineStarterForResult<const std::shared_ptr<Response>&>
executeOnceAsync(const String& method,
const String& path,
const Headers& headers,
const std::shared_ptr<Body>& body,
const std::shared_ptr<ConnectionHandle>& connectionHandle = nullptr) override;
};
}}}
#endif /* oatpp_web_client_HttpRequestExecutor_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/web/client/HttpRequestExecutor.hpp
|
C++
|
apache-2.0
| 7,093
|
/***************************************************************************
*
* 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 "RequestExecutor.hpp"
#include <thread>
#include <chrono>
namespace oatpp { namespace web { namespace client {
RequestExecutor::RequestExecutionError::RequestExecutionError(v_int32 errorCode, const char* message, v_int32 readErrorCode)
: std::runtime_error(message)
, m_errorCode(errorCode)
, m_message(message)
, m_readErrorCode(readErrorCode)
{}
v_int32 RequestExecutor::RequestExecutionError::getErrorCode() const {
return m_errorCode;
}
const char* RequestExecutor::RequestExecutionError::getMessage() const {
return m_message;
}
v_int32 RequestExecutor::RequestExecutionError::getReadErrorCode() const {
return m_readErrorCode;
}
RequestExecutor::RequestExecutor(const std::shared_ptr<RetryPolicy>& retryPolicy)
: m_retryPolicy(retryPolicy)
{}
std::shared_ptr<RequestExecutor::Response> RequestExecutor::execute(
const String& method,
const String& path,
const Headers& headers,
const std::shared_ptr<Body>& body,
const std::shared_ptr<ConnectionHandle>& connectionHandle
) {
if(!m_retryPolicy) {
auto ch = connectionHandle;
if (!ch) {
ch = getConnection();
}
return executeOnce(method, path, headers, body, ch);
} else {
RetryPolicy::Context context;
auto ch = connectionHandle;
while(true) {
context.attempt ++;
try {
if (!ch) {
ch = getConnection();
}
auto response = executeOnce(method, path, headers, body, ch);
if(!m_retryPolicy->retryOnResponse(response->getStatusCode(), context) || !m_retryPolicy->canRetry(context)) {
return response;
}
} catch (...) {
if(!m_retryPolicy->canRetry(context)) {
break;
}
}
invalidateConnection(ch);
ch.reset();
v_int64 waitMicro = m_retryPolicy->waitForMicroseconds(context);
v_int64 tick0 = oatpp::base::Environment::getMicroTickCount();
v_int64 tick = tick0;
while(tick < tick0 + waitMicro) {
std::this_thread::sleep_for(std::chrono::microseconds(tick0 + waitMicro - tick));
tick = oatpp::base::Environment::getMicroTickCount();
}
}
}
return nullptr;
}
oatpp::async::CoroutineStarterForResult<const std::shared_ptr<RequestExecutor::Response>&>
RequestExecutor::executeAsync(
const String& method,
const String& path,
const Headers& headers,
const std::shared_ptr<Body>& body,
const std::shared_ptr<ConnectionHandle>& connectionHandle
) {
class ExecutorCoroutine : public oatpp::async::CoroutineWithResult<ExecutorCoroutine, const std::shared_ptr<RequestExecutor::Response>&> {
private:
RequestExecutor* m_this;
String m_method;
String m_path;
Headers m_headers;
std::shared_ptr<Body> m_body;
std::shared_ptr<ConnectionHandle> m_connectionHandle;
RetryPolicy::Context m_context;
public:
ExecutorCoroutine(RequestExecutor* _this,
const String& method,
const String& path,
const Headers& headers,
const std::shared_ptr<Body>& body,
const std::shared_ptr<ConnectionHandle>& connectionHandle)
: m_this(_this)
, m_method(method)
, m_path(path)
, m_headers(headers)
, m_body(body)
, m_connectionHandle(connectionHandle)
{}
Action act() override {
if(!m_connectionHandle) {
return m_this->getConnectionAsync().callbackTo(&ExecutorCoroutine::onConnection);
}
return yieldTo(&ExecutorCoroutine::execute);
}
Action onConnection(const std::shared_ptr<ConnectionHandle>& connectionHandle) {
m_connectionHandle = connectionHandle;
return yieldTo(&ExecutorCoroutine::execute);
}
Action execute() {
m_context.attempt ++;
return m_this->executeOnceAsync(m_method, m_path, m_headers, m_body, m_connectionHandle).callbackTo(&ExecutorCoroutine::onResponse);
}
Action onResponse(const std::shared_ptr<RequestExecutor::Response>& response) {
if( m_this->m_retryPolicy &&
m_this->m_retryPolicy->retryOnResponse(response->getStatusCode(), m_context) &&
m_this->m_retryPolicy->canRetry(m_context)
) {
return yieldTo(&ExecutorCoroutine::retry);
}
return _return(response);
}
Action retry() {
if(m_connectionHandle) {
m_this->invalidateConnection(m_connectionHandle);
m_connectionHandle.reset();
}
return waitFor(std::chrono::microseconds(m_this->m_retryPolicy->waitForMicroseconds(m_context))).next(yieldTo(&ExecutorCoroutine::act));
}
Action handleError(Error* error) override {
if(m_this->m_retryPolicy && m_this->m_retryPolicy->canRetry(m_context)) {
return yieldTo(&ExecutorCoroutine::retry);
}
if(m_connectionHandle) {
m_this->invalidateConnection(m_connectionHandle);
m_connectionHandle.reset();
}
return error;
}
};
return ExecutorCoroutine::startForResult(this, method, path, headers, body, connectionHandle);
}
}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/client/RequestExecutor.cpp
|
C++
|
apache-2.0
| 6,080
|
/***************************************************************************
*
* 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_client_RequestExecutor_hpp
#define oatpp_web_client_RequestExecutor_hpp
#include "RetryPolicy.hpp"
#include "oatpp/web/protocol/http/incoming/Response.hpp"
#include "oatpp/web/protocol/http/outgoing/Body.hpp"
#include "oatpp/web/protocol/http/Http.hpp"
namespace oatpp { namespace web { namespace client {
/**
* Abstract RequestExecutor.
* RequestExecutor is class responsible for making remote requests.
*/
class RequestExecutor {
public:
/**
* Convenience typedef for &id:oatpp::String;.
*/
typedef oatpp::String String;
/**
* Convenience typedef for &id:oatpp::async::Action;.
*/
typedef oatpp::async::Action Action;
public:
/**
* Convenience typedef for &id:oatpp::web::protocol::http::Headers;.
*/
typedef oatpp::web::protocol::http::Headers Headers;
/**
* Convenience typedef for &id:oatpp::web::protocol::http::incoming::Response;.
*/
typedef oatpp::web::protocol::http::incoming::Response Response;
/**
* Convenience typedef for &id:oatpp::web::protocol::http::outgoing::Body;.
*/
typedef oatpp::web::protocol::http::outgoing::Body Body;
public:
/**
* ConnectionHandle is always specific to a RequestExecutor.
* You can't pass ConnectionHandle retrieved by one RequestExecutor implementation
* to another
*/
class ConnectionHandle {
public:
virtual ~ConnectionHandle() {}
};
public:
typedef Action (oatpp::async::AbstractCoroutine::*AsyncCallback)(const std::shared_ptr<Response>&);
typedef Action (oatpp::async::AbstractCoroutine::*AsyncConnectionCallback)(const std::shared_ptr<ConnectionHandle>&);
public:
/**
* Class representing Request Execution Error.
*/
class RequestExecutionError : public std::runtime_error {
public:
/**
* Error code for "can't connect" error.
*/
constexpr static const v_int32 ERROR_CODE_CANT_CONNECT = 1;
/**
* Error code for "can't parse starting line" error.
*/
constexpr static const v_int32 ERROR_CODE_CANT_PARSE_STARTING_LINE = 2;
/**
* Error code for "can't parse headers" error.
*/
constexpr static const v_int32 ERROR_CODE_CANT_PARSE_HEADERS = 3;
/**
* Error code for "can't read response" error.
*/
constexpr static const v_int32 ERROR_CODE_CANT_READ_RESPONSE = 4;
/**
* Error code for "no response" error.
*/
constexpr static const v_int32 ERROR_CODE_NO_RESPONSE = 5;
private:
v_int32 m_errorCode;
const char* m_message;
v_int32 m_readErrorCode;
public:
/**
* Constructor.
* @param errorCode - error code.
* @param message - error message.
* @param readErrorCode - io error code.
*/
RequestExecutionError(v_int32 errorCode, const char* message, v_int32 readErrorCode = 0);
/**
* Get error code.
* @return - error code.
*/
v_int32 getErrorCode() const;
/**
* Get error message.
* @return - error message.
*/
const char* getMessage() const;
/**
* This value is valid if errorCode == &l:RequestExecutor::RequestExecutionError::ERROR_CODE_CANT_READ_RESPONSE; <br>
* For more information about the read error you get check out:
* <ul>
* <li>&id:oatpp::data::stream::IOStream; for possible error codes.</li>
* <li>Implementation-specific behaviour of corresponding Connection and ConnectionProvider.</li>
* </ul>
*/
v_int32 getReadErrorCode() const;
};
private:
std::shared_ptr<RetryPolicy> m_retryPolicy;
public:
/**
* Constructor.
* @param retryPolicy - &id:oatpp::web::client::RetryPolicy;.
*/
RequestExecutor(const std::shared_ptr<RetryPolicy>& retryPolicy);
/**
* Virtual destructor.
*/
virtual ~RequestExecutor() = default;
/**
* Obtain &l:RequestExecutor::ConnectionHandle; which then can be passed to &l:RequestExecutor::execute ();.
* @return std::shared_ptr to &l:RequestExecutor::ConnectionHandle;.
*/
virtual std::shared_ptr<ConnectionHandle> getConnection() = 0;
/**
* Same as &l:RequestExecutor::getConnection (); but Async.
* @return - &id:oatpp::async::CoroutineStarterForResult;.
*/
virtual oatpp::async::CoroutineStarterForResult<const std::shared_ptr<ConnectionHandle>&> getConnectionAsync() = 0;
/**
* Invalidate connection.
* @param connectionHandle
*/
virtual void invalidateConnection(const std::shared_ptr<ConnectionHandle>& connectionHandle) = 0;
/**
* Execute request once without any retries.
* @param method - method ex: ["GET", "POST", "PUT", etc.].
* @param path - path to resource.
* @param headers - headers map &l:RequestExecutor::Headers;.
* @param body - `std::shared_ptr` to &l:RequestExecutor::Body; object.
* @param connectionHandle - &l:RequestExecutor::ConnectionHandle;
* @return - &id:oatpp::web::protocol::http::incoming::Response;.
*/
virtual std::shared_ptr<Response> executeOnce(const String& method,
const String& path,
const Headers& headers,
const std::shared_ptr<Body>& body,
const std::shared_ptr<ConnectionHandle>& connectionHandle) = 0;
/**
* Same as &l:RequestExecutor::executeOnce (); but Async.
* @param method - method ex: ["GET", "POST", "PUT", etc.].
* @param path - path to resource.
* @param headers - headers map &l:RequestExecutor::Headers;.
* @param body - `std::shared_ptr` to &l:RequestExecutor::Body; object.
* @param connectionHandle - &l:RequestExecutor::ConnectionHandle;.
* @return - &id:oatpp::async::CoroutineStarterForResult;.
*/
virtual oatpp::async::CoroutineStarterForResult<const std::shared_ptr<Response>&>
executeOnceAsync(const String& method,
const String& path,
const Headers& headers,
const std::shared_ptr<Body>& body,
const std::shared_ptr<ConnectionHandle>& connectionHandle) = 0;
/**
* Execute request taking into account retry policy.
* @param method - method ex: ["GET", "POST", "PUT", etc.].
* @param path - path to resource.
* @param headers - headers map &l:RequestExecutor::Headers;.
* @param body - `std::shared_ptr` to &l:RequestExecutor::Body; object.
* @param connectionHandle - &l:RequestExecutor::ConnectionHandle;
* @return - &id:oatpp::web::protocol::http::incoming::Response;.
*/
virtual std::shared_ptr<Response> execute(const String& method,
const String& path,
const Headers& headers,
const std::shared_ptr<Body>& body,
const std::shared_ptr<ConnectionHandle>& connectionHandle);
/**
* Same as &l:RequestExecutor::execute (); but Async.
* @param method - method ex: ["GET", "POST", "PUT", etc.].
* @param path - path to resource.
* @param headers - headers map &l:RequestExecutor::Headers;.
* @param body - `std::shared_ptr` to &l:RequestExecutor::Body; object.
* @param connectionHandle - &l:RequestExecutor::ConnectionHandle;.
* @return - &id:oatpp::async::CoroutineStarterForResult;.
*/
oatpp::async::CoroutineStarterForResult<const std::shared_ptr<Response>&>
virtual executeAsync(const String& method,
const String& path,
const Headers& headers,
const std::shared_ptr<Body>& body,
const std::shared_ptr<ConnectionHandle>& connectionHandle);
};
}}}
#endif /* oatpp_web_client_RequestExecutor_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/web/client/RequestExecutor.hpp
|
C++
|
apache-2.0
| 8,760
|
/***************************************************************************
*
* 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 "RetryPolicy.hpp"
namespace oatpp { namespace web { namespace client {
SimpleRetryPolicy::SimpleRetryPolicy(v_int64 maxAttempts,
const std::chrono::duration<v_int64, std::micro>& delay,
const std::unordered_set<v_int32>& httpCodes)
: m_maxAttempts(maxAttempts)
, m_delay(delay.count())
, m_httpCodes(httpCodes)
{}
bool SimpleRetryPolicy::canRetry(const Context& context) {
return context.attempt <= m_maxAttempts || m_maxAttempts == -1;
}
bool SimpleRetryPolicy::retryOnResponse(v_int32 responseStatusCode, const Context& context) {
(void) context;
return m_httpCodes.find(responseStatusCode) != m_httpCodes.end();
}
v_int64 SimpleRetryPolicy::waitForMicroseconds(const Context& context) {
(void) context;
return m_delay;
}
}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/client/RetryPolicy.cpp
|
C++
|
apache-2.0
| 1,829
|
/***************************************************************************
*
* 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_client_RetryPolicy_hpp
#define oatpp_web_client_RetryPolicy_hpp
#include "oatpp/core/Types.hpp"
#include <unordered_set>
namespace oatpp { namespace web { namespace client {
/**
* Class to control retries in RequestExecutor.
*/
class RetryPolicy {
public:
/**
* This structure holds information about request attempts.
*/
struct Context {
/**
* Attempt number.
*/
v_int64 attempt = 0;
};
public:
/**
* Virtual destructor.
*/
virtual ~RetryPolicy() = default;
/**
* Check if the context is eligible to retry.
* @param context - &l:RetryPolicy::Context ;.
* @return - `true` - to retry. `false` - do NOT retry.
*/
virtual bool canRetry(const Context& context) = 0;
/**
* Check whether the client should retry for a given response from the server.
* @param responseStatusCode - HTTP status code of the response.
* @param context - &l:RetryPolicy::Context ;.
* @return - `true` - to retry. `false` - do NOT retry.
*/
virtual bool retryOnResponse(v_int32 responseStatusCode, const Context& context) = 0;
/**
* How much client should wait before the next attempt?
* @param context - &l:RetryPolicy::Context ;.
* @return - delay in microseconds.
*/
virtual v_int64 waitForMicroseconds(const Context& context) = 0;
};
class SimpleRetryPolicy : public RetryPolicy {
private:
v_int64 m_maxAttempts;
v_int64 m_delay;
std::unordered_set<v_int32> m_httpCodes;
public:
/**
* Constructor.
* @param maxAttempts - max number of attempts to retry. `-1` - retry infinitely.
* @param delay - delay between attempts.
* @param httpCodes - set of HTTP codes to retry for.
*/
SimpleRetryPolicy(v_int64 maxAttempts,
const std::chrono::duration<v_int64, std::micro>& delay,
const std::unordered_set<v_int32>& httpCodes = {503});
/**
* Check if the context is eligible to retry.
* @param context - &l:RetryPolicy::Context ;.
* @return - `true` - to retry. `false` - do NOT retry.
*/
bool canRetry(const Context& context) override;
/**
* Check whether the client should retry for a given response from the server. <br>
* *This particular implementation returns `true` for codes from the set provided in the constructor*.
* @param responseStatusCode - HTTP status code of the response.
* @param context - &l:RetryPolicy::Context ;.
* @return - `true` - to retry. `false` - do NOT retry.
*/
bool retryOnResponse(v_int32 responseStatusCode, const Context& context) override;
/**
* How much client should wait before the next attempt? <br>
* *This particular implementation returns the delay passed to the constructor*.
* @param context - &l:RetryPolicy::Context ;.
* @return - delay in microseconds.
*/
v_int64 waitForMicroseconds(const Context& context) override;
};
}}}
#endif // oatpp_web_client_RetryPolicy_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/web/client/RetryPolicy.hpp
|
C++
|
apache-2.0
| 3,933
|
/***************************************************************************
*
* 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 "FileProvider.hpp"
#include "oatpp/core/data/resource/File.hpp"
namespace oatpp { namespace web { namespace mime { namespace multipart {
FileProvider::FileProvider(const oatpp::String& filename)
: m_filename(filename)
{}
std::shared_ptr<data::resource::Resource> FileProvider::getResource(const std::shared_ptr<Part>& part) {
(void)part;
return std::make_shared<data::resource::File>(m_filename->c_str());
}
async::CoroutineStarter FileProvider::getResourceAsync(const std::shared_ptr<Part>& part,
std::shared_ptr<data::resource::Resource>& stream)
{
(void)part;
stream = std::make_shared<data::resource::File>(m_filename->c_str());
return nullptr;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Other functions
std::shared_ptr<PartReader> createFilePartReader(const oatpp::String& filename, v_io_size maxDataSize) {
auto provider = std::make_shared<FileProvider>(filename);
auto reader = std::make_shared<StreamPartReader>(provider, maxDataSize);
return reader;
}
std::shared_ptr<AsyncPartReader> createAsyncFilePartReader(const oatpp::String& filename, v_io_size maxDataSize) {
auto provider = std::make_shared<FileProvider>(filename);
auto reader = std::make_shared<AsyncStreamPartReader>(provider, maxDataSize);
return reader;
}
}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/mime/multipart/FileProvider.cpp
|
C++
|
apache-2.0
| 2,410
|
/***************************************************************************
*
* 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_mime_multipart_FileProvider_hpp
#define oatpp_web_mime_multipart_FileProvider_hpp
#include "PartReader.hpp"
#include "Reader.hpp"
namespace oatpp { namespace web { namespace mime { namespace multipart {
class FileProvider : public PartReaderResourceProvider {
private:
oatpp::String m_filename;
public:
FileProvider(const oatpp::String& filename);
std::shared_ptr<data::resource::Resource> getResource(const std::shared_ptr<Part>& part) override;
async::CoroutineStarter getResourceAsync(const std::shared_ptr<Part>& part,
std::shared_ptr<data::resource::Resource>& resource) override;
};
/**
* Create file part reader. <br>
* Reader will save part to a specified file.
* @param filename - name of the file.
* @param maxDataSize - max size of the received data. put `-1` for no-limit.
* @return - `std::shared_ptr` to &id:oatpp::web::mime::multipart::PartReader;.
*/
std::shared_ptr<PartReader> createFilePartReader(const oatpp::String& filename, v_io_size maxDataSize = -1);
/**
* Create async file part reader. <br>
* Reader will save part to a specified file.
* @param filename - name of the file.
* @param maxDataSize - max size of the received data. put `-1` for no-limit.
* @return - `std::shared_ptr` to &id:oatpp::web::mime::multipart::AsyncPartReader;.
*/
std::shared_ptr<AsyncPartReader> createAsyncFilePartReader(const oatpp::String& filename, v_io_size maxDataSize = -1);
}}}}
#endif //oatpp_web_mime_multipart_FileProvider_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/web/mime/multipart/FileProvider.hpp
|
C++
|
apache-2.0
| 2,528
|
/***************************************************************************
*
* 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 "InMemoryDataProvider.hpp"
#include "oatpp/core/data/resource/InMemoryData.hpp"
namespace oatpp { namespace web { namespace mime { namespace multipart {
std::shared_ptr<data::resource::Resource> InMemoryDataProvider::getResource(const std::shared_ptr<Part>& part) {
(void)part;
return std::make_shared<data::resource::InMemoryData>();
}
async::CoroutineStarter InMemoryDataProvider::getResourceAsync(const std::shared_ptr<Part>& part,
std::shared_ptr<data::resource::Resource>& resource)
{
(void)part;
resource = std::make_shared<data::resource::InMemoryData>();
return nullptr;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Other functions
std::shared_ptr<PartReader> createInMemoryPartReader(v_io_size maxDataSize) {
auto provider = std::make_shared<InMemoryDataProvider>();
auto reader = std::make_shared<StreamPartReader>(provider, maxDataSize);
return reader;
}
std::shared_ptr<AsyncPartReader> createAsyncInMemoryPartReader(v_io_size maxDataSize) {
auto provider = std::make_shared<InMemoryDataProvider>();
auto reader = std::make_shared<AsyncStreamPartReader>(provider, maxDataSize);
return reader;
}
}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/mime/multipart/InMemoryDataProvider.cpp
|
C++
|
apache-2.0
| 2,291
|
/***************************************************************************
*
* 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_mime_multipart_InMemoryDataProvider_hpp
#define oatpp_web_mime_multipart_InMemoryDataProvider_hpp
#include "PartReader.hpp"
#include "Reader.hpp"
namespace oatpp { namespace web { namespace mime { namespace multipart {
class InMemoryDataProvider : public PartReaderResourceProvider {
public:
std::shared_ptr<data::resource::Resource> getResource(const std::shared_ptr<Part>& part) override;
async::CoroutineStarter getResourceAsync(const std::shared_ptr<Part>& part,
std::shared_ptr<data::resource::Resource>& resource) override;
};
/**
* Create in-memory part reader.
* @param maxDataSize - max-allowed size of the data. Use `-1` for infinity.
* @return
*/
std::shared_ptr<PartReader> createInMemoryPartReader(v_io_size maxDataSize);
/**
* Create Async in-memory part reader.
* @param maxDataSize - max-allowed size of the data. Use `-1` for infinity.
* @return
*/
std::shared_ptr<AsyncPartReader> createAsyncInMemoryPartReader(v_io_size maxDataSize);
}}}}
#endif //oatpp_web_mime_multipart_InMemoryDataProvider_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/web/mime/multipart/InMemoryDataProvider.hpp
|
C++
|
apache-2.0
| 2,096
|
/***************************************************************************
*
* 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 "Multipart.hpp"
#include "oatpp/web/protocol/http/Http.hpp"
#include "oatpp/encoding/Base64.hpp"
#include "oatpp/core/utils/Random.hpp"
namespace oatpp { namespace web { namespace mime { namespace multipart {
Multipart::Multipart(const oatpp::String& boundary)
: m_boundary(boundary)
{}
oatpp::String Multipart::getBoundary() {
return m_boundary;
}
std::shared_ptr<Part> Multipart::readNextPartSimple() {
async::Action action;
auto result = readNextPart(action);
if(!action.isNone()) {
throw std::runtime_error("[oatpp::web::mime::multipart::Multipart::readNextPartSimple()]. Error."
"Async method is called for non-async API.");
}
return result;
}
void Multipart::writeNextPartSimple(const std::shared_ptr<Part>& part) {
async::Action action;
writeNextPart(part, action);
if(!action.isNone()) {
throw std::runtime_error("[oatpp::web::mime::multipart::Multipart::writeNextPartSimple()]. Error."
"Async method is called for non-async API.");
}
}
oatpp::String Multipart::generateRandomBoundary(v_int32 boundarySize) {
std::unique_ptr<v_char8[]> buffer(new v_char8[boundarySize]);
utils::random::Random::randomBytes(buffer.get(), boundarySize);
return encoding::Base64::encode(buffer.get(), boundarySize, encoding::Base64::ALPHABET_BASE64_URL_SAFE);
}
oatpp::String Multipart::parseBoundaryFromHeaders(const Headers& requestHeaders) {
oatpp::String boundary;
auto contentType = requestHeaders.getAsMemoryLabel<oatpp::data::share::StringKeyLabel>("Content-Type");
if(contentType) {
oatpp::web::protocol::http::HeaderValueData valueData;
oatpp::web::protocol::http::Parser::parseHeaderValueData(valueData, contentType, ';');
boundary = valueData.getTitleParamValue("boundary");
}
return boundary;
}
}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/mime/multipart/Multipart.cpp
|
C++
|
apache-2.0
| 2,834
|
/***************************************************************************
*
* 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_mime_multipart_Multipart_hpp
#define oatpp_web_mime_multipart_Multipart_hpp
#include "Part.hpp"
#include <list>
namespace oatpp { namespace web { namespace mime { namespace multipart {
/**
* Typedef for headers map. Headers map key is case-insensitive.
* For more info see &id:oatpp::data::share::LazyStringMap;.
*/
typedef oatpp::data::share::LazyStringMultimap<oatpp::data::share::StringKeyLabelCI> Headers;
/**
* Abstract Multipart.
*/
class Multipart {
private:
oatpp::String m_boundary;
public:
/**
* Constructor.
* @param boundary - multipart boundary value.
*/
Multipart(const oatpp::String& boundary);
/**
* Default virtual Destructor.
*/
virtual ~Multipart() = default;
/**
* Get multipart boundary value.
* @return - multipart boundary value.
*/
oatpp::String getBoundary();
/**
* Read part-by-part from Multipart.
* @return
*/
virtual std::shared_ptr<Part> readNextPart(async::Action& action) = 0;
/**
* Write part-by-part to Multipart.
* @param part
*/
virtual void writeNextPart(const std::shared_ptr<Part>& part, async::Action& action) = 0;
/**
* Read part-by-part from Multipart. <br>
* Call writeNextPart(...) and throw if `action.isNone() == false`.
* @return
*/
std::shared_ptr<Part> readNextPartSimple();
/**
* Write part-by-part to Multipart.
* Call writeNextPartSimple(...) and throw if `action.isNone() == false`.
* @param part
*/
void writeNextPartSimple(const std::shared_ptr<Part>& part);
public:
/**
* Generate random boundary for Multipart object. Base64 encoded.
* @param boundarySize - size in bytes of random vector.
* @return - &id:oatpp::String;.
*/
static oatpp::String generateRandomBoundary(v_int32 boundarySize = 15);
/**
* Parse boundary value from headers
* @param headers
* @return
*/
static oatpp::String parseBoundaryFromHeaders(const Headers& requestHeaders);
};
}}}}
#endif // oatpp_web_mime_multipart_Multipart_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/web/mime/multipart/Multipart.hpp
|
C++
|
apache-2.0
| 3,026
|
/***************************************************************************
*
* 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 "Part.hpp"
#include "oatpp/web/protocol/http/Http.hpp"
#include "oatpp/core/parser/Caret.hpp"
#include <cstring>
namespace oatpp { namespace web { namespace mime { namespace multipart {
Part::Part(const Headers &headers, const std::shared_ptr<data::resource::Resource>& payload)
: m_headers(headers)
, m_payload(payload)
{
auto contentDisposition = m_headers.getAsMemoryLabel<oatpp::data::share::StringKeyLabel>("Content-Disposition");
if(contentDisposition) {
oatpp::web::protocol::http::HeaderValueData valueData;
oatpp::web::protocol::http::Parser::parseHeaderValueData(valueData, contentDisposition, ';');
m_name = valueData.getTitleParamValue("name");
m_filename = valueData.getTitleParamValue("filename");
}
}
void Part::setPayload(const std::shared_ptr<data::resource::Resource>& payload) {
m_payload = payload;
}
std::shared_ptr<data::resource::Resource> Part::getPayload() {
return m_payload;
}
oatpp::String Part::getName() const {
return m_name;
}
oatpp::String Part::getFilename() const {
return m_filename;
}
const Part::Headers& Part::getHeaders() const {
return m_headers;
}
oatpp::String Part::getHeader(const oatpp::data::share::StringKeyLabelCI& headerName) const {
return m_headers.get(headerName);
}
void Part::putHeader(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value) {
m_headers.put(key, value);
}
bool Part::putHeaderIfNotExists(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value) {
return m_headers.putIfNotExists(key, value);
}
void Part::setTag(const char* tagName, const std::shared_ptr<oatpp::base::Countable>& tagObject) {
m_tagName = tagName;
m_tagObject = tagObject;
}
const char* Part::getTagName() {
return m_tagName;
}
std::shared_ptr<oatpp::base::Countable> Part::getTagObject() {
return m_tagObject;
}
void Part::clearTag() {
m_tagName = nullptr;
m_tagObject.reset();
}
}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/mime/multipart/Part.cpp
|
C++
|
apache-2.0
| 2,990
|
/***************************************************************************
*
* 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_mime_multipart_Part_hpp
#define oatpp_web_mime_multipart_Part_hpp
#include "oatpp/core/data/share/LazyStringMap.hpp"
#include "oatpp/core/data/resource/Resource.hpp"
namespace oatpp { namespace web { namespace mime { namespace multipart {
/**
* One part of the multipart.
*/
class Part {
public:
/**
* Typedef for headers map. Headers map key is case-insensitive.
* For more info see &id:oatpp::data::share::LazyStringMap;.
*/
typedef oatpp::data::share::LazyStringMultimap<oatpp::data::share::StringKeyLabelCI> Headers;
private:
oatpp::String m_name;
oatpp::String m_filename;
Headers m_headers;
std::shared_ptr<data::resource::Resource> m_payload;
private:
const char* m_tagName;
std::shared_ptr<oatpp::base::Countable> m_tagObject;
public:
/**
* Default constructor.
*/
Part() = default;
/**
* Constructor.
* @param headers - headers of the part.
* @param payload - part payload.
*/
Part(const Headers& headers, const std::shared_ptr<data::resource::Resource>& payload = nullptr);
/**
* Set payload.
* @param payload
*/
void setPayload(const std::shared_ptr<data::resource::Resource>& payload);
/**
* Get payload.
* @return
*/
std::shared_ptr<data::resource::Resource> getPayload();
/**
* Get name of the part.
* @return - name of the part.
*/
oatpp::String getName() const;
/**
* Get filename of the part (if applicable).
* @return - filename.
*/
oatpp::String getFilename() const;
/**
* Get request's headers map.
* @return Headers map
*/
const Headers& getHeaders() const;
/**
* Get header value
* @param headerName
* @return header value
*/
oatpp::String getHeader(const oatpp::data::share::StringKeyLabelCI& headerName) const;
/**
* Add http header.
* @param key - &id:oatpp::data::share::StringKeyLabelCI;.
* @param value - &id:oatpp::data::share::StringKeyLabel;.
*/
void putHeader(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value);
/**
* Add http header if not already exists.
* @param key - &id:oatpp::data::share::StringKeyLabelCI;.
* @param value - &id:oatpp::data::share::StringKeyLabel;.
* @return - `true` if header was added.
*/
bool putHeaderIfNotExists(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value);
/**
* Tag-object - object used to associate some data with the Part. <br>
* Ex.: used by &id:oatpp::web::mime::multipart::InMemoryPartReader;. to
* associate intermediate buffer with the part.
* @param tagName
* @param tagObject
*/
void setTag(const char* tagName, const std::shared_ptr<oatpp::base::Countable>& tagObject);
/**
* Get tag name.
* @return
*/
const char* getTagName();
/**
* Get tag object.
* @return
*/
std::shared_ptr<oatpp::base::Countable> getTagObject();
/**
* Clear the tag.
*/
void clearTag();
};
}}}}
#endif // oatpp_web_mime_multipart_Part_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/web/mime/multipart/Part.hpp
|
C++
|
apache-2.0
| 4,048
|
/***************************************************************************
*
* 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 "PartList.hpp"
namespace oatpp { namespace web { namespace mime { namespace multipart {
PartList::PartList(const oatpp::String& boundary)
: Multipart(boundary)
, m_readIteratorInitialized(false)
{}
PartList::PartList(const Headers& requestHeaders)
: Multipart(parseBoundaryFromHeaders(requestHeaders))
, m_readIteratorInitialized(false)
{
if(!getBoundary()) {
throw std::runtime_error("[oatpp::web::mime::multipart::PartList::PartList]: Error. No 'boundary' value found in headers.");
}
}
std::shared_ptr<PartList> PartList::createSharedWithRandomBoundary(v_int32 boundarySize) {
auto boundary = generateRandomBoundary(boundarySize);
return std::make_shared<PartList>(boundary);
}
std::shared_ptr<Part> PartList::readNextPart(async::Action& action) {
if(!m_readIteratorInitialized) {
m_readIteratorInitialized = true;
m_iterator = m_parts.begin();
}
if(m_iterator == m_parts.end()) {
return nullptr;
}
return *m_iterator ++;
}
void PartList::writeNextPart(const std::shared_ptr<Part>& part, async::Action& action) {
if(part->getName()) {
m_namedParts[part->getName()].push_back(part);
}
m_parts.push_back(part);
}
std::shared_ptr<Part> PartList::getNamedPart(const oatpp::String& name) {
auto it = m_namedParts.find(name);
if(it != m_namedParts.end()) {
return it->second.front();
}
return nullptr;
}
std::list<std::shared_ptr<Part>> PartList::getNamedParts(const oatpp::String& name) {
auto it = m_namedParts.find(name);
if(it != m_namedParts.end()) {
return it->second;
}
return std::list<std::shared_ptr<Part>>{};
}
const std::list<std::shared_ptr<Part>>& PartList::getAllParts() {
return m_parts;
}
v_int64 PartList::count() {
return m_parts.size();
}
}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/mime/multipart/PartList.cpp
|
C++
|
apache-2.0
| 2,814
|
/***************************************************************************
*
* 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_web_mime_multipart_PartList_hpp
#define oatpp_web_mime_multipart_PartList_hpp
#include "Multipart.hpp"
namespace oatpp { namespace web { namespace mime { namespace multipart {
/**
* Structure that holds Multipart parts in the `std::list`.
*/
class PartList : public Multipart {
private:
std::unordered_map<oatpp::String, std::list<std::shared_ptr<Part>>> m_namedParts;
bool m_readIteratorInitialized;
std::list<std::shared_ptr<Part>> m_parts;
std::list<std::shared_ptr<Part>>::const_iterator m_iterator;
public:
/**
* Constructor.
* @param boundary - multipart boundary value.
*/
PartList(const oatpp::String& boundary);
/**
* Constructor.
* @param requestHeaders - request headers. Headers must contain "Content-Type" header.
*/
PartList(const Headers& requestHeaders);
/**
* Create Multipart object with random boundary. <br>
* It will generate random vector of size `boundarySize` in bytes encoded in base64.
* @param boundarySize - size of the random vecrot in bytes.
* @return - `std::shared_ptr` to Multipart.
*/
static std::shared_ptr<PartList> createSharedWithRandomBoundary(v_int32 boundarySize = 15);
/**
* Read part-by-part from Multipart.
* @return
*/
std::shared_ptr<Part> readNextPart(async::Action& action) override;
/**
* Write part-by-part to Multipart.
* @param part
*/
void writeNextPart(const std::shared_ptr<Part>& part, async::Action& action) override;
/**
* Get part by name <br>
* Returns the first part if multiple parts with same name exist.
* Applicable to named parts only.
* @param name - &id:oatpp::String;.
* @return - `std::shared_ptr` to &id:oatpp::web::mime::multipart::Part;.
*/
std::shared_ptr<Part> getNamedPart(const oatpp::String& name);
/**
* Get all parts by name <br>
* Applicable to named parts only.
* @param name - &id:oatpp::String;.
* @return - `std::list` of `std::shared_ptr` to &id:oatpp::web::mime::multipart::Part;.
*/
std::list<std::shared_ptr<Part>> getNamedParts(const oatpp::String& name);
/**
* Get list of all parts.
* @return - `std::list` of `std::shared_ptr` to &id:oatpp::web::mime::multipart::Part;.
*/
const std::list<std::shared_ptr<Part>>& getAllParts();
/**
* Get parts count.
* @return - parts count.
*/
v_int64 count();
};
}}}}
#endif //oatpp_web_mime_multipart_PartList_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/web/mime/multipart/PartList.hpp
|
C++
|
apache-2.0
| 3,465
|
/***************************************************************************
*
* 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 "PartReader.hpp"
namespace oatpp { namespace web { namespace mime { namespace multipart {
const char* const StreamPartReader::TAG_NAME = "[oatpp::web::mime::multipart::StreamPartReader::TAG]";
StreamPartReader::StreamPartReader(const std::shared_ptr<PartReaderResourceProvider>& resourceProvider,
v_io_size maxDataSize)
: m_resourceProvider(resourceProvider)
, m_maxDataSize(maxDataSize)
{}
void StreamPartReader::onNewPart(const std::shared_ptr<Part>& part) {
if(!m_resourceProvider) {
throw std::runtime_error("[oatpp::web::mime::multipart::StreamPartReader::onNewPart()]: Error. Stream provider is nullptr.");
}
auto tag = part->getTagObject();
if(tag) {
throw std::runtime_error("[oatpp::web::mime::multipart::StreamPartReader::onNewPart()]: Error. "
"Part tag object is not nullptr. Seems like this part is already being processed by another part reader.");
}
auto tagObject = std::make_shared<TagObject>();
tagObject->resource = m_resourceProvider->getResource(part);
tagObject->outputStream = tagObject->resource->openOutputStream();
part->setTag(TAG_NAME, tagObject);
}
void StreamPartReader::onPartData(const std::shared_ptr<Part>& part, const char* data, oatpp::v_io_size size) {
auto tag = part->getTagObject();
if(!tag) {
throw std::runtime_error("[oatpp::web::mime::multipart::StreamPartReader::onPartData()]: Error. "
"Part tag object is nullptr.");
}
if(part->getTagName() != TAG_NAME) {
throw std::runtime_error("[oatpp::web::mime::multipart::StreamPartReader::onPartData()]: Error. "
"Wrong tag name. Seems like this part is already being processed by another part reader.");
}
auto tagObject = std::static_pointer_cast<TagObject>(tag);
if(size > 0) {
if(m_maxDataSize > 0 && tagObject->size + size > m_maxDataSize) {
OATPP_LOGE("[oatpp::web::mime::multipart::StreamPartReader::onPartData()]", "Error. Part size exceeds specified maxDataSize=%d", m_maxDataSize);
throw std::runtime_error("[oatpp::web::mime::multipart::StreamPartReader::onPartData()]: Error. Part size exceeds specified maxDataSize");
}
auto res = tagObject->outputStream->writeExactSizeDataSimple(data, size);
if(res != size) {
OATPP_LOGE("[oatpp::web::mime::multipart::StreamPartReader::onPartData()]", "Error. Failed to stream all data. Streamed %d/%d", res, size);
throw std::runtime_error("[oatpp::web::mime::multipart::StreamPartReader::onPartData()]: Error. Failed to stream all data.");
}
tagObject->size += res;
} else {
part->setPayload(tagObject->resource);
part->clearTag();
}
}
const char* const AsyncStreamPartReader::TAG_NAME = "[oatpp::web::mime::multipart::AsyncStreamPartReader::TAG]";
AsyncStreamPartReader::AsyncStreamPartReader(const std::shared_ptr<PartReaderResourceProvider>& resourceProvider,
v_io_size maxDataSize)
: m_resourceProvider(resourceProvider)
, m_maxDataSize(maxDataSize)
{}
async::CoroutineStarter AsyncStreamPartReader::onNewPartAsync(const std::shared_ptr<Part>& part) {
class OnNewPartCoroutine : public async::Coroutine<OnNewPartCoroutine> {
private:
std::shared_ptr<Part> m_part;
std::shared_ptr<PartReaderResourceProvider> m_resourceProvider;
std::shared_ptr<data::resource::Resource> m_obtainedResource;
public:
OnNewPartCoroutine(const std::shared_ptr<Part>& part,
const std::shared_ptr<PartReaderResourceProvider>& resourceProvider)
: m_part(part)
, m_resourceProvider(resourceProvider)
{}
Action act() override {
if(!m_resourceProvider) {
throw std::runtime_error("[oatpp::web::mime::multipart::AsyncStreamPartReader::onNewPartAsync(){OnNewPartCoroutine}]: Error. Stream provider is nullptr.");
}
auto tag = m_part->getTagObject();
if(tag) {
throw std::runtime_error("[oatpp::web::mime::multipart::AsyncStreamPartReader::onNewPartAsync(){OnNewPartCoroutine}]: Error. "
"Part tag object is not nullptr. Seems like this part is already being processed by another part reader.");
}
return m_resourceProvider->getResourceAsync(m_part, m_obtainedResource).next(yieldTo(&OnNewPartCoroutine::onResourceObtained));
}
Action onResourceObtained() {
auto tagObject = std::make_shared<TagObject>();
tagObject->resource = m_obtainedResource;
tagObject->outputStream = m_obtainedResource->openOutputStream();
m_part->setTag(TAG_NAME, tagObject);
return finish();
}
};
return OnNewPartCoroutine::start(part, m_resourceProvider);
}
async::CoroutineStarter AsyncStreamPartReader::onPartDataAsync(const std::shared_ptr<Part>& part, const char* data, oatpp::v_io_size size) {
auto tag = part->getTagObject();
if(!tag) {
throw std::runtime_error("[oatpp::web::mime::multipart::AsyncStreamPartReader::onPartDataAsync()]: Error. "
"Part tag object is nullptr.");
}
if(part->getTagName() != TAG_NAME) {
throw std::runtime_error("[oatpp::web::mime::multipart::AsyncStreamPartReader::onPartDataAsync()]: Error. "
"Wrong tag name. Seems like this part is already being processed by another part reader.");
}
auto tagObject = std::static_pointer_cast<TagObject>(tag);
if(size > 0) {
if(m_maxDataSize > 0 && tagObject->size + size > m_maxDataSize) {
OATPP_LOGE("[oatpp::web::mime::multipart::AsyncStreamPartReader::onPartDataAsync()]", "Error. Part size exceeds specified maxDataSize=%d", m_maxDataSize);
throw std::runtime_error("[oatpp::web::mime::multipart::AsyncStreamPartReader::onPartDataAsync()]: Error. Part size exceeds specified maxDataSize");
}
return tagObject->outputStream->writeExactSizeDataAsync(data, size);
} else {
part->setPayload(tagObject->resource);
part->clearTag();
return nullptr;
}
}
}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/mime/multipart/PartReader.cpp
|
C++
|
apache-2.0
| 7,066
|
/***************************************************************************
*
* 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_mime_multipart_PartReader_hpp
#define oatpp_web_mime_multipart_PartReader_hpp
#include "./Multipart.hpp"
#include "oatpp/core/data/stream/Stream.hpp"
namespace oatpp { namespace web { namespace mime { namespace multipart {
/**
* Abstract read handler of multipart parts.
*/
class PartReader {
public:
/**
* Default virtual destructor.
*/
virtual ~PartReader() = default;
/**
* Called when new part headers are parsed and part object is created.
* @param part
*/
virtual void onNewPart(const std::shared_ptr<Part>& part) = 0;
/**
* Called on each new chunk of data is parsed for the multipart-part. <br>
* When all data is read, called again with `data == nullptr && size == 0` to indicate end of the part.
* @param part
* @param data - pointer to buffer containing chunk data.
* @param size - size of the buffer.
*/
virtual void onPartData(const std::shared_ptr<Part>& part, const char* data, oatpp::v_io_size size) = 0;
};
/**
* Abstract Async read handler of multipart parts.
*/
class AsyncPartReader {
public:
/**
* Default virtual destructor.
*/
virtual ~AsyncPartReader() = default;
/**
* Called when new part headers are parsed and part object is created.
* @param part
* @return - &id:oatpp::async::CoroutineStarter;.
*/
virtual async::CoroutineStarter onNewPartAsync(const std::shared_ptr<Part>& part) = 0;
/**
* Called on each new chunk of data is parsed for the multipart-part. <br>
* When all data is read, called again with `data == nullptr && size == 0` to indicate end of the part.
* @param part
* @param data - pointer to buffer containing chunk data.
* @param size - size of the buffer.
* @return - &id:oatpp::async::CoroutineStarter;.
*/
virtual async::CoroutineStarter onPartDataAsync(const std::shared_ptr<Part>& part, const char* data, oatpp::v_io_size size) = 0;
};
/**
* Resource provider for `StreamPartReader`.
*/
class PartReaderResourceProvider {
public:
/**
* Default virtual destructor.
*/
virtual ~PartReaderResourceProvider() = default;
/**
* Get data resource to write (save) part data in.
* @param part
* @return
*/
virtual std::shared_ptr<data::resource::Resource> getResource(const std::shared_ptr<Part>& part) = 0;
/**
* Get data resource to write (save) part data in.
* @param part
* @param resource - put here pointer to obtained resource.
* @return
*/
virtual async::CoroutineStarter getResourceAsync(const std::shared_ptr<Part>& part,
std::shared_ptr<data::resource::Resource>& resource) = 0;
};
/**
* Part reader used in order to stream part data.
*/
class StreamPartReader : public PartReader {
private:
static const char* const TAG_NAME;
private:
class TagObject : public oatpp::base::Countable {
public:
v_io_size size = 0;
std::shared_ptr<data::resource::Resource> resource;
std::shared_ptr<data::stream::OutputStream> outputStream;
};
private:
std::shared_ptr<PartReaderResourceProvider> m_resourceProvider;
v_io_size m_maxDataSize;
public:
/**
* Constructor.
* @param resourceProvider
* @param maxDataSize - use `-1` for no limit.
*/
StreamPartReader(const std::shared_ptr<PartReaderResourceProvider>& resourceProvider, v_io_size maxDataSize = -1);
/**
* Called when new part headers are parsed and part object is created.
* @param part
*/
void onNewPart(const std::shared_ptr<Part>& part) override;
/**
* Called on each new chunk of data is parsed for the multipart-part. <br>
* When all data is read, called again with `data == nullptr && size == 0` to indicate end of the part.
* @param part
* @param data - pointer to buffer containing chunk data.
* @param size - size of the buffer.
*/
void onPartData(const std::shared_ptr<Part>& part, const char* data, oatpp::v_io_size size) override;
};
/**
* Async part reader used in order to stream part data in Asynchronous manner.
*/
class AsyncStreamPartReader : public AsyncPartReader {
private:
static const char* const TAG_NAME;
private:
class TagObject : public oatpp::base::Countable {
public:
v_io_size size = 0;
std::shared_ptr<data::resource::Resource> resource;
std::shared_ptr<data::stream::OutputStream> outputStream;
};
private:
std::shared_ptr<PartReaderResourceProvider> m_resourceProvider;
v_io_size m_maxDataSize;
public:
/**
* Constructor.
* @param resourceProvider
* @param maxDataSize - use `-1` for no limit.
*/
AsyncStreamPartReader(const std::shared_ptr<PartReaderResourceProvider>& resourceProvider, v_io_size maxDataSize = -1);
/**
* Called when new part headers are parsed and part object is created.
* @param part
* @return - &id:oatpp::async::CoroutineStarter;.
*/
async::CoroutineStarter onNewPartAsync(const std::shared_ptr<Part>& part) override;
/**
* Called on each new chunk of data is parsed for the multipart-part. <br>
* When all data is read, called again with `data == nullptr && size == 0` to indicate end of the part.
* @param part
* @param data - pointer to buffer containing chunk data.
* @param size - size of the buffer.
* @return - &id:oatpp::async::CoroutineStarter;.
*/
async::CoroutineStarter onPartDataAsync(const std::shared_ptr<Part>& part, const char* data, oatpp::v_io_size size) override;
};
}}}}
#endif //oatpp_web_mime_multipart_PartReader_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/web/mime/multipart/PartReader.hpp
|
C++
|
apache-2.0
| 6,498
|
/***************************************************************************
*
* 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 "Reader.hpp"
namespace oatpp { namespace web { namespace mime { namespace multipart {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// PartsParser
PartsParser::PartsParser(Multipart* multipart)
: m_multipart(multipart)
{}
PartsParser::PartsParser(Multipart* multipart, const PartReadersMap& readersMap)
: m_readers(readersMap)
, m_multipart(multipart)
{}
void PartsParser::onPartHeaders(const Headers& partHeaders) {
m_currPart = std::make_shared<Part>(partHeaders);
if(m_currPart->getName()) {
auto it = m_readers.find(m_currPart->getName());
if(it != m_readers.end()) {
m_currReader = it->second;
} else {
m_currReader = m_defaultReader;
}
}
if(m_currReader) {
m_currReader->onNewPart(m_currPart);
}
}
void PartsParser::onPartData(const char* data, v_buff_size size) {
if(size > 0) {
if(m_currReader) {
m_currReader->onPartData(m_currPart, data, size);
}
} else {
if(m_currReader) {
m_currReader->onPartData(m_currPart, nullptr, 0);
}
m_multipart->writeNextPartSimple(m_currPart);
}
}
void PartsParser::setPartReader(const oatpp::String& partName, const std::shared_ptr<PartReader>& reader) {
m_readers[partName] = reader;
}
void PartsParser::setDefaultPartReader(const std::shared_ptr<PartReader>& reader) {
m_defaultReader = reader;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// AsyncPartsParser
AsyncPartsParser::AsyncPartsParser(Multipart* multipart)
: m_multipart(multipart)
{}
AsyncPartsParser::AsyncPartsParser(Multipart* multipart, const AsyncPartReadersMap& readersMap)
: m_readers(readersMap)
, m_multipart(multipart)
{}
async::CoroutineStarter AsyncPartsParser::onPartHeadersAsync(const Headers& partHeaders) {
m_currPart = std::make_shared<Part>(partHeaders);
if(m_currPart->getName()) {
auto it = m_readers.find(m_currPart->getName());
if(it != m_readers.end()) {
m_currReader = it->second;
} else {
m_currReader = m_defaultReader;
}
}
if(m_currReader) {
return m_currReader->onNewPartAsync(m_currPart);
}
return nullptr;
}
async::CoroutineStarter AsyncPartsParser::onPartDone(const std::shared_ptr<Part>& part) {
class PutPartCoroutine : public async::Coroutine<PutPartCoroutine> {
private:
Multipart* m_multipart;
std::shared_ptr<AsyncPartReader> m_currReader;
std::shared_ptr<Part> m_part;
public:
PutPartCoroutine(Multipart* multipart,
const std::shared_ptr<AsyncPartReader>& currReader,
const std::shared_ptr<Part>& part)
: m_multipart(multipart)
, m_currReader(currReader)
, m_part(part)
{}
Action act() override {
return m_currReader->onPartDataAsync(m_part, nullptr, 0).next(yieldTo(&PutPartCoroutine::putPart));
}
Action putPart() {
async::Action action;
m_multipart->writeNextPart(m_part, action);
if(!action.isNone()) {
return action;
}
return finish();
}
};
return PutPartCoroutine::start(m_multipart, m_currReader, part);
}
async::CoroutineStarter AsyncPartsParser::onPartDataAsync(const char* data, v_buff_size size) {
if(size > 0) {
if(m_currReader) {
return m_currReader->onPartDataAsync(m_currPart, data, size);
}
} else {
return onPartDone(m_currPart);
}
return nullptr;
}
void AsyncPartsParser::setPartReader(const oatpp::String& partName, const std::shared_ptr<AsyncPartReader>& reader) {
m_readers[partName] = reader;
}
void AsyncPartsParser::setDefaultPartReader(const std::shared_ptr<AsyncPartReader>& reader) {
m_defaultReader = reader;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// InMemoryReader
Reader::Reader(Multipart* multipart)
: m_partsParser(std::make_shared<PartsParser>(multipart))
, m_parser(multipart->getBoundary(), m_partsParser, nullptr)
{}
v_io_size Reader::write(const void *data, v_buff_size count, async::Action& action) {
data::buffer::InlineWriteData inlineData(data, count);
m_parser.parseNext(inlineData, action);
return count - inlineData.bytesLeft;
}
void Reader::setPartReader(const oatpp::String& partName, const std::shared_ptr<PartReader>& reader) {
m_partsParser->m_readers[partName] = reader;
}
void Reader::setDefaultPartReader(const std::shared_ptr<PartReader>& reader) {
m_partsParser->m_defaultReader = reader;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// AsyncReader
AsyncReader::AsyncReader(const std::shared_ptr<Multipart>& multipart)
: m_partsParser(std::make_shared<AsyncPartsParser>(multipart.get()))
, m_parser(multipart->getBoundary(), nullptr, m_partsParser)
, m_multipart(multipart)
{}
v_io_size AsyncReader::write(const void *data, v_buff_size count, async::Action& action) {
data::buffer::InlineWriteData inlineData(data, count);
while(inlineData.bytesLeft > 0 && !m_parser.finished() && action.isNone()) {
m_parser.parseNext(inlineData, action);
}
return count - inlineData.bytesLeft;
}
void AsyncReader::setPartReader(const oatpp::String& partName, const std::shared_ptr<AsyncPartReader>& reader) {
m_partsParser->m_readers[partName] = reader;
}
void AsyncReader::setDefaultPartReader(const std::shared_ptr<AsyncPartReader>& reader) {
m_partsParser->m_defaultReader = reader;
}
}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/mime/multipart/Reader.cpp
|
C++
|
apache-2.0
| 6,595
|
/***************************************************************************
*
* 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_mime_multipart_Reader_hpp
#define oatpp_web_mime_multipart_Reader_hpp
#include "PartReader.hpp"
#include "Multipart.hpp"
#include "StatefulParser.hpp"
#include <unordered_map>
namespace oatpp { namespace web { namespace mime { namespace multipart {
class Reader; // FWD
/**
* Map of part readers. `<part-name> --> <part-reader>`.
*/
typedef std::unordered_map<oatpp::String, std::shared_ptr<PartReader>> PartReadersMap;
/**
* In memory multipart parser. <br>
* Extends - &id:oatpp::web::mime::multipart::StatefulParser::Listener;.
*/
class PartsParser : public StatefulParser::Listener {
friend Reader;
private:
PartReadersMap m_readers;
std::shared_ptr<PartReader> m_defaultReader;
std::shared_ptr<PartReader> m_currReader;
Multipart* m_multipart;
std::shared_ptr<Part> m_currPart;
public:
/**
* Constructor.
* @param multipart - pointer to &id:oatpp::web::mime::multipart::Multipart;.
*/
PartsParser(Multipart* multipart);
PartsParser(Multipart* multipart, const PartReadersMap& readersMap);
void onPartHeaders(const Headers& partHeaders) override;
void onPartData(const char* data, v_buff_size size) override;
void setPartReader(const oatpp::String& partName, const std::shared_ptr<PartReader>& reader);
void setDefaultPartReader(const std::shared_ptr<PartReader>& reader);
};
class AsyncReader; // FWD
/**
* Map of async part readers. `<part-name> --> <part-reader>`.
*/
typedef std::unordered_map<oatpp::String, std::shared_ptr<AsyncPartReader>> AsyncPartReadersMap;
/**
* Async In memory multipart parser. <br>
* Extends - &id:oatpp::web::mime::multipart::StatefulParser::AsyncListener;.
*/
class AsyncPartsParser : public StatefulParser::AsyncListener {
friend AsyncReader;
private:
async::CoroutineStarter onPartDone(const std::shared_ptr<Part>& part);
private:
AsyncPartReadersMap m_readers;
std::shared_ptr<AsyncPartReader> m_defaultReader;
std::shared_ptr<AsyncPartReader> m_currReader;
Multipart* m_multipart;
std::shared_ptr<Part> m_currPart;
public:
/**
* Constructor.
* @param multipart - pointer to &id:oatpp::web::mime::multipart::Multipart;.
*/
AsyncPartsParser(Multipart* multipart);
AsyncPartsParser(Multipart* multipart, const AsyncPartReadersMap& readersMap);
async::CoroutineStarter onPartHeadersAsync(const Headers& partHeaders) override;
async::CoroutineStarter onPartDataAsync(const char* data, v_buff_size size) override;
void setPartReader(const oatpp::String& partName, const std::shared_ptr<AsyncPartReader>& reader);
void setDefaultPartReader(const std::shared_ptr<AsyncPartReader>& reader);
};
/**
* In memory Multipart reader.
* Extends - &id:oatpp::data::stream::WriteCallback;.
*/
class Reader : public oatpp::data::stream::WriteCallback {
private:
std::shared_ptr<PartsParser> m_partsParser;
StatefulParser m_parser;
public:
/**
* Constructor.
* @param multipart - Multipart object to save read data to.
*/
Reader(Multipart* multipart);
v_io_size write(const void *data, v_buff_size count, async::Action& action) override;
/**
* Set named part reader. <br>
* Part with the `name == partName` will be read using the specified `reader`.
* @param partName - name of the part to read.
* @param reader - reader to read part with.
*/
void setPartReader(const oatpp::String& partName, const std::shared_ptr<PartReader>& reader);
/**
* Set default reader for parts. <br>
* `setPartReader` has precedence.
* @param reader
*/
void setDefaultPartReader(const std::shared_ptr<PartReader>& reader);
};
/**
* In memory Multipart reader.
* Extends - &id:oatpp::data::stream::WriteCallback;.
*/
class AsyncReader : public oatpp::data::stream::WriteCallback {
private:
std::shared_ptr<AsyncPartsParser> m_partsParser;
StatefulParser m_parser;
std::shared_ptr<Multipart> m_multipart;
public:
/**
* Constructor.
* @param multipart - Multipart object to save read data to.
*/
AsyncReader(const std::shared_ptr<Multipart>& multipart);
v_io_size write(const void *data, v_buff_size count, async::Action& action) override;
/**
* Set named part reader. <br>
* Part with the `name == partName` will be read using the specified `reader`.
* @param partName - name of the part to read.
* @param reader - reader to read part with.
*/
void setPartReader(const oatpp::String& partName, const std::shared_ptr<AsyncPartReader>& reader);
/**
* Set default reader for parts. <br>
* `setPartReader` has precedence.
* @param reader
*/
void setDefaultPartReader(const std::shared_ptr<AsyncPartReader>& reader);
};
}}}}
#endif // oatpp_web_mime_multipart_Reader_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/web/mime/multipart/Reader.hpp
|
C++
|
apache-2.0
| 5,712
|
/***************************************************************************
*
* 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 "StatefulParser.hpp"
#include "oatpp/web/protocol/http/Http.hpp"
#include "oatpp/core/parser/Caret.hpp"
#include "oatpp/core/parser/ParsingError.hpp"
namespace oatpp { namespace web { namespace mime { namespace multipart {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// StatefulParser::ListenerCall
void StatefulParser::ListenerCall::setOnHeadersCall() {
callType = CALL_ON_HEADERS;
data = nullptr;
size = 0;
}
void StatefulParser::ListenerCall::setOnDataCall(const char* pData, v_buff_size pSize) {
callType = CALL_ON_DATA;
data = pData;
size = pSize;
}
void StatefulParser::ListenerCall::call(StatefulParser* parser) {
if(parser->m_listener) {
switch(callType) {
case CALL_ON_HEADERS:
{
Headers headers;
parser->parseHeaders(headers);
parser->m_listener->onPartHeaders(headers);
}
break;
case CALL_ON_DATA:
parser->m_listener->onPartData(data, size);
break;
}
}
}
async::CoroutineStarter StatefulParser::ListenerCall::callAsync(StatefulParser* parser) {
if(parser->m_asyncListener) {
switch(callType) {
case CALL_ON_HEADERS: {
Headers headers;
parser->parseHeaders(headers);
return parser->m_asyncListener->onPartHeadersAsync(headers);
}
case CALL_ON_DATA:
return parser->m_asyncListener->onPartDataAsync(data, size);
}
}
return nullptr;
}
StatefulParser::ListenerCall::operator bool() const {
return callType != CALL_NONE;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// StatefulParser
StatefulParser::StatefulParser(const oatpp::String& boundary,
const std::shared_ptr<Listener>& listener,
const std::shared_ptr<AsyncListener>& asyncListener)
: m_state(STATE_BOUNDARY)
, m_currPartIndex(0)
, m_currBoundaryCharIndex(0)
, m_checkForBoundary(true)
, m_finishingBoundary(false)
, m_readingBody(false)
, m_headerSectionEndAccumulator(0)
, m_firstBoundarySample("--" + boundary)
, m_nextBoundarySample("\r\n--" + boundary)
, m_maxPartHeadersSize(4092)
, m_listener(listener)
, m_asyncListener(asyncListener)
{}
void StatefulParser::parseHeaders(Headers& headers) {
m_currPartIndex ++;
auto headersText = m_headersBuffer.toString();
m_headersBuffer.setCurrentPosition(0);
protocol::http::Status status;
parser::Caret caret(headersText);
protocol::http::Parser::parseHeaders(headers, headersText.getPtr(), caret, status);
}
StatefulParser::ListenerCall StatefulParser::parseNext_Boundary(data::buffer::InlineWriteData& inlineData) {
ListenerCall result;
auto data = inlineData.currBufferPtr;
auto size = inlineData.bytesLeft;
auto sampleData = m_nextBoundarySample->data();
v_io_size sampleSize = m_nextBoundarySample->size();
if (m_currPartIndex == 0) {
sampleData = m_firstBoundarySample->data();
sampleSize = m_firstBoundarySample->size();
} else {
sampleData = m_nextBoundarySample->data();
sampleSize = m_nextBoundarySample->size();
}
v_io_size checkSize = sampleSize - m_currBoundaryCharIndex;
if(checkSize > size) {
checkSize = size;
}
parser::Caret caret((const char*)data, size);
if(caret.isAtText(&sampleData[m_currBoundaryCharIndex], checkSize, true)) {
m_currBoundaryCharIndex += caret.getPosition();
if(m_currBoundaryCharIndex == sampleSize) {
m_state = STATE_AFTER_BOUNDARY;
m_currBoundaryCharIndex = 0;
m_readingBody = false;
if(m_currPartIndex > 0) {
result.setOnDataCall(nullptr, 0);
}
}
inlineData.inc(caret.getPosition());
return result;
} else if(m_readingBody) {
if(m_currBoundaryCharIndex > 0) {
result.setOnDataCall(sampleData, m_currBoundaryCharIndex);
} else {
m_checkForBoundary = false;
}
m_state = STATE_DATA;
m_currBoundaryCharIndex = 0;
return result;
}
throw std::runtime_error("[oatpp::web::mime::multipart::StatefulParser::parseNext_Boundary()]: Error. Invalid state.");
}
void StatefulParser::parseNext_AfterBoundary(data::buffer::InlineWriteData& inlineData) {
p_char8 data = (p_char8) inlineData.currBufferPtr;
auto size = inlineData.bytesLeft;
if(m_currBoundaryCharIndex == 0) {
if(data[0] == '-') {
m_finishingBoundary = true;
} else if(data[0] != '\r') {
throw std::runtime_error("[oatpp::web::mime::multipart::StatefulParser::parseNext_AfterBoundary()]: Error. Invalid char.");
}
}
if(size > 1 || m_currBoundaryCharIndex == 1) {
if (m_finishingBoundary && data[1 - m_currBoundaryCharIndex] == '-') {
auto result = 2 - m_currBoundaryCharIndex;
m_state = STATE_DONE;
m_currBoundaryCharIndex = 0;
inlineData.inc(result);
return;
} else if (!m_finishingBoundary && data[1 - m_currBoundaryCharIndex] == '\n') {
auto result = 2 - m_currBoundaryCharIndex;
m_state = STATE_HEADERS;
m_currBoundaryCharIndex = 0;
m_headerSectionEndAccumulator = 0;
inlineData.inc(result);
return;
} else {
throw std::runtime_error("[oatpp::web::mime::multipart::StatefulParser::parseNext_AfterBoundary()]: Error. Invalid trailing char.");
}
}
m_currBoundaryCharIndex = 1;
inlineData.inc(1);
return;
}
StatefulParser::ListenerCall StatefulParser::parseNext_Headers(data::buffer::InlineWriteData& inlineData) {
ListenerCall result;
p_char8 data = (p_char8) inlineData.currBufferPtr;
auto size = inlineData.bytesLeft;
for(v_buff_size i = 0; i < size; i ++) {
m_headerSectionEndAccumulator <<= 8;
m_headerSectionEndAccumulator |= data[i];
if(m_headerSectionEndAccumulator == HEADERS_SECTION_END) {
if(m_headersBuffer.getCurrentPosition() + i > m_maxPartHeadersSize) {
throw std::runtime_error("[oatpp::web::mime::multipart::StatefulParser::parseNext_Headers()]: Error. Too large heades.");
}
m_headersBuffer.writeSimple(data, i);
result.setOnHeadersCall();
m_state = STATE_DATA;
m_checkForBoundary = true;
inlineData.inc(i + 1);
return result;
}
}
if(m_headersBuffer.getCurrentPosition() + size > m_maxPartHeadersSize) {
throw std::runtime_error("[oatpp::web::mime::multipart::StatefulParser::parseNext_Headers()]: Error. Headers section is too large.");
}
m_headersBuffer.writeSimple(data, size);
inlineData.inc(size);
return result;
}
StatefulParser::ListenerCall StatefulParser::parseNext_Data(data::buffer::InlineWriteData& inlineData) {
ListenerCall result;
const char* data = (const char*) inlineData.currBufferPtr;
auto size = inlineData.bytesLeft;
parser::Caret caret(data, size);
bool rFound = caret.findChar('\r');
if(rFound && !m_checkForBoundary) {
caret.inc();
rFound = caret.findChar('\r');
}
m_checkForBoundary = true;
if(rFound) {
if(caret.getPosition() > 0) {
result.setOnDataCall(data, caret.getPosition());
}
m_state = STATE_BOUNDARY;
m_readingBody = true;
inlineData.inc(caret.getPosition());
} else {
result.setOnDataCall(data, size);
inlineData.inc(size);
}
return result;
}
void StatefulParser::parseNext(data::buffer::InlineWriteData& inlineData, async::Action& action) {
while(inlineData.bytesLeft > 0) {
ListenerCall listenerCall;
switch (m_state) {
case STATE_BOUNDARY:
listenerCall = parseNext_Boundary(inlineData);
break;
case STATE_AFTER_BOUNDARY:
parseNext_AfterBoundary(inlineData);
break;
case STATE_HEADERS:
listenerCall = parseNext_Headers(inlineData);
break;
case STATE_DATA:
listenerCall = parseNext_Data(inlineData);
break;
case STATE_DONE:
return;
default:
throw std::runtime_error("[oatpp::web::mime::multipart::StatefulParser::parseNext()]: Error. Invalid state.");
}
if(listenerCall) {
if(m_asyncListener) {
action = listenerCall.callAsync(this).next(async::Action::createActionByType(async::Action::TYPE_REPEAT));
break;
}else {
listenerCall.call(this);
}
}
}
}
bool StatefulParser::finished() {
return m_state == STATE_DONE;
}
}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/mime/multipart/StatefulParser.cpp
|
C++
|
apache-2.0
| 9,428
|
/***************************************************************************
*
* 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_mime_multipart_StatefulParser_hpp
#define oatpp_web_mime_multipart_StatefulParser_hpp
#include "oatpp/core/data/stream/BufferStream.hpp"
#include "oatpp/core/data/share/LazyStringMap.hpp"
#include "oatpp/core/Types.hpp"
#include <unordered_map>
namespace oatpp { namespace web { namespace mime { namespace multipart {
/**
* Stateful parser of multipart-data stream.
* Parser designed to work with stream-like data in order to store minimum data in the memory.
*/
class StatefulParser {
private:
static constexpr v_int32 STATE_BOUNDARY = 0;
static constexpr v_int32 STATE_AFTER_BOUNDARY = 1;
static constexpr v_int32 STATE_HEADERS = 2;
static constexpr v_int32 STATE_DATA = 3;
static constexpr v_int32 STATE_DONE = 4;
private:
static constexpr v_uint32 HEADERS_SECTION_END = ('\r' << 24) | ('\n' << 16) | ('\r' << 8) | ('\n');
private:
/**
* Typedef for headers map. Headers map key is case-insensitive.
* For more info see &id:oatpp::data::share::LazyStringMap;.
*/
typedef oatpp::data::share::LazyStringMultimap<oatpp::data::share::StringKeyLabelCI> Headers;
public:
/**
* Listener for parsed items.
*/
class Listener {
public:
/**
* Typedef for headers map. Headers map key is case-insensitive.
* For more info see &id:oatpp::data::share::LazyStringMap;.
*/
typedef oatpp::data::share::LazyStringMultimap<oatpp::data::share::StringKeyLabelCI> Headers;
public:
/**
* Default virtual Destructor.
*/
virtual ~Listener() = default;
/**
* Called on new part found in the stream.
* Always called before `onPartData` events.
* @param partHeaders - complete set of part headers.
*/
virtual void onPartHeaders(const Headers& partHeaders) = 0;
/**
* Called on each new chunk of bytes parsed from the part body.
* When all data of message is read, readMessage is called again with size == 0 to
* indicate end of the part.
* @param data - pointer to data.
* @param size - size of the data in bytes.
*/
virtual void onPartData(const char* data, v_buff_size size) = 0;
};
public:
/**
* Async Listener for parsed items.
*/
class AsyncListener {
public:
/**
* Typedef for headers map. Headers map key is case-insensitive.
* For more info see &id:oatpp::data::share::LazyStringMap;.
*/
typedef oatpp::data::share::LazyStringMultimap<oatpp::data::share::StringKeyLabelCI> Headers;
public:
/**
* Default virtual Destructor.
*/
virtual ~AsyncListener() = default;
/**
* Called on new part found in the stream.
* Always called before `onPartData` events.
* @param partHeaders - complete set of part headers.
*/
virtual async::CoroutineStarter onPartHeadersAsync(const Headers& partHeaders) = 0;
/**
* Called on each new chunk of bytes parsed from the part body.
* When all data of message is read, readMessage is called again with size == 0 to
* indicate end of the part.
* @param data - pointer to data.
* @param size - size of the data in bytes.
*/
virtual async::CoroutineStarter onPartDataAsync(const char* data, v_buff_size size) = 0;
};
private:
class ListenerCall {
public:
static constexpr v_int32 CALL_NONE = 0;
static constexpr v_int32 CALL_ON_HEADERS = 1;
static constexpr v_int32 CALL_ON_DATA = 2;
public:
ListenerCall()
: callType(CALL_NONE)
, data(nullptr)
, size(0)
{}
v_int32 callType;
const char* data;
v_io_size size;
void setOnHeadersCall();
void setOnDataCall(const char* pData, v_buff_size pSize);
void call(StatefulParser* parser);
async::CoroutineStarter callAsync(StatefulParser* parser);
explicit operator bool() const;
};
private:
v_int32 m_state;
v_int64 m_currPartIndex;
v_buff_size m_currBoundaryCharIndex;
bool m_checkForBoundary;
bool m_finishingBoundary;
bool m_readingBody;
v_uint32 m_headerSectionEndAccumulator;
oatpp::String m_firstBoundarySample;
oatpp::String m_nextBoundarySample;
/*
* Headers of the part are stored in the buffer and are parsed as one chunk.
*/
data::stream::BufferOutputStream m_headersBuffer;
/*
* Max length of all headers per one part.
* Default value = 4096 bytes.
*/
v_buff_size m_maxPartHeadersSize;
std::shared_ptr<Listener> m_listener;
std::shared_ptr<AsyncListener> m_asyncListener;
private:
void parseHeaders(Headers& headers);
private:
ListenerCall parseNext_Boundary(data::buffer::InlineWriteData& inlineData);
void parseNext_AfterBoundary(data::buffer::InlineWriteData& inlineData);
ListenerCall parseNext_Headers(data::buffer::InlineWriteData& inlineData);
ListenerCall parseNext_Data(data::buffer::InlineWriteData& inlineData);
public:
/**
* Constructor.
* @param boundary - value of multipart boundary.
* @param listener - &l:StatefulParser::Listener;.
* @param asyncListener - &l:StatefulParser::AsyncListener;.
*/
StatefulParser(const oatpp::String& boundary,
const std::shared_ptr<Listener>& listener,
const std::shared_ptr<AsyncListener>& asyncListener);
/**
* Parse next chunk of bytes.
* @param inlineData - inline data.
* @param action - Async Action in case Async Listener was provided in constructor.
*/
void parseNext(data::buffer::InlineWriteData& inlineData, async::Action& action);
/**
* Check if parser done parsing data.
* @return - `true` or `false`.
*/
bool finished();
};
}}}}
#endif // oatpp_web_mime_multipart_StatefulParser_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/web/mime/multipart/StatefulParser.hpp
|
C++
|
apache-2.0
| 6,658
|
/***************************************************************************
*
* 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 "TemporaryFileProvider.hpp"
#include "oatpp/core/data/resource/TemporaryFile.hpp"
namespace oatpp { namespace web { namespace mime { namespace multipart {
TemporaryFileProvider::TemporaryFileProvider(const oatpp::String& tmpDirectory, v_int32 randomWordSizeBytes)
: m_tmpDirectory(tmpDirectory)
, m_randomWordSizeBytes(randomWordSizeBytes)
{}
std::shared_ptr<data::resource::Resource> TemporaryFileProvider::getResource(const std::shared_ptr<Part>& part) {
(void)part;
return std::make_shared<data::resource::TemporaryFile>(m_tmpDirectory, m_randomWordSizeBytes);
}
async::CoroutineStarter TemporaryFileProvider::getResourceAsync(const std::shared_ptr<Part>& part,
std::shared_ptr<data::resource::Resource>& stream)
{
(void)part;
stream = std::make_shared<data::resource::TemporaryFile>(m_tmpDirectory, m_randomWordSizeBytes);
return nullptr;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Other functions
std::shared_ptr<PartReader> createTemporaryFilePartReader(const oatpp::String& tmpDirectory,
v_int32 randomWordSizeBytes,
v_io_size maxDataSize)
{
auto provider = std::make_shared<TemporaryFileProvider>(tmpDirectory, randomWordSizeBytes);
auto reader = std::make_shared<StreamPartReader>(provider, maxDataSize);
return reader;
}
std::shared_ptr<AsyncPartReader> createAsyncTemporaryFilePartReader(const oatpp::String& tmpDirectory,
v_int32 randomWordSizeBytes,
v_io_size maxDataSize)
{
auto provider = std::make_shared<TemporaryFileProvider>(tmpDirectory, randomWordSizeBytes);
auto reader = std::make_shared<AsyncStreamPartReader>(provider, maxDataSize);
return reader;
}
}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/mime/multipart/TemporaryFileProvider.cpp
|
C++
|
apache-2.0
| 3,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.
*
***************************************************************************/
#ifndef oatpp_web_mime_multipart_TemporaryFileProvider_hpp
#define oatpp_web_mime_multipart_TemporaryFileProvider_hpp
#include "PartReader.hpp"
#include "Reader.hpp"
namespace oatpp { namespace web { namespace mime { namespace multipart {
class TemporaryFileProvider : public PartReaderResourceProvider {
private:
oatpp::String m_tmpDirectory;
v_int32 m_randomWordSizeBytes;
public:
TemporaryFileProvider(const oatpp::String& tmpDirectory, v_int32 randomWordSizeBytes = 8);
std::shared_ptr<data::resource::Resource> getResource(const std::shared_ptr<Part>& part) override;
async::CoroutineStarter getResourceAsync(const std::shared_ptr<Part>& part,
std::shared_ptr<data::resource::Resource>& resource) override;
};
/**
* Create part reader to a temporary file.
* @param tmpDirectory - directory for temporary files.
* @param randomWordSizeBytes - number of random bytes to generate file name.
* @param maxDataSize - max size of the received data. put `-1` for no-limit.
* @return - `std::shared_ptr` to &id:oatpp::web::mime::multipart::PartReader;.
*/
std::shared_ptr<PartReader> createTemporaryFilePartReader(const oatpp::String& tmpDirectory,
v_int32 randomWordSizeBytes = 8,
v_io_size maxDataSize = -1);
/**
* Create async part reader to a temporary file.
* @param tmpDirectory - directory for temporary files.
* @param randomWordSizeBytes - number of random bytes to generate file name.
* @param maxDataSize - max size of the received data. put `-1` for no-limit.
* @return - `std::shared_ptr` to &id:oatpp::web::mime::multipart::AsyncPartReader;.
*/
std::shared_ptr<AsyncPartReader> createAsyncTemporaryFilePartReader(const oatpp::String& tmpDirectory,
v_int32 randomWordSizeBytes = 8,
v_io_size maxDataSize = -1);
}}}}
#endif //oatpp_web_mime_multipart_TemporaryFileProvider_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/web/mime/multipart/TemporaryFileProvider.hpp
|
C++
|
apache-2.0
| 3,109
|
/***************************************************************************
*
* 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 "CommunicationError.hpp"
namespace oatpp { namespace web { namespace protocol {
CommunicationError::CommunicationError(oatpp::v_io_size ioStatus, const oatpp::String& message)
:std::runtime_error(*message)
, m_ioStatus(ioStatus)
, m_message(message)
{}
oatpp::v_io_size CommunicationError::getIOStatus() {
return m_ioStatus;
}
oatpp::String& CommunicationError::getMessage(){
return m_message;
}
}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/CommunicationError.cpp
|
C++
|
apache-2.0
| 1,426
|
/***************************************************************************
*
* 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_CommunicationError_hpp
#define oatpp_web_protocol_CommunicationError_hpp
#include "oatpp/core/IODefinitions.hpp"
namespace oatpp { namespace web { namespace protocol {
/**
* Communication Error
*/
class CommunicationError : public std::runtime_error {
private:
oatpp::v_io_size m_ioStatus;
oatpp::String m_message;
public:
/**
* Constructor.
* @param ioStatus - I/O error. See &id:oatpp::v_io_size;.
* @param message - error message.
*/
CommunicationError(oatpp::v_io_size ioStatus, const oatpp::String& message);
/**
* Get I/O error. See &id:oatpp::v_io_size;.
* @return &id:oatpp::v_io_size;.
*/
oatpp::v_io_size getIOStatus();
/**
* Get error message.
* @return - error message.
*/
oatpp::String& getMessage();
};
/**
* Protocol Error Info.
*/
template<class Status>
struct ProtocolErrorInfo {
/**
* Default Constructor.
*/
ProtocolErrorInfo()
: ioStatus(0)
{}
/**
* Constructor.
* @param pIOStatus - I/O level error. See &id:oatpp::v_io_size;.
* @param pStatus - configurable arbitrary data type.
*/
ProtocolErrorInfo(oatpp::v_io_size pIOStatus, const Status& pStatus)
: ioStatus(pIOStatus)
, status(pStatus)
{}
/**
* Get I/O level error.
*/
oatpp::v_io_size ioStatus;
/**
* Configurable arbitrary data type.
*/
Status status;
};
/**
* Protocol Error template.
* @tparam Status - arbitrary data type.
*/
template<class Status>
class ProtocolError : public CommunicationError {
public:
/**
* Cenvenience typedef for ProtocolErrorInfo
*/
typedef ProtocolErrorInfo<Status> Info;
private:
Info m_info;
public:
/**
* Constructor.
* @param info - &l:ProtocolError::Info ;.
* @param message - error message.
*/
ProtocolError(const Info& info, const oatpp::String& message)
: CommunicationError(info.ioStatus, message)
, m_info(info)
{}
/**
* Get error info.
* @return - error info.
*/
Info getInfo() {
return m_info;
}
};
/**
* Protocol Error template.
* @tparam Status - arbitrary data type.
*/
template<class Status>
class AsyncProtocolError : public oatpp::AsyncIOError {
public:
/**
* Cenvenience typedef for ProtocolErrorInfo
*/
typedef ProtocolErrorInfo<Status> Info;
private:
Info m_info;
oatpp::String m_message;
public:
/**
* Constructor.
* @param info - &l:ProtocolError::Info ;.
* @param message - error message.
*/
AsyncProtocolError(const Info& info, const oatpp::String& message)
: oatpp::AsyncIOError("AsyncProtocolError", info.ioStatus)
, m_info(info)
, m_message(message)
{}
/**
* Error message.
* @return - error message.
*/
oatpp::String getMessage() {
return m_message;
}
/**
* Get error info.
* @return - error info.
*/
Info getInfo() {
return m_info;
}
};
}}}
#endif /* oatpp_web_protocol_CommunicationError_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/CommunicationError.hpp
|
C++
|
apache-2.0
| 3,945
|
/***************************************************************************
*
* 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 "./Http.hpp"
#include "oatpp/core/data/stream/BufferStream.hpp"
#include "oatpp/core/utils/ConversionUtils.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http {
const Status Status::CODE_100(100, "Continue");
const Status Status::CODE_101(101, "Switching");
const Status Status::CODE_102(102, "Processing");
const Status Status::CODE_200(200, "OK");
const Status Status::CODE_201(201, "Created");
const Status Status::CODE_202(202, "Accepted");
const Status Status::CODE_203(203, "Non-Authoritative Information");
const Status Status::CODE_204(204, "No Content");
const Status Status::CODE_205(205, "Reset Content");
const Status Status::CODE_206(206, "Partial Content");
const Status Status::CODE_207(207, "Multi-Status");
const Status Status::CODE_226(226, "IM Used");
const Status Status::CODE_300(300, "Multiple Choices");
const Status Status::CODE_301(301, "Moved Permanently");
const Status Status::CODE_302(302, "Moved Temporarily");
const Status Status::CODE_303(303, "See Other");
const Status Status::CODE_304(304, "Not Modified");
const Status Status::CODE_305(305, "Use Proxy");
const Status Status::CODE_306(306, "Reserved");
const Status Status::CODE_307(307, "Temporary Redirect");
const Status Status::CODE_400(400, "Bad Request");
const Status Status::CODE_401(401, "Unauthorized");
const Status Status::CODE_402(402, "Payment Required");
const Status Status::CODE_403(403, "Forbidden");
const Status Status::CODE_404(404, "Not Found");
const Status Status::CODE_405(405, "Method Not Allowed");
const Status Status::CODE_406(406, "Not Acceptable");
const Status Status::CODE_407(407, "Proxy Authentication Required");
const Status Status::CODE_408(408, "Request Timeout");
const Status Status::CODE_409(409, "Conflict");
const Status Status::CODE_410(410, "Gone");
const Status Status::CODE_411(411, "Length Required");
const Status Status::CODE_412(412, "Precondition Failed");
const Status Status::CODE_413(413, "Request Entity Too Large");
const Status Status::CODE_414(414, "Request-URI Too Large");
const Status Status::CODE_415(415, "Unsupported Media Type");
const Status Status::CODE_416(416, "Requested Range Not Satisfiable");
const Status Status::CODE_417(417, "Expectation Failed");
const Status Status::CODE_418(418, "I'm a Teapot");
const Status Status::CODE_422(422, "Unprocessable Entity");
const Status Status::CODE_423(423, "Locked");
const Status Status::CODE_424(424, "Failed Dependency");
const Status Status::CODE_425(425, "Unordered Collection");
const Status Status::CODE_426(426, "Upgrade Required");
const Status Status::CODE_428(428, "Precondition Required");
const Status Status::CODE_429(429, "Too Many Requests");
const Status Status::CODE_431(431, "Request Header Fields Too Large");
const Status Status::CODE_434(434, "Requested host unavailable");
const Status Status::CODE_444(444, "Close connection withot sending headers");
const Status Status::CODE_449(449, "Retry With");
const Status Status::CODE_451(451, "Unavailable For Legal Reasons");
const Status Status::CODE_500(500, "Internal Server Error");
const Status Status::CODE_501(501, "Not Implemented");
const Status Status::CODE_502(502, "Bad Gateway");
const Status Status::CODE_503(503, "Service Unavailable");
const Status Status::CODE_504(504, "Gateway Timeout");
const Status Status::CODE_505(505, "HTTP Version Not Supported");
const Status Status::CODE_506(506, "Variant Also Negotiates");
const Status Status::CODE_507(507, "Insufficient Storage");
const Status Status::CODE_508(508, "Loop Detected");
const Status Status::CODE_509(509, "Bandwidth Limit Exceeded");
const Status Status::CODE_510(510, "Not Extended");
const Status Status::CODE_511(511, "Network Authentication Required");
const char* const Header::Value::CONNECTION_CLOSE = "close";
const char* const Header::Value::CONNECTION_KEEP_ALIVE = "keep-alive";
const char* const Header::Value::CONNECTION_UPGRADE = "Upgrade";
const char* const Header::Value::SERVER = "oatpp/" OATPP_VERSION;
const char* const Header::Value::USER_AGENT = "oatpp/" OATPP_VERSION;
const char* const Header::Value::TRANSFER_ENCODING_CHUNKED = "chunked";
const char* const Header::Value::CONTENT_TYPE_APPLICATION_JSON = "application/json";
const char* const Header::Value::EXPECT_100_CONTINUE = "100-continue";
const char* const Header::ACCEPT = "Accept";
const char* const Header::AUTHORIZATION = "Authorization";
const char* const Header::WWW_AUTHENTICATE = "WWW-Authenticate";
const char* const Header::CONNECTION = "Connection";
const char* const Header::TRANSFER_ENCODING = "Transfer-Encoding";
const char* const Header::CONTENT_ENCODING = "Content-Encoding";
const char* const Header::CONTENT_LENGTH = "Content-Length";
const char* const Header::CONTENT_TYPE = "Content-Type";
const char* const Header::CONTENT_RANGE = "Content-Range";
const char* const Header::RANGE = "Range";
const char* const Header::HOST = "Host";
const char* const Header::USER_AGENT = "User-Agent";
const char* const Header::SERVER = "Server";
const char* const Header::UPGRADE = "Upgrade";
const char* const Header::CORS_ORIGIN = "Access-Control-Allow-Origin";
const char* const Header::CORS_METHODS = "Access-Control-Allow-Methods";
const char* const Header::CORS_HEADERS = "Access-Control-Allow-Headers";
const char* const Header::CORS_MAX_AGE = "Access-Control-Max-Age";
const char* const Header::ACCEPT_ENCODING = "Accept-Encoding";
const char* const Header::EXPECT = "Expect";
const char* const Range::UNIT_BYTES = "bytes";
const char* const ContentRange::UNIT_BYTES = "bytes";
oatpp::String Range::toString() const {
data::stream::BufferOutputStream stream(256);
stream.writeSimple(units->data(), units->size());
stream.writeSimple("=", 1);
stream.writeAsString(start);
stream.writeSimple("-", 1);
stream.writeAsString(end);
return stream.toString();
}
Range Range::parse(oatpp::parser::Caret& caret) {
auto unitsLabel = caret.putLabel();
if(caret.findChar('=')) {
unitsLabel.end();
caret.inc();
} else {
caret.setError("'=' - expected");
return Range();
}
auto startLabel = caret.putLabel();
if(caret.findChar('-')) {
startLabel.end();
caret.inc();
} else {
caret.setError("'-' - expected");
return Range();
}
auto endLabel = caret.putLabel();
caret.findRN();
endLabel.end();
auto start = oatpp::utils::conversion::strToInt64((const char*) startLabel.getData());
auto end = oatpp::utils::conversion::strToInt64((const char*) endLabel.getData());
return Range(unitsLabel.toString(), start, end);
}
Range Range::parse(const oatpp::String& str) {
oatpp::parser::Caret caret(str);
return parse(caret);
}
oatpp::String ContentRange::toString() const {
data::stream::BufferOutputStream stream(256);
stream.writeSimple(units->data(), units->size());
stream.writeSimple(" ", 1);
stream.writeAsString(start);
stream.writeSimple("-", 1);
stream.writeAsString(end);
stream.writeSimple("/", 1);
if(isSizeKnown) {
stream.writeAsString(size);
} else {
stream.writeSimple("*", 1);
}
return stream.toString();
}
ContentRange ContentRange::parse(oatpp::parser::Caret& caret) {
auto unitsLabel = caret.putLabel();
if(caret.findChar(' ')) {
unitsLabel.end();
caret.inc();
} else {
caret.setError("' ' - expected");
return ContentRange();
}
auto startLabel = caret.putLabel();
if(caret.findChar('-')) {
startLabel.end();
caret.inc();
} else {
caret.setError("'-' - expected");
return ContentRange();
}
auto endLabel = caret.putLabel();
if(caret.findChar('/')) {
endLabel.end();
caret.inc();
} else {
caret.setError("'/' - expected");
return ContentRange();
}
auto sizeLabel = caret.putLabel();
caret.findRN();
sizeLabel.end();
v_int64 start = oatpp::utils::conversion::strToInt64((const char*) startLabel.getData());
v_int64 end = oatpp::utils::conversion::strToInt64((const char*) endLabel.getData());
v_int64 size = 0;
bool isSizeKnown = false;
if(sizeLabel.getData()[0] != '*') {
isSizeKnown = true;
size = oatpp::utils::conversion::strToInt64((const char*) sizeLabel.getData());
}
return ContentRange(unitsLabel.toString(), start, end, size, isSizeKnown);
}
ContentRange ContentRange::parse(const oatpp::String& str) {
oatpp::parser::Caret caret(str);
return parse(caret);
}
oatpp::String HeaderValueData::getTitleParamValue(const data::share::StringKeyLabelCI& key) const {
auto it = titleParams.find(key);
if(it != titleParams.end()) {
return it->second.toString();
}
return nullptr;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Parser
oatpp::data::share::StringKeyLabelCI Parser::parseHeaderNameLabel(const std::shared_ptr<std::string>& headersText,
oatpp::parser::Caret& caret) {
const char* data = caret.getData();
for(v_buff_size i = caret.getPosition(); i < caret.getDataSize(); i++) {
v_char8 a = data[i];
if(a == ':' || a == ' '){
oatpp::data::share::StringKeyLabelCI label(headersText, &data[caret.getPosition()], i - caret.getPosition());
caret.setPosition(i);
return label;
}
}
return oatpp::data::share::StringKeyLabelCI(nullptr, nullptr, 0);
}
void Parser::parseRequestStartingLine(RequestStartingLine& line,
const std::shared_ptr<std::string>& headersText,
oatpp::parser::Caret& caret,
Status& error) {
auto methodLabel = caret.putLabel();
if(caret.findChar(' ')){
line.method = oatpp::data::share::StringKeyLabel(headersText, methodLabel.getData(), methodLabel.getSize());
caret.inc();
} else {
error = Status::CODE_400;
return;
}
auto pathLabel = caret.putLabel();
if(caret.findChar(' ')){
line.path = oatpp::data::share::StringKeyLabel(headersText, pathLabel.getData(), pathLabel.getSize());
caret.inc();
} else {
error = Status::CODE_400;
return;
}
auto protocolLabel = caret.putLabel();
if(caret.findRN()){
line.protocol = oatpp::data::share::StringKeyLabel(headersText, protocolLabel.getData(), protocolLabel.getSize());
caret.skipRN();
} else {
error = Status::CODE_400;
return;
}
}
void Parser::parseResponseStartingLine(ResponseStartingLine& line,
const std::shared_ptr<std::string>& headersText,
oatpp::parser::Caret& caret,
Status& error) {
auto protocolLabel = caret.putLabel();
if(caret.findChar(' ')){
line.protocol = oatpp::data::share::StringKeyLabel(headersText, protocolLabel.getData(), protocolLabel.getSize());
caret.inc();
} else {
error = Status::CODE_400;
return;
}
line.statusCode = (v_int32)caret.parseInt();
auto descriptionLabel = caret.putLabel();
if(caret.findRN()){
line.description = oatpp::data::share::StringKeyLabel(headersText, descriptionLabel.getData(), descriptionLabel.getSize());
caret.skipRN();
} else {
error = Status::CODE_400;
return;
}
}
void Parser::parseOneHeader(Headers& headers,
const std::shared_ptr<std::string>& headersText,
oatpp::parser::Caret& caret,
Status& error)
{
caret.skipChar(' ');
auto name = parseHeaderNameLabel(headersText, caret);
if(name.getData() != nullptr) {
caret.skipChar(' ');
if(!caret.canContinueAtChar(':', 1)) {
error = Status::CODE_400;
return;
}
caret.skipChar(' ');
v_buff_size valuePos0 = caret.getPosition();
caret.findRN();
headers.put_LockFree(name, oatpp::data::share::StringKeyLabel(headersText, &caret.getData()[valuePos0], caret.getPosition() - valuePos0));
caret.skipRN();
} else {
error = Status::CODE_431;
return;
}
}
void Parser::parseHeaders(Headers& headers,
const std::shared_ptr<std::string>& headersText,
oatpp::parser::Caret& caret,
Status& error)
{
while (!caret.isAtRN()) {
parseOneHeader(headers, headersText, caret, error);
if(error.code != 0) {
return;
}
}
caret.skipRN();
}
void Parser::parseHeaderValueData(HeaderValueData& data, const oatpp::data::share::StringKeyLabel& headerValue, char separator) {
oatpp::parser::Caret caret((const char*) headerValue.getData(), headerValue.getSize());
const char charSet[5] = {' ', '=', separator, '\r', '\n'};
const char charSet2[4] = {' ', separator, '\r', '\n'};
while (caret.canContinue()) {
caret.skipChar(' ');
auto label = caret.putLabel();
auto res = caret.findCharFromSet(charSet, 5);
if (res == '=') {
data::share::StringKeyLabelCI key(headerValue.getMemoryHandle(), label.getData(), label.getSize());
caret.inc();
if (caret.isAtChar('"')) {
label = caret.parseStringEnclosed('"', '"', '\\');
} else if (caret.isAtChar('\'')) {
label = caret.parseStringEnclosed('\'', '\'', '\\');
} else {
label = caret.putLabel();
caret.findCharFromSet(charSet2, 4);
}
data.titleParams[key] = data::share::StringKeyLabel(headerValue.getMemoryHandle(), label.getData(),
label.getSize());
} else {
data.tokens.insert(
data::share::StringKeyLabelCI(headerValue.getMemoryHandle(), label.getData(), label.getSize()));
}
if (caret.isAtCharFromSet("\r\n", 2)) {
break;
} else if (caret.isAtChar(separator)) {
caret.inc();
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Utils
void Utils::writeHeaders(const Headers& headers, data::stream::ConsistentOutputStream* stream) {
auto& map = headers.getAll_Unsafe();
auto it = map.begin();
while(it != map.end()) {
stream->writeSimple(it->first.getData(), it->first.getSize());
stream->writeSimple(": ", 2);
stream->writeSimple(it->second.getData(), it->second.getSize());
stream->writeSimple("\r\n", 2);
it ++;
}
}
}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/Http.cpp
|
C++
|
apache-2.0
| 15,412
|
/***************************************************************************
*
* 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_Http_hpp
#define oatpp_web_protocol_http_Http_hpp
#include "oatpp/network/tcp/Connection.hpp"
#include "oatpp/web/protocol/CommunicationError.hpp"
#include "oatpp/core/parser/Caret.hpp"
#include "oatpp/core/data/share/LazyStringMap.hpp"
#include "oatpp/core/Types.hpp"
#include <unordered_map>
#include <unordered_set>
namespace oatpp { namespace web { namespace protocol { namespace http {
/**
* Typedef for headers map. Headers map key is case-insensitive.
* For more info see &id:oatpp::data::share::LazyStringMultimap;.
*/
typedef oatpp::data::share::LazyStringMultimap<oatpp::data::share::StringKeyLabelCI> Headers;
/**
* Typedef for query parameters map.
* For more info see &id:oatpp::data::share::LazyStringMultimap;.
*/
typedef oatpp::data::share::LazyStringMultimap<oatpp::data::share::StringKeyLabel> QueryParams;
/**
* Http status.
*/
class Status{
public:
/**
* Continue.
*/
static const Status CODE_100;// Continue
/**
* Switching Protocols.
*/
static const Status CODE_101;// Switching
/**
* Processing.
*/
static const Status CODE_102;// Processing
/**
* OK.
*/
static const Status CODE_200;// OK
/**
* Created.
*/
static const Status CODE_201;// Created
/**
* Accepted.
*/
static const Status CODE_202;// Accepted
/**
* Non-Authoritative Information.
*/
static const Status CODE_203;// Non-Authoritative Information
/**
* No Content.
*/
static const Status CODE_204;// No Content
/**
* Reset Content.
*/
static const Status CODE_205;// Reset Content
/**
* Partial Content.
*/
static const Status CODE_206;// Partial Content
/**
* Multi-Status.
*/
static const Status CODE_207;// Multi-Status
/**
* IM Used.
*/
static const Status CODE_226;// IM Used
/**
* Multiple Choices.
*/
static const Status CODE_300;// Multiple Choices
/**
* Moved Permanently.
*/
static const Status CODE_301;// Moved Permanently
/**
* Moved Temporarily.
*/
static const Status CODE_302;// Moved Temporarily
/**
* See Other.
*/
static const Status CODE_303;// See Other
/**
* Not Modified.
*/
static const Status CODE_304;// Not Modified
/**
* Use Proxy.
*/
static const Status CODE_305;// Use Proxy
/**
* Reserved.
*/
static const Status CODE_306;// Reserved
/**
* Temporary Redirect.
*/
static const Status CODE_307;// Temporary Redirect
/**
* Bad Request.
*/
static const Status CODE_400;// Bad Request
/**
* Unauthorized.
*/
static const Status CODE_401;// Unauthorized
/**
* Payment Required.
*/
static const Status CODE_402;// Payment Required
/**
* Forbidden.
*/
static const Status CODE_403;// Forbidden
/**
* Not Found.
*/
static const Status CODE_404;// Not Found
/**
* Method Not Allowed.
*/
static const Status CODE_405;// Method Not Allowed
/**
* Not Acceptable.
*/
static const Status CODE_406;// Not Acceptable
/**
* Proxy Authentication Required.
*/
static const Status CODE_407;// Proxy Authentication Required
/**
* Request Timeout.
*/
static const Status CODE_408;// Request Timeout
/**
* Conflict.
*/
static const Status CODE_409;// Conflict
/**
* Gone
*/
static const Status CODE_410;// Gone
/**
* Length Required.
*/
static const Status CODE_411;// Length Required
/**
* Precondition Failed.
*/
static const Status CODE_412;// Precondition Failed
/**
* Request Entity Too Large.
*/
static const Status CODE_413;// Request Entity Too Large
/**
* Request-URI Too Large.
*/
static const Status CODE_414;// Request-URI Too Large
/**
* Unsupported Media Type.
*/
static const Status CODE_415;// Unsupported Media Type
/**
* Requested Range Not Satisfiable.
*/
static const Status CODE_416;// Requested Range Not Satisfiable
/**
* Expectation Failed.
*/
static const Status CODE_417;// Expectation Failed
/**
* I'm a Teapot (rfc7168 2.3.3)
*/
static const Status CODE_418;// I'm a teapot
/**
* Unprocessable Entity.
*/
static const Status CODE_422;// Unprocessable Entity
/**
* Locked.
*/
static const Status CODE_423;// Locked
/**
* Failed Dependency.
*/
static const Status CODE_424;// Failed Dependency
/**
* Unordered Collection.
*/
static const Status CODE_425;// Unordered Collection
/**
* Upgrade Required.
*/
static const Status CODE_426;// Upgrade Required
/**
* Precondition Required.
*/
static const Status CODE_428;// Precondition Required
/**
* Too Many Requests.
*/
static const Status CODE_429;// Too Many Requests
/**
* Request Header Fields Too Large.
*/
static const Status CODE_431;// Request Header Fields Too Large
/**
* Requested host unavailable.
*/
static const Status CODE_434;// Requested host unavailable
/**
* Close connection withot sending headers.
*/
static const Status CODE_444;// Close connection withot sending headers
/**
* Retry With.
*/
static const Status CODE_449;// Retry With
/**
* Unavailable For Legal Reasons.
*/
static const Status CODE_451;// Unavailable For Legal Reasons
/**
* Internal Server Error.
*/
static const Status CODE_500;// Internal Server Error
/**
* Not Implemented.
*/
static const Status CODE_501;// Not Implemented
/**
* Bad Gateway.
*/
static const Status CODE_502;// Bad Gateway
/**
* Service Unavailable.
*/
static const Status CODE_503;// Service Unavailable
/**
* Gateway Timeout.
*/
static const Status CODE_504;// Gateway Timeout
/**
* HTTP Version Not Supported.
*/
static const Status CODE_505;// HTTP Version Not Supported
/**
* Variant Also Negotiates.
*/
static const Status CODE_506;// Variant Also Negotiates
/**
* Insufficient Storage.
*/
static const Status CODE_507;// Insufficient Storage
/**
* Loop Detected.
*/
static const Status CODE_508;// Loop Detected
/**
* Bandwidth Limit Exceeded.
*/
static const Status CODE_509;// Bandwidth Limit Exceeded
/**
* Not Extended.
*/
static const Status CODE_510;// Not Extended
/**
* Network Authentication Required.
*/
static const Status CODE_511;// Network Authentication Required
/**
* Constructor.
*/
Status()
: code(0)
, description(nullptr)
{}
/**
* Constructor.
* @param pCode - status code.
* @param pDesc - description.
*/
Status(v_int32 pCode, const char* pDesc)
: code(pCode)
, description(pDesc)
{}
/**
* Status code.
*/
v_int32 code;
/**
* Description.
*/
const char* description;
bool operator==(const Status& other) const {
return this->code == other.code;
}
bool operator!=(const Status& other) const {
return this->code != other.code;
}
};
/**
* HttpError extends &id:oatpp::web::protocol::ProtocolError;<&l:Status;>.
*/
class HttpError : public protocol::ProtocolError<Status> {
private:
Headers m_headers;
public:
/**
* Constructor.
* @param info
* @param message
*/
HttpError(const Info& info, const oatpp::String& message)
: protocol::ProtocolError<Status>(info, message)
{}
/**
* Constructor.
* @param status
* @param message
*/
HttpError(const Status& status, const oatpp::String& message)
: protocol::ProtocolError<Status>(Info(0, status), message)
{}
/**
* Constructor.
* @param status
* @param message
* @param headers
*/
HttpError(const Status& status, const oatpp::String& message, const Headers& headers)
: protocol::ProtocolError<Status>(Info(0, status), message)
, m_headers(headers)
{}
/**
* Get headers
* @return
*/
const Headers& getHeaders() const {
return m_headers;
}
};
/**
* Throw &l:HttpError; if assertion failed.
* @param COND - boolean statement. If evaluates to false - throw error.
* @param STATUS - &l:Status;.
* @param MESSAGE - String message.
*/
#define OATPP_ASSERT_HTTP(COND, STATUS, MESSAGE) \
if(!(COND)) { throw oatpp::web::protocol::http::HttpError(STATUS, MESSAGE); }
/**
* Collection of HTTP Header constants.
*/
class Header {
public:
/**
* Possible values for headers.
*/
class Value {
public:
static const char* const CONNECTION_CLOSE;
static const char* const CONNECTION_KEEP_ALIVE;
static const char* const CONNECTION_UPGRADE;
static const char* const SERVER;
static const char* const USER_AGENT;
static const char* const TRANSFER_ENCODING_CHUNKED;
static const char* const CONTENT_TYPE_APPLICATION_JSON;
static const char* const EXPECT_100_CONTINUE;
};
public:
static const char* const ACCEPT; // "Accept"
static const char* const AUTHORIZATION; // "Authorization"
static const char* const WWW_AUTHENTICATE; // "WWW-Authenticate"
static const char* const CONNECTION; // "Connection"
static const char* const TRANSFER_ENCODING; // "Transfer-Encoding"
static const char* const CONTENT_ENCODING; // "Content-Encoding"
static const char* const CONTENT_LENGTH; // "Content-Length"
static const char* const CONTENT_TYPE; // "Content-Type"
static const char* const CONTENT_RANGE; // "Content-Range"
static const char* const RANGE; // "Range"
static const char* const HOST; // "Host"
static const char* const USER_AGENT; // "User-Agent"
static const char* const SERVER; // "Server"
static const char* const UPGRADE; // "Upgrade"
static const char* const CORS_ORIGIN; // Access-Control-Allow-Origin
static const char* const CORS_METHODS; // Access-Control-Allow-Methods
static const char* const CORS_HEADERS; // Access-Control-Allow-Headers
static const char* const CORS_MAX_AGE; // Access-Control-Max-Age
static const char* const ACCEPT_ENCODING; // Accept-Encoding
static const char* const EXPECT; // Expect
};
class Range {
public:
static const char* const UNIT_BYTES;
private:
Range()
: units(nullptr)
{}
public:
Range(const oatpp::String& pUnits,
v_int64 pStart,
v_int64 pEnd)
: units(pUnits)
, start(pStart)
, end(pEnd)
{}
oatpp::String units;
v_int64 start;
v_int64 end;
oatpp::String toString() const;
bool isValid() const {
return units.get() != nullptr;
}
static Range parse(oatpp::parser::Caret& caret);
static Range parse(const oatpp::String& str);
};
class ContentRange {
public:
static const char* const UNIT_BYTES;
private:
ContentRange()
: units(nullptr)
{}
public:
ContentRange(const oatpp::String& pUnits,
v_int64 pStart,
v_int64 pEnd,
v_int64 pSize,
bool pIsSizeKnown)
: units(pUnits)
, start(pStart)
, end(pEnd)
, size(pSize)
, isSizeKnown(pIsSizeKnown)
{}
oatpp::String units;
v_int64 start;
v_int64 end;
v_int64 size;
bool isSizeKnown;
oatpp::String toString() const;
bool isValid() const {
return units.get() != nullptr;
}
static ContentRange parse(oatpp::parser::Caret& caret);
static ContentRange parse(const oatpp::String& str);
};
/**
* Struct representing HTTP request starting line.
* Example request starting line: `GET /path/to/resource/ HTTP/1.1`.
*/
struct RequestStartingLine {
/**
* Method as &id:oatpp::data::share::StringKeyLabel;.
*/
oatpp::data::share::StringKeyLabel method; // GET, POST ...
/**
* Path as &id:oatpp::data::share::StringKeyLabel;.
*/
oatpp::data::share::StringKeyLabel path;
/**
* Protocol as &id:oatpp::data::share::StringKeyLabel;.
*/
oatpp::data::share::StringKeyLabel protocol;
};
/**
* Struct representing HTTP response starting line.
* Example response starting line: `HTTP/1.1 200 OK`.
*/
struct ResponseStartingLine {
/**
* Protocol as &id:oatpp::data::share::StringKeyLabel;.
*/
oatpp::data::share::StringKeyLabel protocol;
/**
* Status code as v_int32.
*/
v_int32 statusCode;
/**
* Description as &id:oatpp::data::share::StringKeyLabel;.
*/
oatpp::data::share::StringKeyLabel description;
};
/**
* Data contained in the value of one header.
*/
struct HeaderValueData {
/**
* value tokens.
*/
std::unordered_set<data::share::StringKeyLabelCI> tokens;
/**
* Title params.
*/
std::unordered_map<data::share::StringKeyLabelCI, data::share::StringKeyLabel> titleParams;
/**
* Get title parm value by key.
* @param key
* @return
*/
oatpp::String getTitleParamValue(const data::share::StringKeyLabelCI& key) const;
};
/**
* Oatpp Http parser.
*/
class Parser {
private:
static oatpp::data::share::StringKeyLabelCI parseHeaderNameLabel(const std::shared_ptr<std::string>& headersText,
oatpp::parser::Caret& caret);
public:
/**
* Parse &l:RequestStartingLine;.
* @param line - &l:RequestStartingLine;. Values will be set to line's fields.
* @param headersText - `std::shared_ptr` to `std::string` needed as a "memory handle" for
* &l:RequestStartingLine; fields. See &id:oatpp::data::share::MemoryLabel;.
* @param caret - &id:oatpp::parser::Caret;.
* @param error - out parameter &l:Status;.
*/
static void parseRequestStartingLine(RequestStartingLine& line,
const std::shared_ptr<std::string>& headersText,
oatpp::parser::Caret& caret,
Status& error);
/**
* Parse &l:ResponseStartingLine;.
* @param line - &l:ResponseStartingLine;. Values will be set to line's fields.
* @param headersText - `std::shared_ptr` to `std::string` needed as a "memory handle" for
* &l:ResponseStartingLine; fields. See &id:oatpp::data::share::MemoryLabel;.
* @param caret - &id:oatpp::parser::Caret;.
* @param error - out parameter &l:Status;.
*/
static void parseResponseStartingLine(ResponseStartingLine& line,
const std::shared_ptr<std::string>& headersText,
oatpp::parser::Caret& caret,
Status& error);
/**
* Parse one header line. Example of the header line:
* `"Content-Type: application/json\r\n"`.
* @param headers - &l:Headers; map to put parsed header to.
* @param headersText - `std::shared_ptr` to `std::string` needed as a "memory handle" for
* &l:Headers; values. See &id:oatpp::data::share::MemoryLabel;.
* @param caret - &id:oatpp::parser::Caret;.
* @param error - out parameter &l:Status;.
*/
static void parseOneHeader(Headers& headers,
const std::shared_ptr<std::string>& headersText,
oatpp::parser::Caret& caret,
Status& error);
/**
* Parse HTTP headers to &l:Headers; map.
* @param headers - &l:Headers; map to put parsed headers to.
* @param headersText - `std::shared_ptr` to `std::string` needed as a "memory handle" for
* &l:Headers; values. See &id:oatpp::data::share::MemoryLabel;.
* @param caret - &id:oatpp::parser::Caret;.
* @param error - out parameter &l:Status;.
*/
static void parseHeaders(Headers& headers,
const std::shared_ptr<std::string>& headersText,
oatpp::parser::Caret& caret,
Status& error);
/**
* Parse data that is contained in a one header.
* @param data - out. parsed data.
* @param headerValue - header value string.
* @param separator - subvalues separator.
*/
static void parseHeaderValueData(HeaderValueData& data, const oatpp::data::share::StringKeyLabel& headerValue, char separator);
};
/**
* Http utils.
*/
class Utils {
public:
/**
* Write headers map to stream.
* @param headers
* @param stream
*/
static void writeHeaders(const Headers& headers, data::stream::ConsistentOutputStream* stream);
};
}}}}
namespace std {
template<>
struct hash<oatpp::web::protocol::http::Status> {
typedef oatpp::web::protocol::http::Status argument_type;
typedef v_uint64 result_type;
result_type operator()(oatpp::web::protocol::http::Status const& s) const noexcept {
return s.code;
}
};
}
#endif /* oatpp_web_protocol_http_Http_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/Http.hpp
|
C++
|
apache-2.0
| 17,721
|
/***************************************************************************
*
* 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 "Chunked.hpp"
#include "oatpp/core/utils/ConversionUtils.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace encoding {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// EncoderChunked
v_io_size EncoderChunked::suggestInputStreamReadSize() {
return 32767;
}
v_int32 EncoderChunked::iterate(data::buffer::InlineReadData& dataIn, data::buffer::InlineReadData& dataOut) {
if(dataOut.bytesLeft > 0) {
return Error::FLUSH_DATA_OUT;
}
if(dataIn.currBufferPtr != nullptr) {
if(m_lastFlush > 0) {
dataIn.inc(m_lastFlush);
m_lastFlush = 0;
}
if(m_finished){
dataOut.set(nullptr, 0);
return Error::FINISHED;
}
if(dataIn.bytesLeft == 0) {
return Error::PROVIDE_DATA_IN;
}
if(m_writeChunkHeader) {
async::Action action;
data::stream::BufferOutputStream stream(16);
if(!m_firstChunk) {
stream.write("\r\n", 2, action);
}
stream << utils::conversion::primitiveToStr(dataIn.bytesLeft, "%X");
stream.write("\r\n", 2, action);
m_chunkHeader = stream.toString();
dataOut.set((p_char8) m_chunkHeader->data(), m_chunkHeader->size());
m_firstChunk = false;
m_writeChunkHeader = false;
return Error::FLUSH_DATA_OUT;
}
dataOut = dataIn;
m_lastFlush = dataOut.bytesLeft;
m_writeChunkHeader = true;
return Error::FLUSH_DATA_OUT;
}
if(m_writeChunkHeader){
async::Action action;
data::stream::BufferOutputStream stream(16);
if(!m_firstChunk) {
stream.write("\r\n", 2, action);
}
stream.write("0\r\n\r\n", 5, action);
m_chunkHeader = stream.toString();
dataOut.set((p_char8) m_chunkHeader->data(), m_chunkHeader->size());
m_firstChunk = false;
m_writeChunkHeader = false;
return Error::FLUSH_DATA_OUT;
}
m_finished = true;
dataOut.set(nullptr, 0);
return Error::FINISHED;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// DecoderChunked
DecoderChunked::DecoderChunked()
: m_chunkHeaderBuffer(16)
, m_currentChunkSize(-1)
, m_firstChunk(true)
, m_finished(false)
, m_lastFlush(0)
{}
v_io_size DecoderChunked::suggestInputStreamReadSize() {
if(m_currentChunkSize > 0) {
return m_currentChunkSize;
}
return 1;
}
v_int32 DecoderChunked::readHeader(data::buffer::InlineReadData& dataIn) {
async::Action action;
while(dataIn.bytesLeft > 0 && m_currentChunkSize < 0) {
if (m_chunkHeaderBuffer.getCurrentPosition() < 12) {
m_chunkHeaderBuffer.write(dataIn.currBufferPtr, 1, action);
dataIn.inc(1);
auto pos = m_chunkHeaderBuffer.getCurrentPosition();
if(m_currentChunkSize == -1) {
if (pos > 2 && m_chunkHeaderBuffer.getData()[pos - 2] == '\r' && m_chunkHeaderBuffer.getData()[pos - 1] == '\n') {
if(m_firstChunk) {
m_currentChunkSize = strtol((const char *) m_chunkHeaderBuffer.getData(), nullptr, 16);
} else {
// skip "/r/n" before chunk size
m_currentChunkSize = strtol((const char *) (m_chunkHeaderBuffer.getData() + 2), nullptr, 16);
}
if (m_currentChunkSize > 0) {
return Error::OK;
} else {
m_currentChunkSize = -2;
}
}
} else if(m_currentChunkSize == -2) {
if (pos > 4 &&
m_chunkHeaderBuffer.getData()[pos - 4] == '\r' && m_chunkHeaderBuffer.getData()[pos - 3] == '\n' &&
m_chunkHeaderBuffer.getData()[pos - 2] == '\r' && m_chunkHeaderBuffer.getData()[pos - 1] == '\n') {
m_currentChunkSize = 0;
m_finished = true;
return Error::OK;
}
}
} else {
return ERROR_CHUNK_HEADER_TOO_LONG;
}
}
return Error::PROVIDE_DATA_IN;
}
v_int32 DecoderChunked::iterate(data::buffer::InlineReadData& dataIn, data::buffer::InlineReadData& dataOut) {
if(dataOut.bytesLeft > 0) {
return Error::FLUSH_DATA_OUT;
}
if(dataIn.currBufferPtr != nullptr) {
if(m_lastFlush > 0) {
dataIn.inc(m_lastFlush);
m_currentChunkSize -= m_lastFlush;
if(m_currentChunkSize == 0) {
m_currentChunkSize = -1;
}
m_lastFlush = 0;
}
if (m_finished) {
dataOut.set(nullptr, 0);
return Error::FINISHED;
}
if (dataIn.bytesLeft == 0) {
return Error::PROVIDE_DATA_IN;
}
if(m_currentChunkSize < 0) {
return readHeader(dataIn);
} else if(m_currentChunkSize == 0) {
m_chunkHeaderBuffer.setCurrentPosition(0);
dataOut.set(nullptr, 0);
m_finished = true;
return Error::FINISHED;
}
m_chunkHeaderBuffer.setCurrentPosition(0);
m_lastFlush = dataIn.bytesLeft;
if(m_lastFlush > m_currentChunkSize) {
m_lastFlush = m_currentChunkSize;
}
dataOut.set(dataIn.currBufferPtr, m_lastFlush);
return Error::FLUSH_DATA_OUT;
}
m_chunkHeaderBuffer.setCurrentPosition(0);
dataOut.set(nullptr, 0);
m_finished = true;
return Error::FINISHED;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ChunkedEncoderProvider
oatpp::String ChunkedEncoderProvider::getEncodingName() {
return "chunked";
}
std::shared_ptr<data::buffer::Processor> ChunkedEncoderProvider::getProcessor() {
return std::make_shared<EncoderChunked>();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ChunkedDecoderProvider
oatpp::String ChunkedDecoderProvider::getEncodingName() {
return "chunked";
}
std::shared_ptr<data::buffer::Processor> ChunkedDecoderProvider::getProcessor() {
return std::make_shared<DecoderChunked>();
}
}}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/encoding/Chunked.cpp
|
C++
|
apache-2.0
| 6,898
|
/***************************************************************************
*
* 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_encoding_Chunked_hpp
#define oatpp_web_protocol_http_encoding_Chunked_hpp
#include "EncoderProvider.hpp"
#include "oatpp/core/data/stream/BufferStream.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace encoding {
/**
* Chunked-encoding buffer processor. &id:oatpp::data::buffer::Processor;.
*/
class EncoderChunked : public data::buffer::Processor {
private:
oatpp::String m_chunkHeader;
bool m_writeChunkHeader = true;
bool m_firstChunk = true;
bool m_finished = false;
v_io_size m_lastFlush = 0;
public:
/**
* If the client is using the input stream to read data and push it to the processor,
* the client MAY ask the processor for a suggested read size.
* @return - suggested read size.
*/
v_io_size suggestInputStreamReadSize() override;
/**
* Process data.
* @param dataIn - data provided by client to processor. Input data. &id:data::buffer::InlineReadData;.
* Set `dataIn` buffer pointer to `nullptr` to designate the end of input.
* @param dataOut - data provided to client by processor. Output data. &id:data::buffer::InlineReadData;.
* @return - &l:Processor::Error;.
*/
v_int32 iterate(data::buffer::InlineReadData& dataIn, data::buffer::InlineReadData& dataOut) override;
};
/**
* Chunked-decoding buffer processor. &id:oatpp::data::buffer::Processor;.
*/
class DecoderChunked : public data::buffer::Processor {
public:
static constexpr v_int32 ERROR_CHUNK_HEADER_TOO_LONG = 100;
private:
data::stream::BufferOutputStream m_chunkHeaderBuffer;
v_io_size m_currentChunkSize;
bool m_firstChunk;
bool m_finished;
v_io_size m_lastFlush;
private:
v_int32 readHeader(data::buffer::InlineReadData& dataIn);
public:
/**
* Constructor.
*/
DecoderChunked();
/**
* If the client is using the input stream to read data and push it to the processor,
* the client MAY ask the processor for a suggested read size.
* @return - suggested read size.
*/
v_io_size suggestInputStreamReadSize() override;
/**
* Process data.
* @param dataIn - data provided by client to processor. Input data. &id:data::buffer::InlineReadData;.
* Set `dataIn` buffer pointer to `nullptr` to designate the end of input.
* @param dataOut - data provided to client by processor. Output data. &id:data::buffer::InlineReadData;.
* @return - &l:Processor::Error;.
*/
v_int32 iterate(data::buffer::InlineReadData& dataIn, data::buffer::InlineReadData& dataOut) override;
};
/**
* EncoderProvider for "chunked" encoding.
*/
class ChunkedEncoderProvider : public EncoderProvider {
public:
/**
* Get encoding name.
* @return
*/
oatpp::String getEncodingName() override;
/**
* Get &id:oatpp::data::buffer::Processor; for chunked encoding.
* @return - &id:oatpp::data::buffer::Processor;
*/
std::shared_ptr<data::buffer::Processor> getProcessor() override;
};
/**
* EncoderProvider for "chunked" decoding.
*/
class ChunkedDecoderProvider : public EncoderProvider {
public:
/**
* Get encoding name.
* @return
*/
oatpp::String getEncodingName() override;
/**
* Get &id:oatpp::data::buffer::Processor; for chunked decoding.
* @return - &id:oatpp::data::buffer::Processor;
*/
std::shared_ptr<data::buffer::Processor> getProcessor() override;
};
}}}}}
#endif //oatpp_web_protocol_http_encoding_Chunked_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/encoding/Chunked.hpp
|
C++
|
apache-2.0
| 4,417
|
/***************************************************************************
*
* 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_encoding_EncoderProvider_hpp
#define oatpp_web_protocol_http_encoding_EncoderProvider_hpp
#include "oatpp/core/data/buffer/Processor.hpp"
#include "oatpp/core/Types.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace encoding {
/**
* Provider of encoding or decoding &id:oatpp::data::buffer::Processor;.
*/
class EncoderProvider {
public:
/**
* Default virtual destructor.
*/
virtual ~EncoderProvider() = default;
/**
* Get name of the encoding. This name is used in HTTP headers.
* @return - name of the encoding. Ex.: "gzip" or "deflate" or "chunked".
*/
virtual oatpp::String getEncodingName() = 0;
/**
* Get &id:oatpp::data::buffer::Processor; for decoding/encoding.
* @return - &id:oatpp::data::buffer::Processor;
*/
virtual std::shared_ptr<data::buffer::Processor> getProcessor() = 0;
};
}}}}}
#endif // oatpp_web_protocol_http_encoding_EncoderProvider_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/encoding/EncoderProvider.hpp
|
C++
|
apache-2.0
| 1,973
|
/***************************************************************************
*
* 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 "ProviderCollection.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace encoding {
void ProviderCollection::add(const std::shared_ptr<EncoderProvider>& provider) {
m_providers[provider->getEncodingName()] = provider;
}
std::shared_ptr<EncoderProvider> ProviderCollection::get(const data::share::StringKeyLabelCI& encoding) const {
auto it = m_providers.find(encoding);
if(it != m_providers.end()) {
return it->second;
}
return nullptr;
}
std::shared_ptr<EncoderProvider> ProviderCollection::get(const std::unordered_set<data::share::StringKeyLabelCI>& encodings) const {
for(const auto& encoding : encodings) {
auto provider = get(encoding);
if(provider) {
return provider;
}
}
return nullptr;
}
}}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/encoding/ProviderCollection.cpp
|
C++
|
apache-2.0
| 1,787
|
/***************************************************************************
*
* 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_encoding_ProviderCollection_hpp
#define oatpp_web_protocol_http_encoding_ProviderCollection_hpp
#include "EncoderProvider.hpp"
#include "oatpp/core/data/share/MemoryLabel.hpp"
#include <unordered_map>
#include <unordered_set>
namespace oatpp { namespace web { namespace protocol { namespace http { namespace encoding {
/**
* Collection of &id:oatpp::web::protocol::http::encoding::EncoderProvider;.
*/
class ProviderCollection {
private:
std::unordered_map<data::share::StringKeyLabelCI, std::shared_ptr<EncoderProvider>> m_providers;
public:
/**
* Add encoder to collection.
* @param provider
*/
void add(const std::shared_ptr<EncoderProvider>& provider);
/**
* Get encoder by encoding name.
* @param encoding - encoding name.
* @return
*/
std::shared_ptr<EncoderProvider> get(const data::share::StringKeyLabelCI& encoding) const;
/**
* Select available provider for set of encodings.
* @param encodings - set of desired encodings
* @return
*/
std::shared_ptr<EncoderProvider> get(const std::unordered_set<data::share::StringKeyLabelCI>& encodings) const;
};
}}}}}
#endif // oatpp_web_protocol_http_encoding_ProviderCollection_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/encoding/ProviderCollection.hpp
|
C++
|
apache-2.0
| 2,218
|
/***************************************************************************
*
* 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 "BodyDecoder.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace incoming {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// BodyDecoder
oatpp::async::CoroutineStarterForResult<const oatpp::String&>
BodyDecoder::decodeToStringAsync(const Headers& headers,
const std::shared_ptr<data::stream::InputStream>& bodyStream,
const std::shared_ptr<data::stream::IOStream>& connection) const
{
class ToStringDecoder : public oatpp::async::CoroutineWithResult<ToStringDecoder, const oatpp::String&> {
private:
const BodyDecoder* m_decoder;
Headers m_headers;
std::shared_ptr<data::stream::InputStream> m_bodyStream;
std::shared_ptr<data::stream::IOStream> m_connection;
std::shared_ptr<data::stream::BufferOutputStream> m_outputStream;
public:
ToStringDecoder(const BodyDecoder* decoder,
const Headers& headers,
const std::shared_ptr<data::stream::InputStream>& bodyStream,
const std::shared_ptr<data::stream::IOStream>& connection)
: m_decoder(decoder)
, m_headers(headers)
, m_bodyStream(bodyStream)
, m_connection(connection)
, m_outputStream(std::make_shared<data::stream::BufferOutputStream>())
{}
Action act() override {
return m_decoder->decodeAsync(m_headers, m_bodyStream, m_outputStream, m_connection)
.next(yieldTo(&ToStringDecoder::onDecoded));
}
Action onDecoded() {
return _return(m_outputStream->toString());
}
};
return ToStringDecoder::startForResult(this, headers, bodyStream, connection);
}
}}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/incoming/BodyDecoder.cpp
|
C++
|
apache-2.0
| 2,762
|
/***************************************************************************
*
* 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_incoming_BodyDecoder_hpp
#define oatpp_web_protocol_http_incoming_BodyDecoder_hpp
#include "oatpp/web/protocol/http/Http.hpp"
#include "oatpp/core/data/mapping/ObjectMapper.hpp"
#include "oatpp/core/data/stream/BufferStream.hpp"
#include "oatpp/core/async/Coroutine.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace incoming {
/**
* Abstract BodyDecoder.
* Body Decoder is responsible to decode body of incoming request.
* For example if you receive chunked-encoded body, you have to decode it in order to get "plain" body.
* You may extend this class in order to customize body-decoding process.
*/
class BodyDecoder {
private:
template<class Wrapper>
class ToDtoDecoder : public oatpp::async::CoroutineWithResult<ToDtoDecoder<Wrapper>, const Wrapper&> {
private:
const BodyDecoder* m_decoder;
Headers m_headers;
std::shared_ptr<data::stream::InputStream> m_bodyStream;
std::shared_ptr<data::stream::IOStream> m_connection;
std::shared_ptr<data::mapping::ObjectMapper> m_objectMapper;
std::shared_ptr<data::stream::BufferOutputStream> m_outputStream;
public:
ToDtoDecoder(const BodyDecoder* decoder,
Headers& headers,
const std::shared_ptr<data::stream::InputStream>& bodyStream,
const std::shared_ptr<data::stream::IOStream>& connection,
const std::shared_ptr<data::mapping::ObjectMapper>& objectMapper)
: m_decoder(decoder)
, m_headers(headers)
, m_bodyStream(bodyStream)
, m_connection(connection)
, m_objectMapper(objectMapper)
, m_outputStream(std::make_shared<data::stream::BufferOutputStream>())
{}
oatpp::async::Action act() override {
return m_decoder->decodeAsync(m_headers, m_bodyStream, m_outputStream, m_connection)
.next(this->yieldTo(&ToDtoDecoder::onDecoded));
}
oatpp::async::Action onDecoded() {
auto body = m_outputStream->toString();
oatpp::parser::Caret caret(body);
auto dto = m_objectMapper->readFromCaret<Wrapper>(caret);
if(caret.hasError()) {
return this->template error<oatpp::async::Error>(caret.getErrorMessage());
}
return this->_return(dto);
}
};
public:
/**
* Virtual destructor.
*/
virtual ~BodyDecoder() = default;
/**
* Implement this method! Decode bodyStream and write decoded data to toStream.
* @param headers - Headers map. &id:oatpp::web::protocol::http::Headers;.
* @param bodyStream - pointer to &id:oatpp::data::stream::InputStream;.
* @param writeCallback - &id:oatpp::data::stream::WriteCallback;.
* @param connection
*/
virtual void decode(const Headers& headers,
data::stream::InputStream* bodyStream,
data::stream::WriteCallback* writeCallback,
data::stream::IOStream* connection) const = 0;
/**
* Implement this method! Same as &l:BodyDecoder::decode (); but Async.
* @param headers - Headers map. &id:oatpp::web::protocol::http::Headers;.
* @param bodyStream - `std::shared_ptr` to &id:oatpp::data::stream::InputStream;.
* @param writeCallback - `std::shared_ptr` to &id:oatpp::data::stream::WriteCallback;.
* @param connection
* @return - &id:oatpp::async::CoroutineStarter;.
*/
virtual oatpp::async::CoroutineStarter decodeAsync(const Headers& headers,
const std::shared_ptr<data::stream::InputStream>& bodyStream,
const std::shared_ptr<data::stream::WriteCallback>& writeCallback,
const std::shared_ptr<data::stream::IOStream>& connection) const = 0;
/**
* Read body stream and decode it to string.
* @param headers - Headers map. &id:oatpp::web::protocol::http::Headers;.
* @param bodyStream - pointer to &id:oatpp::data::stream::InputStream;.
* @param connection
* @return - &oatpp::String;.
*/
oatpp::String decodeToString(const Headers& headers,
data::stream::InputStream* bodyStream,
data::stream::IOStream* connection) const
{
oatpp::data::stream::BufferOutputStream stream;
decode(headers, bodyStream, &stream, connection);
return stream.toString();
}
/**
* Read body stream, decode, and deserialize it as DTO Object (see [Data Transfer Object (DTO)](https://oatpp.io/docs/components/dto/)).
* @tparam Wrapper - ObjectWrapper type.
* @param headers - Headers map. &id:oatpp::web::protocol::http::Headers;.
* @param bodyStream - pointer to &id:oatpp::data::stream::InputStream;.
* @param connection
* @param objectMapper - pointer to &id:oatpp::data::mapping::ObjectMapper;.
* @return - deserialized DTO object.
*/
template<class Wrapper>
Wrapper decodeToDto(const Headers& headers,
data::stream::InputStream* bodyStream,
data::stream::IOStream* connection,
data::mapping::ObjectMapper* objectMapper) const
{
return objectMapper->readFromString<Wrapper>(decodeToString(headers, bodyStream, connection));
}
/**
* Same as &l:BodyDecoder::decodeToString (); but Async.
* @param headers - Headers map. &id:oatpp::web::protocol::http::Headers;.
* @param bodyStream - `std::shared_ptr` to &id:oatpp::data::stream::InputStream;.
* @param connection
* @return - &id:oatpp::async::CoroutineStarterForResult;.
*/
oatpp::async::CoroutineStarterForResult<const oatpp::String&>
decodeToStringAsync(const Headers& headers,
const std::shared_ptr<data::stream::InputStream>& bodyStream,
const std::shared_ptr<data::stream::IOStream>& connection) const;
/**
* Same as &l:BodyDecoder::decodeToDto (); but Async.
* @tparam Wrapper - ObjectWrapper type.
* @param headers - Headers map. &id:oatpp::web::protocol::http::Headers;.
* @param bodyStream - `std::shared_ptr` to &id:oatpp::data::stream::InputStream;.
* @param connection
* @param objectMapper - `std::shared_ptr` to &id:oatpp::data::mapping::ObjectMapper;.
* @return - &id:oatpp::async::CoroutineStarterForResult;.
*/
template<class Wrapper>
oatpp::async::CoroutineStarterForResult<const Wrapper&>
decodeToDtoAsync(const Headers& headers,
const std::shared_ptr<data::stream::InputStream>& bodyStream,
const std::shared_ptr<data::stream::IOStream>& connection,
const std::shared_ptr<data::mapping::ObjectMapper>& objectMapper) const
{
return ToDtoDecoder<Wrapper>::startForResult(this, headers, bodyStream, connection, objectMapper);
}
};
}}}}}
#endif /* oatpp_web_protocol_http_incoming_BodyDecoder_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/incoming/BodyDecoder.hpp
|
C++
|
apache-2.0
| 7,890
|
/***************************************************************************
*
* 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 "Request.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace incoming {
Request::Request(const std::shared_ptr<oatpp::data::stream::IOStream>& connection,
const http::RequestStartingLine& startingLine,
const http::Headers& headers,
const std::shared_ptr<oatpp::data::stream::InputStream>& bodyStream,
const std::shared_ptr<const http::incoming::BodyDecoder>& bodyDecoder)
: m_connection(connection)
, m_startingLine(startingLine)
, m_headers(headers)
, m_bodyStream(bodyStream)
, m_bodyDecoder(bodyDecoder)
, m_queryParamsParsed(false)
{}
std::shared_ptr<Request> Request::createShared(const std::shared_ptr<oatpp::data::stream::IOStream>& connection,
const http::RequestStartingLine& startingLine,
const http::Headers& headers,
const std::shared_ptr<oatpp::data::stream::InputStream>& bodyStream,
const std::shared_ptr<const http::incoming::BodyDecoder>& bodyDecoder)
{
return std::make_shared<Request>(connection, startingLine, headers, bodyStream, bodyDecoder);
}
std::shared_ptr<oatpp::data::stream::IOStream> Request::getConnection() {
return m_connection;
}
const http::RequestStartingLine& Request::getStartingLine() const {
return m_startingLine;
}
void Request::setPathVariables(const url::mapping::Pattern::MatchMap& pathVariables) {
m_pathVariables = pathVariables;
}
const url::mapping::Pattern::MatchMap& Request::getPathVariables() const {
return m_pathVariables;
}
const http::Headers& Request::getHeaders() const {
return m_headers;
}
const http::QueryParams& Request::getQueryParameters() const {
if(!m_queryParamsParsed) {
oatpp::network::Url::Parser::parseQueryParams(m_queryParams, m_pathVariables.getTail());
m_queryParamsParsed = true;
}
return m_queryParams;
}
oatpp::String Request::getQueryParameter(const oatpp::data::share::StringKeyLabel& name) const {
return getQueryParameters().get(name);
}
oatpp::String Request::getQueryParameter(const oatpp::data::share::StringKeyLabel& name, const oatpp::String& defaultValue) const {
auto value = getQueryParameter(name);
return value ? value : defaultValue;
}
std::shared_ptr<oatpp::data::stream::InputStream> Request::getBodyStream() const {
return m_bodyStream;
}
std::shared_ptr<const http::incoming::BodyDecoder> Request::getBodyDecoder() const {
return m_bodyDecoder;
}
void Request::putHeader(const oatpp::String& key, const oatpp::String& value) {
m_headers.put(key, value);
}
bool Request::putHeaderIfNotExists(const oatpp::String& key, const oatpp::String& value) {
return m_headers.putIfNotExists(key, value);
}
bool Request::putOrReplaceHeader(const String &key, const String &value) {
return m_headers.putOrReplace(key, value);
}
bool Request::putOrReplaceHeader_Unsafe(const data::share::StringKeyLabelCI& key,
const data::share::StringKeyLabel &value) {
return m_headers.putOrReplace(key, value);
}
void Request::putHeader_Unsafe(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value) {
m_headers.put(key, value);
}
bool Request::putHeaderIfNotExists_Unsafe(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value) {
return m_headers.putIfNotExists(key, value);
}
oatpp::String Request::getHeader(const oatpp::data::share::StringKeyLabelCI& headerName) const{
return m_headers.get(headerName);
}
oatpp::String Request::getPathVariable(const oatpp::data::share::StringKeyLabel& name) const {
return m_pathVariables.getVariable(name);
}
oatpp::String Request::getPathTail() const {
return m_pathVariables.getTail();
}
void Request::putBundleData(const oatpp::String& key, const oatpp::Void& polymorph) {
m_bundle.put(key, polymorph);
}
const data::Bundle& Request::getBundle() const {
return m_bundle;
}
void Request::transferBody(const base::ObjectHandle<data::stream::WriteCallback>& writeCallback) const {
m_bodyDecoder->decode(m_headers, m_bodyStream.get(), writeCallback.get(), m_connection.get());
}
void Request::transferBodyToStream(const base::ObjectHandle<oatpp::data::stream::OutputStream>& toStream) const {
m_bodyDecoder->decode(m_headers, m_bodyStream.get(), toStream.get(), m_connection.get());
}
oatpp::String Request::readBodyToString() const {
return m_bodyDecoder->decodeToString(m_headers, m_bodyStream.get(), m_connection.get());
}
async::CoroutineStarter Request::transferBodyAsync(const std::shared_ptr<data::stream::WriteCallback>& writeCallback) const {
return m_bodyDecoder->decodeAsync(m_headers, m_bodyStream, writeCallback, m_connection);
}
async::CoroutineStarter Request::transferBodyToStreamAsync(const std::shared_ptr<oatpp::data::stream::OutputStream>& toStream) const {
return m_bodyDecoder->decodeAsync(m_headers, m_bodyStream, toStream, m_connection);
}
async::CoroutineStarterForResult<const oatpp::String&> Request::readBodyToStringAsync() const {
return m_bodyDecoder->decodeToStringAsync(m_headers, m_bodyStream, m_connection);
}
}}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/incoming/Request.cpp
|
C++
|
apache-2.0
| 6,292
|
/***************************************************************************
*
* 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_incoming_Request_hpp
#define oatpp_web_protocol_http_incoming_Request_hpp
#include "oatpp/web/protocol/http/Http.hpp"
#include "oatpp/web/protocol/http/incoming/BodyDecoder.hpp"
#include "oatpp/web/url/mapping/Pattern.hpp"
#include "oatpp/network/Url.hpp"
#include "oatpp/core/data/Bundle.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace incoming {
/**
* Class http::incoming::Request AKA IncomingRequest represents client's incoming request.
*/
class Request : public oatpp::base::Countable {
private:
std::shared_ptr<oatpp::data::stream::IOStream> m_connection;
http::RequestStartingLine m_startingLine;
url::mapping::Pattern::MatchMap m_pathVariables;
http::Headers m_headers;
std::shared_ptr<oatpp::data::stream::InputStream> m_bodyStream;
/*
* Request should be preconfigured with default BodyDecoder.
* Custom BodyDecoder can be set on demand
*/
std::shared_ptr<const http::incoming::BodyDecoder> m_bodyDecoder;
mutable bool m_queryParamsParsed; // used for lazy parsing of QueryParams
mutable http::QueryParams m_queryParams;
data::Bundle m_bundle;
public:
Request(const std::shared_ptr<oatpp::data::stream::IOStream>& connection,
const http::RequestStartingLine& startingLine,
const http::Headers& headers,
const std::shared_ptr<oatpp::data::stream::InputStream>& bodyStream,
const std::shared_ptr<const http::incoming::BodyDecoder>& bodyDecoder);
public:
static std::shared_ptr<Request> createShared(const std::shared_ptr<oatpp::data::stream::IOStream>& connection,
const http::RequestStartingLine& startingLine,
const http::Headers& headers,
const std::shared_ptr<oatpp::data::stream::InputStream>& bodyStream,
const std::shared_ptr<const http::incoming::BodyDecoder>& bodyDecoder);
/**
* Get raw connection stream.
* @return - &id:std::shared_ptr<oatpp::data::stream::IOStream> m_connection;.
*/
std::shared_ptr<oatpp::data::stream::IOStream> getConnection();
/**
* Get map of url query parameters.
* Query parameters will be lazy parsed from url "tail"
* Please note: lazy parsing of query parameters is not thread-safe!
* @return map<key, value> for "&key=value"
*/
const http::QueryParams& getQueryParameters() const;
/**
* Get query parameter value by name
* @param name
* @return query parameter value
*/
oatpp::String getQueryParameter(const oatpp::data::share::StringKeyLabel& name) const;
/**
* Get query parameter value by name with defaultValue
* @param name
* @param defaultValue
* @return query parameter value or defaultValue if no such parameter found
*/
oatpp::String getQueryParameter(const oatpp::data::share::StringKeyLabel& name, const oatpp::String& defaultValue) const;
/**
* Get request starting line. (method, path, protocol)
* @return starting line structure
*/
const http::RequestStartingLine& getStartingLine() const;
/**
* Set request path variables.
* @param pathVariables - &id:oatpp::web::url::mapping::Pattern::MatchMap;.
*/
void setPathVariables(const url::mapping::Pattern::MatchMap& pathVariables);
/**
* Get path variables according to path-pattern. <br>
* Ex. given request path="/sum/19/1" for path-pattern="/sum/{a}/{b}" <br>
* getPathVariables().getVariable("a") == 19, getPathVariables().getVariable("b") == 1.
*
* @return url MatchMap
*/
const url::mapping::Pattern::MatchMap& getPathVariables() const;
/**
* Get request's headers map
* @return Headers map
*/
const http::Headers& getHeaders() const;
/**
* Get request's body stream
* @return body stream
*/
std::shared_ptr<oatpp::data::stream::InputStream> getBodyStream() const;
/**
* Get body decoder.
* @return Body decoder
*/
std::shared_ptr<const http::incoming::BodyDecoder> getBodyDecoder() const;
/**
* Add http header.
* @param key - &id:oatpp::String;.
* @param value - &id:oatpp::String;.
*/
void putHeader(const oatpp::String& key, const oatpp::String& value);
/**
* Add http header if not already exists.
* @param key - &id:oatpp::String;.
* @param value - &id:oatpp::String;.
* @return - `true` if header was added.
*/
bool putHeaderIfNotExists(const oatpp::String& key, const oatpp::String& value);
/**
* Replaces or adds header.
* @param key - &id:oatpp::String;.
* @param value - &id:oatpp::String;.
* @return - `true` if header was replaces, `false` if header was added.
*/
bool putOrReplaceHeader(const oatpp::String& key, const oatpp::String& value);
/**
* Replaces or adds header.
* @param key - &id:oatpp::data::share::StringKeyLabelCI;.
* @param value - &id:oatpp::data::share::StringKeyLabel;.
* @return - `true` if header was replaces, `false` if header was added.
*/
bool putOrReplaceHeader_Unsafe(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value);
/**
* Add http header.
* @param key - &id:oatpp::data::share::StringKeyLabelCI;.
* @param value - &id:oatpp::data::share::StringKeyLabel;.
*/
void putHeader_Unsafe(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value);
/**
* Add http header if not already exists.
* @param key - &id:oatpp::data::share::StringKeyLabelCI;.
* @param value - &id:oatpp::data::share::StringKeyLabel;.
* @return - `true` if header was added.
*/
bool putHeaderIfNotExists_Unsafe(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value);
/**
* Get header value
* @param headerName - &id:oatpp::data::share::StringKeyLabelCI;.
* @return - &id:oatpp::String;.
*/
oatpp::String getHeader(const oatpp::data::share::StringKeyLabelCI& headerName) const;
/**
* Get path variable according to path-pattern
* @param name
* @return matched value for path-pattern
*/
oatpp::String getPathVariable(const oatpp::data::share::StringKeyLabel& name) const;
/**
* Get path tail according to path-pattern
* Ex. given request path="/hello/path/tail" for path-pattern="/hello/\*"
* tail == "path/tail"
* note '/' symbol is required before '*'
* @return matched tail-value for path-pattern
*/
oatpp::String getPathTail() const;
/**
* Put data to bundle.
* @param key
* @param polymorph
*/
void putBundleData(const oatpp::String& key, const oatpp::Void& polymorph);
/**
* Get data from bundle by key.
* @tparam WrapperType
* @param key
* @return
*/
template<typename WrapperType>
WrapperType getBundleData(const oatpp::String& key) const {
return m_bundle.template get<WrapperType>(key);
}
/**
* Get bundle object.
* @return
*/
const data::Bundle& getBundle() const;
/**
* Transfer body. <br>
* Read body chunk by chunk and pass chunks to the `writeCallback`.
* @param writeCallback - &id:oatpp::data::stream::WriteCallback;.
*/
void transferBody(const base::ObjectHandle<data::stream::WriteCallback>& writeCallback) const;
/**
* Stream content of the body-stream to toStream
* @param toStream
*/
void transferBodyToStream(const base::ObjectHandle<data::stream::OutputStream>& toStream) const;
/**
* Transfer body stream to string
* @return body as string
*/
oatpp::String readBodyToString() const;
/**
* Transfer body to String and parse it as DTO
* @tparam Wrapper - ObjectWrapper type.
* @param objectMapper
* @return DTO
*/
template<class Wrapper>
Wrapper readBodyToDto(const base::ObjectHandle<data::mapping::ObjectMapper>& objectMapper) const {
return objectMapper->readFromString<Wrapper>(m_bodyDecoder->decodeToString(m_headers, m_bodyStream.get(), m_connection.get()));
}
// Async
/**
* Transfer body in Asynchronous manner. <br>
* Read body chunk by chunk and pass chunks to the `writeCallback`.
* @param writeCallback - `std::shared_ptr` to &id:oatpp::data::stream::WriteCallback;.
* @return - &id:oatpp::async::CoroutineStarter;.
*/
async::CoroutineStarter transferBodyAsync(const std::shared_ptr<data::stream::WriteCallback>& writeCallback) const;
/**
* Transfer body stream to toStream Async
* @param toStream
* @return - &id:oatpp::async::CoroutineStarter;.
*/
oatpp::async::CoroutineStarter transferBodyToStreamAsync(const std::shared_ptr<oatpp::data::stream::OutputStream>& toStream) const;
/**
* Transfer body stream to string Async.
* @return - &id:oatpp::async::CoroutineStarterForResult;.
*/
async::CoroutineStarterForResult<const oatpp::String&> readBodyToStringAsync() const;
/**
* Transfer body to String and parse it as DTO
* @tparam Wrapper - DTO `ObjectWrapper`.
* @param objectMapper
* @return - &id:oatpp::async::CoroutineStarterForResult;.
*/
template<class Wrapper>
oatpp::async::CoroutineStarterForResult<const Wrapper&>
readBodyToDtoAsync(const std::shared_ptr<oatpp::data::mapping::ObjectMapper>& objectMapper) const {
return m_bodyDecoder->decodeToDtoAsync<Wrapper>(m_headers, m_bodyStream, m_connection, objectMapper);
}
};
}}}}}
#endif /* oatpp_web_protocol_http_incoming_Request_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/incoming/Request.hpp
|
C++
|
apache-2.0
| 10,495
|
/***************************************************************************
*
* 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 "RequestHeadersReader.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace incoming {
v_io_size RequestHeadersReader::readHeadersSectionIterative(ReadHeadersIteration& iteration,
data::stream::InputStreamBufferedProxy* stream,
async::Action& action)
{
v_buff_size desiredToRead = m_readChunkSize;
if(m_bufferStream->getCurrentPosition() + desiredToRead > m_maxHeadersSize) {
desiredToRead = m_maxHeadersSize - m_bufferStream->getCurrentPosition();
if(desiredToRead <= 0) {
return -1;
}
}
m_bufferStream->reserveBytesUpfront(desiredToRead);
auto bufferData = m_bufferStream->getData() + m_bufferStream->getCurrentPosition();
auto res = stream->peek(bufferData, desiredToRead, action);
if(res > 0) {
m_bufferStream->setCurrentPosition(m_bufferStream->getCurrentPosition() + res);
for(v_buff_size i = 0; i < res; i ++) {
iteration.accumulator <<= 8;
iteration.accumulator |= bufferData[i];
if(iteration.accumulator == SECTION_END) {
stream->commitReadOffset(i + 1);
iteration.done = true;
return res;
}
}
stream->commitReadOffset(res);
}
return res;
}
RequestHeadersReader::Result RequestHeadersReader::readHeaders(data::stream::InputStreamBufferedProxy* stream,
http::HttpError::Info& error) {
m_bufferStream->setCurrentPosition(0);
RequestHeadersReader::Result result;
ReadHeadersIteration iteration;
async::Action action;
while(!iteration.done) {
error.ioStatus = readHeadersSectionIterative(iteration, stream, action);
if(!action.isNone()) {
OATPP_LOGE("[oatpp::web::protocol::http::incoming::RequestHeadersReader::readHeaders]", "Error. Async action is unexpected.");
throw std::runtime_error("[oatpp::web::protocol::http::incoming::RequestHeadersReader::readHeaders]: Error. Async action is unexpected.");
}
if(error.ioStatus > 0) {
continue;
} else if(error.ioStatus == IOError::RETRY_READ || error.ioStatus == IOError::RETRY_WRITE) {
continue;
} else {
break;
}
}
if(error.ioStatus > 0) {
oatpp::parser::Caret caret ((const char*) m_bufferStream->getData(), m_bufferStream->getCurrentPosition());
http::Status status;
http::Parser::parseRequestStartingLine(result.startingLine, nullptr, caret, status);
if(status.code == 0) {
http::Parser::parseHeaders(result.headers, nullptr, caret, status);
}
}
return result;
}
oatpp::async::CoroutineStarterForResult<const RequestHeadersReader::Result&>
RequestHeadersReader::readHeadersAsync(const std::shared_ptr<data::stream::InputStreamBufferedProxy>& stream)
{
class ReaderCoroutine : public oatpp::async::CoroutineWithResult<ReaderCoroutine, const Result&> {
private:
std::shared_ptr<data::stream::InputStreamBufferedProxy> m_stream;
RequestHeadersReader* m_this;
ReadHeadersIteration m_iteration;
RequestHeadersReader::Result m_result;
public:
ReaderCoroutine(RequestHeadersReader* _this,
const std::shared_ptr<data::stream::InputStreamBufferedProxy>& stream)
: m_stream(stream)
, m_this(_this)
{
m_this->m_bufferStream->setCurrentPosition(0);
}
Action act() override {
async::Action action;
auto res = m_this->readHeadersSectionIterative(m_iteration, m_stream.get(), action);
if(!action.isNone()) {
return action;
}
if(m_iteration.done) {
return yieldTo(&ReaderCoroutine::parseHeaders);
} else {
if (res > 0) {
return repeat();
} else if (res == IOError::RETRY_READ || res == IOError::RETRY_WRITE) {
return repeat();
}
}
return error<Error>("[oatpp::web::protocol::http::incoming::RequestHeadersReader::readHeadersAsync()]: Error. Error reading connection stream.");
}
Action parseHeaders() {
oatpp::parser::Caret caret ((const char*) m_this->m_bufferStream->getData(), m_this->m_bufferStream->getCurrentPosition());
http::Status status;
http::Parser::parseRequestStartingLine(m_result.startingLine, nullptr, caret, status);
if(status.code == 0) {
http::Parser::parseHeaders(m_result.headers, nullptr, caret, status);
if(status.code == 0) {
return _return(m_result);
} else {
return error<Error>("[oatpp::web::protocol::http::incoming::RequestHeadersReader::readHeadersAsync()]: Error. Error occurred while parsing headers.");
}
} else {
return error<Error>("[oatpp::web::protocol::http::incoming::RequestHeadersReader::readHeadersAsync()]: Error. Can't parse starting line.");
}
}
};
return ReaderCoroutine::startForResult(this, stream);
}
}}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/incoming/RequestHeadersReader.cpp
|
C++
|
apache-2.0
| 6,008
|
/***************************************************************************
*
* 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_incoming_RequestHeadersReader_hpp
#define oatpp_web_protocol_http_incoming_RequestHeadersReader_hpp
#include "oatpp/web/protocol/http/Http.hpp"
#include "oatpp/core/async/Coroutine.hpp"
#include "oatpp/core/data/stream/StreamBufferedProxy.hpp"
#include "oatpp/core/data/stream/BufferStream.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace incoming {
/**
* Helper class to read http headers of incoming request from stream.
*/
class RequestHeadersReader {
public:
/**
* Convenience typedef for &id:oatpp::async::Action;.
*/
typedef oatpp::async::Action Action;
private:
static constexpr v_uint32 SECTION_END = ('\r' << 24) | ('\n' << 16) | ('\r' << 8) | ('\n');
public:
/**
* Result of headers reading and parsing.
*/
struct Result {
/**
* &id:oatpp::web::protocol::http::RequestStartingLine;.
*/
http::RequestStartingLine startingLine;
/**
* &id:oatpp::web::protocol::http::Headers;.
*/
http::Headers headers;
};
private:
struct ReadHeadersIteration {
v_uint32 accumulator = 0;
bool done = false;
};
private:
v_io_size readHeadersSectionIterative(ReadHeadersIteration& iteration,
data::stream::InputStreamBufferedProxy* stream,
async::Action& action);
private:
oatpp::data::stream::BufferOutputStream* m_bufferStream;
v_buff_size m_readChunkSize;
v_buff_size m_maxHeadersSize;
public:
/**
* Constructor.
* @param readChunkSize
* @param maxHeadersSize
*/
RequestHeadersReader(oatpp::data::stream::BufferOutputStream* bufferStream,
v_buff_size readChunkSize = 2048,
v_buff_size maxHeadersSize = 4096)
: m_bufferStream(bufferStream)
, m_readChunkSize(readChunkSize)
, m_maxHeadersSize(maxHeadersSize)
{}
/**
* Read and parse http headers from stream.
* @param stream - &id:oatpp::data::stream::InputStreamBufferedProxy;.
* @param error - out parameter &id:oatpp::web::protocol::ProtocolError::Info;.
* @return - &l:RequestHeadersReader::Result;.
*/
Result readHeaders(data::stream::InputStreamBufferedProxy* stream, http::HttpError::Info& error);
/**
* Read and parse http headers from stream in asynchronous manner.
* @param stream - `std::shared_ptr` to &id:oatpp::data::stream::InputStreamBufferedProxy;.
* @return - &id:oatpp::async::CoroutineStarterForResult;.
*/
oatpp::async::CoroutineStarterForResult<const RequestHeadersReader::Result&> readHeadersAsync(const std::shared_ptr<data::stream::InputStreamBufferedProxy>& stream);
};
}}}}}
#endif /* oatpp_web_protocol_http_incoming_RequestHeadersReader_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/incoming/RequestHeadersReader.hpp
|
C++
|
apache-2.0
| 3,782
|
/***************************************************************************
*
* 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 "./Response.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace incoming {
Response::Response(v_int32 statusCode,
const oatpp::String& statusDescription,
const http::Headers& headers,
const std::shared_ptr<oatpp::data::stream::InputStream>& bodyStream,
const std::shared_ptr<const http::incoming::BodyDecoder>& bodyDecoder)
: m_statusCode(statusCode)
, m_statusDescription(statusDescription)
, m_headers(headers)
, m_bodyStream(bodyStream)
, m_bodyDecoder(bodyDecoder)
{}
std::shared_ptr<Response> Response::createShared(v_int32 statusCode,
const oatpp::String& statusDescription,
const http::Headers& headers,
const std::shared_ptr<oatpp::data::stream::InputStream>& bodyStream,
const std::shared_ptr<const http::incoming::BodyDecoder>& bodyDecoder)
{
return std::make_shared<Response>(statusCode, statusDescription, headers, bodyStream, bodyDecoder);
}
v_int32 Response::getStatusCode() const {
return m_statusCode;
}
oatpp::String Response::getStatusDescription() const {
return m_statusDescription;
}
const http::Headers& Response::getHeaders() const {
return m_headers;
}
void Response::putHeader(const oatpp::String& key, const oatpp::String& value) {
m_headers.put(key, value);
}
bool Response::putHeaderIfNotExists(const oatpp::String& key, const oatpp::String& value) {
return m_headers.putIfNotExists(key, value);
}
bool Response::putOrReplaceHeader(const String &key, const String &value) {
return m_headers.putOrReplace(key, value);
}
bool Response::putOrReplaceHeader_Unsafe(const data::share::StringKeyLabelCI& key,
const data::share::StringKeyLabel &value) {
return m_headers.putOrReplace(key, value);
}
void Response::putHeader_Unsafe(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value) {
m_headers.put(key, value);
}
bool Response::putHeaderIfNotExists_Unsafe(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value) {
return m_headers.putIfNotExists(key, value);
}
oatpp::String Response::getHeader(const oatpp::data::share::StringKeyLabelCI& headerName) const{
return m_headers.get(headerName);
}
void Response::putBundleData(const oatpp::String& key, const oatpp::Void& polymorph) {
m_bundle.put(key, polymorph);
}
const data::Bundle& Response::getBundle() const {
return m_bundle;
}
std::shared_ptr<oatpp::data::stream::InputStream> Response::getBodyStream() const {
return m_bodyStream;
}
std::shared_ptr<const http::incoming::BodyDecoder> Response::getBodyDecoder() const {
return m_bodyDecoder;
}
void Response::transferBody(const base::ObjectHandle<data::stream::WriteCallback>& writeCallback) const {
m_bodyDecoder->decode(m_headers, m_bodyStream.get(), writeCallback.get(), m_connection.get());
}
void Response::transferBodyToStream(const base::ObjectHandle<oatpp::data::stream::OutputStream>& toStream) const {
m_bodyDecoder->decode(m_headers, m_bodyStream.get(), toStream.get(), m_connection.get());
}
oatpp::String Response::readBodyToString() const {
return m_bodyDecoder->decodeToString(m_headers, m_bodyStream.get(), m_connection.get());
}
async::CoroutineStarter Response::transferBodyAsync(const std::shared_ptr<data::stream::WriteCallback>& writeCallback) const {
return m_bodyDecoder->decodeAsync(m_headers, m_bodyStream, writeCallback, m_connection);
}
oatpp::async::CoroutineStarter Response::transferBodyToStreamAsync(const std::shared_ptr<oatpp::data::stream::OutputStream>& toStream) const {
return m_bodyDecoder->decodeAsync(m_headers, m_bodyStream, toStream, m_connection);
}
}}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/incoming/Response.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_web_protocol_http_incoming_Response_hpp
#define oatpp_web_protocol_http_incoming_Response_hpp
#include "oatpp/web/protocol/http/Http.hpp"
#include "oatpp/web/protocol/http/incoming/BodyDecoder.hpp"
#include "oatpp/core/data/Bundle.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace incoming {
/**
* Class http::incoming::Response AKA IncomingResponse represents server's incoming response
*/
class Response : public oatpp::base::Countable {
private:
v_int32 m_statusCode;
oatpp::String m_statusDescription;
http::Headers m_headers;
std::shared_ptr<oatpp::data::stream::InputStream> m_bodyStream;
/*
* Response should be preconfigured with default BodyDecoder.
* Entity that created response object is responsible for providing correct BodyDecoder.
* Custom BodyDecoder can be set on demand
*/
std::shared_ptr<const http::incoming::BodyDecoder> m_bodyDecoder;
std::shared_ptr<oatpp::data::stream::IOStream> m_connection;
data::Bundle m_bundle;
public:
/**
* Constructor.
* @param statusCode - http status code.
* @param statusDescription - http status description.
* @param headers - &id:oatpp::web::protocol::http::Headers;.
* @param bodyStream - &id:oatpp::data::stream::InputStream;.
* @param bodyDecoder - &id:oatpp::web::protocol::http::incoming::BodyDecoder;.
*/
Response(v_int32 statusCode,
const oatpp::String& statusDescription,
const http::Headers& headers,
const std::shared_ptr<oatpp::data::stream::InputStream>& bodyStream,
const std::shared_ptr<const http::incoming::BodyDecoder>& bodyDecoder);
public:
/**
* Create shared Response.
* @param statusCode - http status code.
* @param statusDescription - http status description.
* @param headers - &id:oatpp::web::protocol::http::Headers;.
* @param bodyStream - &id:oatpp::data::stream::InputStream;.
* @param bodyDecoder - &id:oatpp::web::protocol::http::incoming::BodyDecoder;.
* @return - `std::shared_ptr` to Response.
*/
static std::shared_ptr<Response> createShared(v_int32 statusCode,
const oatpp::String& statusDescription,
const http::Headers& headers,
const std::shared_ptr<oatpp::data::stream::InputStream>& bodyStream,
const std::shared_ptr<const http::incoming::BodyDecoder>& bodyDecoder);
/**
* Get http status code.
* @return - http status code.
*/
v_int32 getStatusCode() const;
/**
* Get http status description.
* @return - http status description.
*/
oatpp::String getStatusDescription() const;
/**
* Get response http headers as &id:oatpp::web::protocol::http::Headers;.
* @return - response http headers as &id:oatpp::web::protocol::http::Headers;.
*/
const http::Headers& getHeaders() const;
/**
* Add http header.
* @param key - &id:oatpp::String;.
* @param value - &id:oatpp::String;.
*/
void putHeader(const oatpp::String& key, const oatpp::String& value);
/**
* Add http header if not already exists.
* @param key - &id:oatpp::String;.
* @param value - &id:oatpp::String;.
* @return - `true` if header was added.
*/
bool putHeaderIfNotExists(const oatpp::String& key, const oatpp::String& value);
/**
* Replaces or adds header.
* @param key - &id:oatpp::String;.
* @param value - &id:oatpp::String;.
* @return - `true` if header was replaces, `false` if header was added.
*/
bool putOrReplaceHeader(const oatpp::String& key, const oatpp::String& value);
/**
* Replaces or adds header.
* @param key - &id:oatpp::data::share::StringKeyLabelCI;.
* @param value - &id:oatpp::data::share::StringKeyLabel;.
* @return - `true` if header was replaces, `false` if header was added.
*/
bool putOrReplaceHeader_Unsafe(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value);
/**
* Add http header.
* @param key - &id:oatpp::data::share::StringKeyLabelCI;.
* @param value - &id:oatpp::data::share::StringKeyLabel;.
*/
void putHeader_Unsafe(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value);
/**
* Add http header if not already exists.
* @param key - &id:oatpp::data::share::StringKeyLabelCI;.
* @param value - &id:oatpp::data::share::StringKeyLabel;.
* @return - `true` if header was added.
*/
bool putHeaderIfNotExists_Unsafe(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value);
/**
* Get header value
* @param headerName - &id:oatpp::data::share::StringKeyLabelCI;.
* @return - &id:oatpp::String;.
*/
oatpp::String getHeader(const oatpp::data::share::StringKeyLabelCI& headerName) const;
/**
* Put data to bundle.
* @param key
* @param polymorph
*/
void putBundleData(const oatpp::String& key, const oatpp::Void& polymorph);
/**
* Get data from bundle by key.
* @tparam WrapperType
* @param key
* @return
*/
template<typename WrapperType>
WrapperType getBundleData(const oatpp::String& key) const {
return m_bundle.template get<WrapperType>(key);
}
/**
* Get bundle object.
* @return
*/
const data::Bundle& getBundle() const;
/**
* Get raw body stream.
* @return - raw body stream as &id:oatpp::data::stream::InputStream;.
*/
std::shared_ptr<data::stream::InputStream> getBodyStream() const;
/**
* Get body decoder configured for this response.
* @return - &id:oatpp::web::protocol::http::incoming::BodyDecoder;.
*/
std::shared_ptr<const http::incoming::BodyDecoder> getBodyDecoder() const;
/**
* Transfer body. <br>
* Read body chunk by chunk and pass chunks to the `writeCallback`.
* @param writeCallback - &id:oatpp::data::stream::WriteCallback;.
*/
void transferBody(const base::ObjectHandle<data::stream::WriteCallback>& writeCallback) const;
/**
* Decode and transfer body to toStream.
* Use case example - stream huge body directly to file using relatively small buffer.
* @param toStream - pointer to &id:oatpp::data::stream::OutputStream;.
*/
void transferBodyToStream(const base::ObjectHandle<data::stream::OutputStream>& toStream) const;
/**
* Decode and read body to &id:oatpp::String;.
* @return - &id:oatpp::String;.
*/
oatpp::String readBodyToString() const;
/**
* Read body stream, decode, and deserialize it as DTO Object (see [Data Transfer Object (DTO)](https://oatpp.io/docs/components/dto/)).
* @tparam Wrapper - ObjectWrapper type.
* @param objectMapper - `std::shared_ptr` to &id:oatpp::data::mapping::ObjectMapper;.
* @return - deserialized DTO object.
*/
template<class Wrapper>
Wrapper readBodyToDto(const base::ObjectHandle<data::mapping::ObjectMapper>& objectMapper) const {
return m_bodyDecoder->decodeToDto<Wrapper>(m_headers, m_bodyStream.get(), m_connection.get(), objectMapper.get());
}
// Async
/**
* Transfer body in Asynchronous manner. <br>
* Read body chunk by chunk and pass chunks to the `writeCallback`.
* @param writeCallback - `std::shared_ptr` to &id:oatpp::data::stream::WriteCallback;.
* @return - &id:oatpp::async::CoroutineStarter;.
*/
async::CoroutineStarter transferBodyAsync(const std::shared_ptr<data::stream::WriteCallback>& writeCallback) const;
/**
* Same as &l:Response::readBodyToDto (); but Async.
* @param toStream - `std::shared_ptr` to &id:oatpp::data::stream::OutputStream;.
* @return - &id:oatpp::async::CoroutineStarter;.
*/
oatpp::async::CoroutineStarter transferBodyToStreamAsync(const std::shared_ptr<data::stream::OutputStream>& toStream) const;
/**
* Same as &l:Response::readBodyToString (); but Async.
* @return - &id:oatpp::async::CoroutineStarterForResult;.
*/
oatpp::async::CoroutineStarterForResult<const oatpp::String&> readBodyToStringAsync() const {
return m_bodyDecoder->decodeToStringAsync(m_headers, m_bodyStream, m_connection);
}
/**
* Same as &l:Response::readBodyToDto (); but Async.
* @tparam Wrapper - ObjectWrapper type.
* @param objectMapper - `std::shared_ptr` to &id:oatpp::data::mapping::ObjectMapper;.
* @return - &id:oatpp::async::CoroutineStarterForResult;.
*/
template<class Wrapper>
oatpp::async::CoroutineStarterForResult<const Wrapper&>
readBodyToDtoAsync(const std::shared_ptr<data::mapping::ObjectMapper>& objectMapper) const {
return m_bodyDecoder->decodeToDtoAsync<Wrapper>(m_headers, m_bodyStream, m_connection, objectMapper);
}
};
}}}}}
#endif /* oatpp_web_protocol_http_incoming_Response_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/incoming/Response.hpp
|
C++
|
apache-2.0
| 9,829
|
/***************************************************************************
*
* 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 "ResponseHeadersReader.hpp"
#include "oatpp/core/data/stream/BufferStream.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace incoming {
v_io_size ResponseHeadersReader::readHeadersSectionIterative(ReadHeadersIteration& iteration,
const std::shared_ptr<oatpp::data::stream::IOStream>& connection,
data::stream::ConsistentOutputStream* bufferStream,
Result& result,
async::Action& action)
{
v_buff_size desiredToRead = m_buffer.getSize();
if(iteration.progress + desiredToRead > m_maxHeadersSize) {
desiredToRead = m_maxHeadersSize - iteration.progress;
if(desiredToRead <= 0) {
return -1;
}
}
auto bufferData = (p_char8) m_buffer.getData();
auto res = connection->read(bufferData, desiredToRead, action);
if(res > 0) {
bufferStream->writeSimple(bufferData, res);
for(v_buff_size i = 0; i < res; i ++) {
iteration.accumulator <<= 8;
iteration.accumulator |= bufferData[i];
if(iteration.accumulator == SECTION_END) {
result.bufferPosStart = i + 1;
result.bufferPosEnd = res;
iteration.done = true;
return res;
}
}
}
return res;
}
ResponseHeadersReader::Result ResponseHeadersReader::readHeaders(const std::shared_ptr<oatpp::data::stream::IOStream>& connection,
http::HttpError::Info& error) {
Result result;
ReadHeadersIteration iteration;
async::Action action;
oatpp::data::stream::BufferOutputStream buffer;
while(!iteration.done) {
error.ioStatus = readHeadersSectionIterative(iteration, connection, &buffer, result, action);
if(!action.isNone()) {
throw std::runtime_error("[oatpp::web::protocol::http::incoming::ResponseHeadersReader::readHeaders]: Error. Async action is unexpected.");
}
if(error.ioStatus > 0) {
continue;
} else if(error.ioStatus == IOError::RETRY_READ || error.ioStatus == IOError::RETRY_WRITE) {
continue;
} else {
break;
}
}
if(error.ioStatus > 0) {
auto headersText = buffer.toString();
oatpp::parser::Caret caret (headersText);
http::Status status;
http::Parser::parseResponseStartingLine(result.startingLine, headersText.getPtr(), caret, status);
if(status.code == 0) {
http::Parser::parseHeaders(result.headers, headersText.getPtr(), caret, status);
}
}
return result;
}
oatpp::async::CoroutineStarterForResult<const ResponseHeadersReader::Result&>
ResponseHeadersReader::readHeadersAsync(const std::shared_ptr<oatpp::data::stream::IOStream>& connection)
{
class ReaderCoroutine : public oatpp::async::CoroutineWithResult<ReaderCoroutine, const Result&> {
private:
ResponseHeadersReader* m_this;
std::shared_ptr<oatpp::data::stream::IOStream> m_connection;
ReadHeadersIteration m_iteration;
ResponseHeadersReader::Result m_result;
oatpp::data::stream::BufferOutputStream m_bufferStream;
public:
ReaderCoroutine(ResponseHeadersReader* _this,
const std::shared_ptr<oatpp::data::stream::IOStream>& connection)
: m_this(_this)
, m_connection(connection)
{}
Action act() override {
async::Action action;
auto res = m_this->readHeadersSectionIterative(m_iteration, m_connection, &m_bufferStream, m_result, action);
if(!action.isNone()) {
return action;
}
if(m_iteration.done) {
return yieldTo(&ReaderCoroutine::parseHeaders);
} else {
if (res > 0) {
return repeat();
} else if (res == IOError::RETRY_READ || res == IOError::RETRY_WRITE) {
return repeat();
}
}
return error<Error>("[oatpp::web::protocol::http::incoming::RequestHeadersReader::readHeadersAsync()]: Error. Error reading connection stream.");
}
Action parseHeaders() {
auto headersText = m_bufferStream.toString();
oatpp::parser::Caret caret (headersText);
http::Status status;
http::Parser::parseResponseStartingLine(m_result.startingLine, headersText.getPtr(), caret, status);
if(status.code == 0) {
http::Parser::parseHeaders(m_result.headers, headersText.getPtr(), caret, status);
if(status.code == 0) {
return _return(m_result);
} else {
return error<Error>("[oatpp::web::protocol::http::incoming::ResponseHeadersReader::readHeadersAsync()]: Error. Error occurred while parsing headers.");
}
} else {
return error<Error>("[oatpp::web::protocol::http::incoming::ResponseHeadersReader::readHeadersAsync()]: Error. Can't parse starting line.");
}
}
};
return ReaderCoroutine::startForResult(this, connection);
}
}}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/incoming/ResponseHeadersReader.cpp
|
C++
|
apache-2.0
| 6,060
|
/***************************************************************************
*
* 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_incoming_ResponseHeadersReader_hpp
#define oatpp_web_protocol_http_incoming_ResponseHeadersReader_hpp
#include "oatpp/web/protocol/http/Http.hpp"
#include "oatpp/core/async/Coroutine.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace incoming {
/**
* Helper class to read http headers of incoming response from stream.
*/
class ResponseHeadersReader {
public:
/**
* Convenience typedef for &id:oatpp::async::Action;.
*/
typedef oatpp::async::Action Action;
private:
static constexpr v_uint32 SECTION_END = ('\r' << 24) | ('\n' << 16) | ('\r' << 8) | ('\n');
public:
/**
* Result of headers reading and parsing.
*/
struct Result {
/**
* &id:oatpp::web::protocol::http::ResponseStartingLine;.
*/
http::ResponseStartingLine startingLine;
/**
* &id:oatpp::web::protocol::http::Headers;.
*/
http::Headers headers;
/**
* This value represents starting position in buffer used to read data from stream for the last read operation.
*/
v_buff_size bufferPosStart;
/**
* This value represents end position in buffer used to read data from stream for the last read operation.
*/
v_buff_size bufferPosEnd;
};
private:
struct ReadHeadersIteration {
v_uint32 accumulator = 0;
v_buff_size progress = 0;
bool done = false;
};
private:
v_io_size readHeadersSectionIterative(ReadHeadersIteration& iteration,
const std::shared_ptr<oatpp::data::stream::IOStream>& connection,
data::stream::ConsistentOutputStream* bufferStream,
Result& result,
async::Action& action);
private:
oatpp::data::share::MemoryLabel m_buffer;
v_buff_size m_maxHeadersSize;
public:
/**
* Constructor.
* @param buffer - buffer to use to read data from stream. &id:oatpp::data::share::MemoryLabel;.
* @param maxHeadersSize
*/
ResponseHeadersReader(const oatpp::data::share::MemoryLabel& buffer, v_buff_size maxHeadersSize)
: m_buffer(buffer)
, m_maxHeadersSize(maxHeadersSize)
{}
/**
* Read and parse http headers from stream.
* @param connection - `std::shared_ptr` to &id:oatpp::data::stream::IOStream;.
* @param error - out parameter &id:oatpp::web::protocol::ProtocolError::Info;.
* @return - &l:ResponseHeadersReader::Result;.
*/
Result readHeaders(const std::shared_ptr<oatpp::data::stream::IOStream>& connection, http::HttpError::Info& error);
/**
* Read and parse http headers from stream in asynchronous manner.
* @param connection - `std::shared_ptr` to &id:oatpp::data::stream::IOStream;.
* @return - &id:oatpp::async::CoroutineStarterForResult;.
*/
oatpp::async::CoroutineStarterForResult<const Result&> readHeadersAsync(const std::shared_ptr<oatpp::data::stream::IOStream>& connection);
};
}}}}}
#endif /* oatpp_web_protocol_http_incoming_ResponseHeadersReader_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/incoming/ResponseHeadersReader.hpp
|
C++
|
apache-2.0
| 4,084
|
/***************************************************************************
*
* 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 "SimpleBodyDecoder.hpp"
#include "oatpp/web/protocol/http/encoding/Chunked.hpp"
#include "oatpp/core/utils/ConversionUtils.hpp"
#include <vector>
namespace oatpp { namespace web { namespace protocol { namespace http { namespace incoming {
const std::string SimpleBodyDecoder::RESPONSE_100_CONTINUE = "HTTP/1.1 100 Continue\r\n";
SimpleBodyDecoder::SimpleBodyDecoder(const std::shared_ptr<encoding::ProviderCollection>& contentDecoders)
: m_contentDecoders(contentDecoders)
{}
base::ObjectHandle<data::buffer::Processor>
SimpleBodyDecoder::getStreamProcessor (const data::share::StringKeyLabelCI& transferEncoding,
const data::share::StringKeyLabelCI& contentEncoding ) const
{
if(!transferEncoding && !contentEncoding) {
return &data::stream::StatelessDataTransferProcessor::INSTANCE;
}
if(contentEncoding && !m_contentDecoders) {
throw std::runtime_error("[oatpp::web::protocol::http::incoming::SimpleBodyDecoder::getStreamProcessor()]: "
"Error. Server content decoders are NOT configured.");
}
std::vector<base::ObjectHandle<data::buffer::Processor>> processors;
if(transferEncoding) {
if(transferEncoding != Header::Value::TRANSFER_ENCODING_CHUNKED) {
throw std::runtime_error("[oatpp::web::protocol::http::incoming::SimpleBodyDecoder::getStreamProcessor()]: "
"Error. Unsupported Transfer-Encoding. '" + transferEncoding.std_str() + "'.");
}
processors.push_back(std::make_shared<http::encoding::DecoderChunked>());
}
if(contentEncoding) {
auto provider = m_contentDecoders->get(contentEncoding);
if(!provider) {
throw std::runtime_error("[oatpp::web::protocol::http::incoming::SimpleBodyDecoder::getStreamProcessor()]: "
"Error. Unsupported Content-Encoding. '" + contentEncoding.std_str() + "'.");
}
processors.push_back(provider->getProcessor());
}
if(processors.size() > 1) {
return std::make_shared<data::buffer::ProcessingPipeline>(processors);
} else if(processors.size() == 1) {
return processors[0].getPtr();
}
return &data::stream::StatelessDataTransferProcessor::INSTANCE;
}
void SimpleBodyDecoder::handleExpectHeader(const Headers& headers, data::stream::IOStream* connection) const {
auto expect = headers.getAsMemoryLabel<data::share::StringKeyLabelCI>(Header::EXPECT);
if(expect == Header::Value::EXPECT_100_CONTINUE) {
auto res = connection->writeExactSizeDataSimple(RESPONSE_100_CONTINUE.data(), RESPONSE_100_CONTINUE.size());
if(res != RESPONSE_100_CONTINUE.size()) {
throw std::runtime_error("[oatpp::web::protocol::http::incoming::SimpleBodyDecoder::handleExpectHeader()]: "
"Error. Unable to send 100-continue response.");
}
}
}
oatpp::async::CoroutineStarter SimpleBodyDecoder::handleExpectHeaderAsync(const Headers& headers,
const std::shared_ptr<data::stream::IOStream>& connection) const
{
auto expect = headers.getAsMemoryLabel<data::share::StringKeyLabelCI>(Header::EXPECT);
if(expect == Header::Value::EXPECT_100_CONTINUE) {
return connection->writeExactSizeDataAsync(RESPONSE_100_CONTINUE.data(), RESPONSE_100_CONTINUE.size());
}
return nullptr;
}
void SimpleBodyDecoder::decode(const Headers& headers,
data::stream::InputStream* bodyStream,
data::stream::WriteCallback* writeCallback,
data::stream::IOStream* connection) const
{
handleExpectHeader(headers, connection);
auto transferEncoding = headers.getAsMemoryLabel<data::share::StringKeyLabelCI>(Header::TRANSFER_ENCODING);
if(transferEncoding) {
auto contentEncoding = headers.getAsMemoryLabel<data::share::StringKeyLabelCI>(Header::CONTENT_ENCODING);
auto processor = getStreamProcessor(transferEncoding, contentEncoding);
data::buffer::IOBuffer buffer;
data::stream::transfer(bodyStream, writeCallback, 0 /* read until error */, buffer.getData(), buffer.getSize(), processor);
} else {
auto contentLengthStr = headers.getAsMemoryLabel<data::share::StringKeyLabel>(Header::CONTENT_LENGTH);
if(contentLengthStr) {
bool success;
auto contentLength = utils::conversion::strToInt64(contentLengthStr.toString(), success);
if (success && contentLength > 0) {
auto contentEncoding = headers.getAsMemoryLabel<data::share::StringKeyLabelCI>(Header::CONTENT_ENCODING);
auto processor = getStreamProcessor(nullptr, contentEncoding);
data::buffer::IOBuffer buffer;
data::stream::transfer(bodyStream, writeCallback, contentLength, buffer.getData(), buffer.getSize(), processor);
}
} else {
auto connectionStr = headers.getAsMemoryLabel<data::share::StringKeyLabelCI>(Header::CONNECTION);
if(connectionStr && connectionStr == "close") {
auto contentEncoding = headers.getAsMemoryLabel<data::share::StringKeyLabelCI>(Header::CONTENT_ENCODING);
auto processor = getStreamProcessor(nullptr, contentEncoding);
data::buffer::IOBuffer buffer;
data::stream::transfer(bodyStream, writeCallback, 0 /* read until error */, buffer.getData(), buffer.getSize(), processor);
} else {
throw std::runtime_error("[oatpp::web::protocol::http::incoming::SimpleBodyDecoder::decode()]: Error. Invalid Request.");
}
}
}
}
async::CoroutineStarter SimpleBodyDecoder::decodeAsync(const Headers& headers,
const std::shared_ptr<data::stream::InputStream>& bodyStream,
const std::shared_ptr<data::stream::WriteCallback>& writeCallback,
const std::shared_ptr<data::stream::IOStream>& connection) const
{
auto pipeline = handleExpectHeaderAsync(headers, connection);
auto transferEncoding = headers.getAsMemoryLabel<data::share::StringKeyLabelCI>(Header::TRANSFER_ENCODING);
if(transferEncoding) {
auto contentEncoding = headers.getAsMemoryLabel<data::share::StringKeyLabelCI>(Header::CONTENT_ENCODING);
auto processor = getStreamProcessor(transferEncoding, contentEncoding);
auto buffer = data::buffer::IOBuffer::createShared();
return std::move(pipeline.next(data::stream::transferAsync(bodyStream, writeCallback, 0 /* read until error */, buffer, processor)));
} else {
auto contentLengthStr = headers.getAsMemoryLabel<data::share::StringKeyLabel>(Header::CONTENT_LENGTH);
if(contentLengthStr) {
bool success;
auto contentLength = utils::conversion::strToInt64(contentLengthStr.toString(), success);
if (success && contentLength > 0) {
auto contentEncoding = headers.getAsMemoryLabel<data::share::StringKeyLabelCI>(Header::CONTENT_ENCODING);
auto processor = getStreamProcessor(nullptr, contentEncoding);
auto buffer = data::buffer::IOBuffer::createShared();
return std::move(pipeline.next(data::stream::transferAsync(bodyStream, writeCallback, contentLength, buffer, processor)));
}
} else {
auto connectionStr = headers.getAsMemoryLabel<data::share::StringKeyLabelCI>(Header::CONNECTION);
if(connectionStr && connectionStr == "close") {
auto contentEncoding = headers.getAsMemoryLabel<data::share::StringKeyLabelCI>(Header::CONTENT_ENCODING);
auto processor = getStreamProcessor(nullptr, contentEncoding);
auto buffer = data::buffer::IOBuffer::createShared();
return std::move(pipeline.next(data::stream::transferAsync(bodyStream, writeCallback, 0 /* read until error */, buffer, processor)));
}
}
}
throw std::runtime_error("[oatpp::web::protocol::http::incoming::SimpleBodyDecoder::decodeAsync()]: Error. Invalid Request.");
}
}}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/incoming/SimpleBodyDecoder.cpp
|
C++
|
apache-2.0
| 8,977
|
/***************************************************************************
*
* 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_incoming_SimpleBodyDecoder_hpp
#define oatpp_web_protocol_http_incoming_SimpleBodyDecoder_hpp
#include "BodyDecoder.hpp"
#include "oatpp/web/protocol/http/encoding/ProviderCollection.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace incoming {
/**
* Default implementation of &id:oatpp::web::protocol::http::incoming::BodyDecoder;.
*/
class SimpleBodyDecoder : public BodyDecoder {
private:
static const std::string RESPONSE_100_CONTINUE;
private:
std::shared_ptr<encoding::ProviderCollection> m_contentDecoders;
private:
base::ObjectHandle<data::buffer::Processor> getStreamProcessor(const data::share::StringKeyLabelCI& transferEncoding,
const data::share::StringKeyLabelCI& contentEncoding) const;
void handleExpectHeader(const Headers& headers, data::stream::IOStream* connection) const;
oatpp::async::CoroutineStarter handleExpectHeaderAsync(const Headers& headers,
const std::shared_ptr<data::stream::IOStream>& connection) const;
public:
/**
* Constructor.
* @param decoders - collection content decoders.
*/
SimpleBodyDecoder(const std::shared_ptr<encoding::ProviderCollection>& contentDecoders = nullptr);
/**
* Decode bodyStream and write decoded data to toStream.
* @param headers - Headers map. &id:oatpp::web::protocol::http::Headers;.
* @param bodyStream - pointer to &id:oatpp::data::stream::InputStream;.
* @param writeCallback - &id:oatpp::data::stream::WriteCallback;.
* @param connection
*/
void decode(const Headers& headers,
data::stream::InputStream* bodyStream,
data::stream::WriteCallback* writeCallback,
data::stream::IOStream* connection) const override;
/**
* Same as &l:SimpleBodyDecoder::decode (); but Async.
* @param headers - Headers map. &id:oatpp::web::protocol::http::Headers;.
* @param bodyStream - `std::shared_ptr` to &id:oatpp::data::stream::InputStream;.
* @param writeCallback - `std::shared_ptr` to &id:oatpp::data::stream::WriteCallback;.
* @param connection
* @return - &id:oatpp::async::CoroutineStarter;.
*/
oatpp::async::CoroutineStarter decodeAsync(const Headers& headers,
const std::shared_ptr<data::stream::InputStream>& bodyStream,
const std::shared_ptr<data::stream::WriteCallback>& writeCallback,
const std::shared_ptr<data::stream::IOStream>& connection) const override;
};
}}}}}
#endif /* oatpp_web_protocol_http_incoming_SimpleBodyDecoder_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/incoming/SimpleBodyDecoder.hpp
|
C++
|
apache-2.0
| 3,754
|
/***************************************************************************
*
* 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 "Body.hpp"
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/outgoing/Body.cpp
|
C++
|
apache-2.0
| 1,016
|
/***************************************************************************
*
* 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_Body_hpp
#define oatpp_web_protocol_http_outgoing_Body_hpp
#include "oatpp/web/protocol/http/Http.hpp"
#include "oatpp/core/data/stream/Stream.hpp"
#include "oatpp/core/async/Coroutine.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace outgoing {
/**
* Abstract http outgoing body.
* You may extend this class in order to implement custom body transferring functionality.
*/
class Body : public data::stream::ReadCallback {
protected:
typedef http::Headers Headers;
public:
/**
* Virtual destructor.
*/
virtual ~Body() = default;
///////////////////////////
// From the ReadCallback //
//
//virtual v_io_size read(void *buffer, v_buff_size count, async::Action& action) = 0;
/**
* Declare headers describing body.
* **Note:** Do NOT declare the `Content-Length` header.
* @param headers - &id:oatpp::web::protocol::http::Headers;.
*/
virtual void declareHeaders(Headers& headers) = 0;
/**
* Pointer to the body known data.
* @return - `p_char8`.
*/
virtual p_char8 getKnownData() = 0;
/**
* Should return the known size of the body (if known).
* If body size is unknown then should return -1.
* @return - &id:oatpp::v_io_size;.
*/
virtual v_int64 getKnownSize() = 0;
};
}}}}}
#endif /* oatpp_web_protocol_http_outgoing_Body_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/outgoing/Body.hpp
|
C++
|
apache-2.0
| 2,388
|
/***************************************************************************
*
* 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 "BufferBody.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace outgoing {
BufferBody::BufferBody(const oatpp::String &buffer, const data::share::StringKeyLabel &contentType)
: m_buffer(buffer ? buffer : "")
, m_contentType(contentType)
, m_inlineData((void*) m_buffer->data(), m_buffer->size())
{}
std::shared_ptr<BufferBody> BufferBody::createShared(const oatpp::String &buffer,
const data::share::StringKeyLabel &contentType) {
return std::make_shared<BufferBody>(buffer, contentType);
}
v_io_size BufferBody::read(void *buffer, v_buff_size count, async::Action &action) {
(void) action;
v_buff_size desiredToRead = m_inlineData.bytesLeft;
if (desiredToRead > 0) {
if (desiredToRead > count) {
desiredToRead = count;
}
std::memcpy(buffer, m_inlineData.currBufferPtr, desiredToRead);
m_inlineData.inc(desiredToRead);
return desiredToRead;
}
return 0;
}
void BufferBody::declareHeaders(Headers &headers) {
if (m_contentType) {
headers.putIfNotExists(Header::CONTENT_TYPE, m_contentType);
}
}
p_char8 BufferBody::getKnownData() {
return (p_char8) m_buffer->data();
}
v_int64 BufferBody::getKnownSize() {
return m_buffer->size();
}
}}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/outgoing/BufferBody.cpp
|
C++
|
apache-2.0
| 2,303
|
/***************************************************************************
*
* 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_BufferBody_hpp
#define oatpp_web_protocol_http_outgoing_BufferBody_hpp
#include "./Body.hpp"
#include "oatpp/web/protocol/http/Http.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace outgoing {
/**
* Implementation of &id:oatpp::web::protocol::http::outgoing::Body; class.
* Implements functionality to use &id::oatpp::String; as data source for http body.
*/
class BufferBody : public oatpp::base::Countable, public Body {
private:
oatpp::String m_buffer;
oatpp::data::share::StringKeyLabel m_contentType;
data::buffer::InlineReadData m_inlineData;
public:
BufferBody(const oatpp::String& buffer, const data::share::StringKeyLabel& contentType);
public:
/**
* Create shared BufferBody.
* @param buffer - &id:oatpp::String;.
* @param contentType - type of the content.
* @return - `std::shared_ptr` to BufferBody.
*/
static std::shared_ptr<BufferBody> createShared(const oatpp::String& buffer,
const data::share::StringKeyLabel& contentType = data::share::StringKeyLabel());
/**
* Read operation callback.
* @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;
/**
* Declare `Content-Length` header.
* @param headers - &id:oatpp::web::protocol::http::Headers;.
*/
void declareHeaders(Headers& headers) override;
/**
* Pointer to the body known data.
* @return - `p_char8`.
*/
p_char8 getKnownData() override;
/**
* Return known size of the body.
* @return - `v_buff_size`.
*/
v_int64 getKnownSize() override;
};
}}}}}
#endif /* oatpp_web_protocol_http_outgoing_BufferBody_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/outgoing/BufferBody.hpp
|
C++
|
apache-2.0
| 3,064
|
/***************************************************************************
*
* 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 "MultipartBody.hpp"
#include "oatpp/core/data/stream/BufferStream.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace outgoing {
v_io_size MultipartBody::readBody(void *buffer, v_buff_size count, async::Action& action) {
const auto& stream = m_iterator.getPartInputStream();
if(!stream) {
OATPP_LOGW("[oatpp::web::protocol::http::outgoing::MultipartBody::MultipartReadCallback::readBody()]", "Warning. Part has no input stream.");
return 0;
}
return stream->read(buffer, count, action);
}
v_io_size MultipartBody::incPart(async::Action& action) {
m_iterator.inc(action);
if(action.isNone()) {
return 0;
}
return oatpp::IOError::RETRY_READ;
}
v_io_size MultipartBody::read(void *buffer, v_buff_size count, async::Action& action) {
if(m_state == STATE_FINISHED) {
return 0;
}
m_iterator.init(action);
if(!action.isNone()) {
return 0;
}
p_char8 currBufferPtr = (p_char8) buffer;
v_io_size bytesLeft = count;
v_io_size res = 0;
while(bytesLeft > 0 && action.isNone()) {
switch (m_state) {
case STATE_BOUNDARY:
res = readBoundary(m_multipart, m_iterator, m_readStream, currBufferPtr, bytesLeft);
break;
case STATE_HEADERS:
res = readHeaders(m_multipart, m_iterator, m_readStream, currBufferPtr, bytesLeft);
break;
case STATE_BODY:
res = readBody(currBufferPtr, bytesLeft, action);
break;
case STATE_INC_PART:
res = incPart(action);
break;
default:
OATPP_LOGE("[oatpp::web::protocol::http::outgoing::MultipartBody::MultipartReadCallback::read()]", "Error. Invalid state %d", m_state);
return 0;
}
if(res > 0) {
currBufferPtr = &currBufferPtr[res];
bytesLeft -= res;
} else if(res == 0) {
if(m_state == STATE_BOUNDARY && m_iterator.finished()) {
m_state = STATE_FINISHED;
break;
}
m_state += 1;
if(m_state == STATE_INC_PART && m_flushParts && bytesLeft < count) {
break;
}
if(m_state == STATE_ROUND) {
m_state = 0;
}
} else if(action.isNone()) {
OATPP_LOGE("[oatpp::web::protocol::http::outgoing::MultipartBody::MultipartReadCallback::read()]", "Error. Invalid read result %d. State=%d", res, m_state);
return 0;
}
}
return count - bytesLeft;
}
v_io_size MultipartBody::readBoundary(const std::shared_ptr<Multipart>& multipart,
PartIterator& iterator,
data::stream::BufferInputStream& readStream,
void *buffer,
v_buff_size count)
{
if (!readStream.getDataMemoryHandle()) {
oatpp::String boundary;
if (iterator.finished()) {
boundary = "\r\n--" + multipart->getBoundary() + "--\r\n";
} else if (iterator.isFirst()) {
boundary = "--" + multipart->getBoundary() + "\r\n";
} else {
boundary = "\r\n--" + multipart->getBoundary() + "\r\n";
}
readStream.reset(boundary.getPtr(), (p_char8) boundary->data(), boundary->size());
}
auto res = readStream.readSimple(buffer, count);
if(res == 0) {
readStream.reset();
}
return res;
}
v_io_size MultipartBody::readHeaders(const std::shared_ptr<Multipart>& multipart,
PartIterator& iterator,
data::stream::BufferInputStream& readStream,
void *buffer,
v_buff_size count)
{
(void) multipart;
if (!readStream.getDataMemoryHandle()) {
oatpp::data::stream::BufferOutputStream stream;
const auto& part = iterator.get();
http::Utils::writeHeaders(part->getHeaders(), &stream);
stream.writeSimple("\r\n", 2);
auto str = stream.toString();
readStream.reset(str.getPtr(), (p_char8) str->data(), str->size());
}
auto res = readStream.readSimple(buffer, count);
if(res == 0) {
readStream.reset();
}
return res;
}
MultipartBody::MultipartBody(const std::shared_ptr<Multipart>& multipart, const oatpp::String& contentType, bool flushParts)
: m_multipart(multipart)
, m_contentType(contentType)
, m_iterator(multipart)
, m_state(STATE_BOUNDARY)
, m_readStream(nullptr, nullptr, 0)
, m_flushParts(flushParts)
{}
void MultipartBody::declareHeaders(Headers& headers) {
headers.put_LockFree(oatpp::web::protocol::http::Header::CONTENT_TYPE, m_contentType + "; boundary=" + m_multipart->getBoundary());
}
p_char8 MultipartBody::getKnownData() {
return nullptr;
}
v_int64 MultipartBody::getKnownSize() {
return -1;
}
}}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/outgoing/MultipartBody.cpp
|
C++
|
apache-2.0
| 5,720
|
/***************************************************************************
*
* 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_MultipartBody_hpp
#define oatpp_web_protocol_http_outgoing_MultipartBody_hpp
#include "./Body.hpp"
#include "oatpp/web/mime/multipart/Multipart.hpp"
#include "oatpp/core/data/stream/BufferStream.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace outgoing {
class MultipartBody : public oatpp::base::Countable, public Body {
public:
/**
* Convenience typedef for &id:oatpp::web::mime::multipart::Multipart;.
*/
typedef oatpp::web::mime::multipart::Multipart Multipart;
/**
* Convenience typedef for &id:oatpp::web::mime::multipart::Part;.
*/
typedef oatpp::web::mime::multipart::Part Part;
private:
/*
* Convenience typedef for &id:oatpp::data::stream::ReadCallback;.
*/
typedef oatpp::data::stream::ReadCallback ReadCallback;
private:
static constexpr v_int32 STATE_BOUNDARY = 0;
static constexpr v_int32 STATE_HEADERS = 1;
static constexpr v_int32 STATE_BODY = 2;
static constexpr v_int32 STATE_INC_PART = 3;
static constexpr v_int32 STATE_ROUND = 4; // number of possible states. used to round the state.
static constexpr v_int32 STATE_FINISHED = 5;
private:
class PartIterator {
private:
std::shared_ptr<Multipart> m_multipart;
std::shared_ptr<Part> m_part;
std::shared_ptr<data::stream::InputStream> m_partInputStream;
bool m_isFirst;
bool m_initialized;
public:
PartIterator(const std::shared_ptr<Multipart>& multipart)
: m_multipart(multipart)
, m_part(nullptr)
, m_partInputStream(nullptr)
, m_isFirst(true)
, m_initialized(false)
{}
void init(async::Action& action) {
if(!m_initialized) {
m_part = m_multipart->readNextPart(action);
m_partInputStream = nullptr;
if(m_part) {
auto payload = m_part->getPayload();
if (payload) {
m_partInputStream = payload->openInputStream();
}
}
m_initialized = true;
}
}
void inc(async::Action& action) {
m_part = m_multipart->readNextPart(action);
m_partInputStream = nullptr;
if(m_part) {
auto payload = m_part->getPayload();
if (payload) {
m_partInputStream = payload->openInputStream();
}
}
m_isFirst = false;
}
bool finished() {
return m_part == nullptr;
}
bool isFirst() {
return m_isFirst;
}
std::shared_ptr<Part> get() {
return m_part;
}
std::shared_ptr<data::stream::InputStream> getPartInputStream() {
return m_partInputStream;
}
};
private:
static v_io_size readBoundary(const std::shared_ptr<Multipart>& multipart,
PartIterator& iterator,
data::stream::BufferInputStream& readStream,
void *buffer,
v_buff_size count);
static v_io_size readHeaders(const std::shared_ptr<Multipart>& multipart,
PartIterator& iterator,
data::stream::BufferInputStream& readStream,
void *buffer,
v_buff_size count);
private:
std::shared_ptr<Multipart> m_multipart;
oatpp::String m_contentType;
private:
PartIterator m_iterator;
v_int32 m_state;
oatpp::data::stream::BufferInputStream m_readStream;
bool m_flushParts;
private:
v_io_size readBody(void *buffer, v_buff_size count, async::Action& action);
v_io_size incPart(async::Action& action);
public:
/**
* Constructor.
* @param multipart - multipart object.
* @param contentType - type of the multipart. Default value = `"multipart/form-data"`.
* @param flushParts - flush data part by part.
*/
MultipartBody(const std::shared_ptr<Multipart>& multipart,
const oatpp::String& contentType = "multipart/form-data",
bool flushParts = false);
/**
* Read operation callback.
* @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;
/**
* Declare `Transfer-Encoding: chunked`, `Content-Type: multipart/<type>` header.
* @param headers - &id:oatpp::web::protocol::http::Headers;.
*/
void declareHeaders(Headers& headers) override;
/**
* Pointer to the body known data.
* @return - `p_char8`.
*/
p_char8 getKnownData() override;
/**
* Always returns `-1` - as body size is unknown.
* @return - `-1`. `v_buff_size`.
*/
v_int64 getKnownSize() override;
};
}}}}}
#endif // oatpp_web_protocol_http_outgoing_MultipartBody_hpp
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/outgoing/MultipartBody.hpp
|
C++
|
apache-2.0
| 5,977
|
/***************************************************************************
*
* 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 "Request.hpp"
#include "oatpp/web/protocol/http/encoding/Chunked.hpp"
#include "oatpp/core/data/stream/BufferStream.hpp"
#include "oatpp/core/data/buffer/IOBuffer.hpp"
#include "oatpp/core/utils/ConversionUtils.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace outgoing {
Request::Request(const oatpp::data::share::StringKeyLabel& method,
const oatpp::data::share::StringKeyLabel& path,
const Headers& headers,
const std::shared_ptr<Body>& body)
: m_method(method)
, m_path(path)
, m_headers(headers)
, m_body(body)
{}
std::shared_ptr<Request> Request::createShared(const oatpp::data::share::StringKeyLabel& method,
const oatpp::data::share::StringKeyLabel& path,
const Headers& headers,
const std::shared_ptr<Body>& body) {
return std::make_shared<Request>(method, path, headers, body);
}
const oatpp::data::share::StringKeyLabel& Request::getMethod() const {
return m_method;
}
const oatpp::data::share::StringKeyLabel& Request::getPath() const {
return m_path;
}
protocol::http::Headers& Request::getHeaders() {
return m_headers;
}
void Request::putHeader(const oatpp::String& key, const oatpp::String& value) {
m_headers.put(key, value);
}
bool Request::putHeaderIfNotExists(const oatpp::String& key, const oatpp::String& value) {
return m_headers.putIfNotExists(key, value);
}
bool Request::putOrReplaceHeader(const String &key, const String &value) {
return m_headers.putOrReplace(key, value);
}
bool Request::putOrReplaceHeader_Unsafe(const data::share::StringKeyLabelCI& key,
const data::share::StringKeyLabel &value) {
return m_headers.putOrReplace(key, value);
}
void Request::putHeader_Unsafe(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value) {
m_headers.put(key, value);
}
bool Request::putHeaderIfNotExists_Unsafe(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value) {
return m_headers.putIfNotExists(key, value);
}
oatpp::String Request::getHeader(const oatpp::data::share::StringKeyLabelCI& headerName) const{
return m_headers.get(headerName);
}
void Request::putBundleData(const oatpp::String& key, const oatpp::Void& polymorph) {
m_bundle.put(key, polymorph);
}
const data::Bundle& Request::getBundle() const {
return m_bundle;
}
std::shared_ptr<Body> Request::getBody() {
return m_body;
}
void Request::send(data::stream::OutputStream* stream){
v_buff_size bodySize = -1;
if(m_body){
m_body->declareHeaders(m_headers);
bodySize = m_body->getKnownSize();
if(bodySize >= 0) {
m_headers.put_LockFree(Header::CONTENT_LENGTH, utils::conversion::int64ToStr(bodySize));
} else {
m_headers.put_LockFree(Header::TRANSFER_ENCODING, Header::Value::TRANSFER_ENCODING_CHUNKED);
}
} else {
m_headers.put_LockFree(Header::CONTENT_LENGTH, "0");
}
oatpp::data::stream::BufferOutputStream buffer(2048);
buffer.writeSimple(m_method.getData(), m_method.getSize());
buffer.writeSimple(" /", 2);
buffer.writeSimple(m_path.getData(), m_path.getSize());
buffer.writeSimple(" ", 1);
buffer.writeSimple("HTTP/1.1", 8);
buffer.writeSimple("\r\n", 2);
http::Utils::writeHeaders(m_headers, &buffer);
buffer.writeSimple("\r\n", 2);
if(m_body) {
if(bodySize >= 0) {
if(bodySize + buffer.getCurrentPosition() < buffer.getCapacity()) {
buffer.writeSimple(m_body->getKnownData(), bodySize);
buffer.flushToStream(stream);
} else {
buffer.flushToStream(stream);
stream->writeExactSizeDataSimple(m_body->getKnownData(), bodySize);
}
} else {
buffer.flushToStream(stream);
http::encoding::EncoderChunked chunkedEncoder;
/* Reuse headers buffer */
buffer.setCurrentPosition(0);
data::stream::transfer(m_body, stream, 0, buffer.getData(), buffer.getCapacity(), &chunkedEncoder);
}
} else {
buffer.flushToStream(stream);
}
}
oatpp::async::CoroutineStarter Request::sendAsync(std::shared_ptr<Request> _this,
const std::shared_ptr<data::stream::OutputStream>& stream)
{
class SendAsyncCoroutine : public oatpp::async::Coroutine<SendAsyncCoroutine> {
private:
std::shared_ptr<Request> m_this;
std::shared_ptr<data::stream::OutputStream> m_stream;
std::shared_ptr<oatpp::data::stream::BufferOutputStream> m_headersWriteBuffer;
public:
SendAsyncCoroutine(std::shared_ptr<Request> request,
const std::shared_ptr<data::stream::OutputStream>& stream)
: m_this(std::move(request))
, m_stream(stream)
, m_headersWriteBuffer(std::make_shared<oatpp::data::stream::BufferOutputStream>())
{}
Action act() override {
v_buff_size bodySize = -1;
if(m_this->m_body){
m_this->m_body->declareHeaders(m_this->m_headers);
bodySize = m_this->m_body->getKnownSize();
if(bodySize >= 0) {
m_this->m_headers.put_LockFree(Header::CONTENT_LENGTH, utils::conversion::int64ToStr(bodySize));
} else {
m_this->m_headers.put_LockFree(Header::TRANSFER_ENCODING, Header::Value::TRANSFER_ENCODING_CHUNKED);
}
} else {
m_this->m_headers.put_LockFree(Header::CONTENT_LENGTH, "0");
}
m_headersWriteBuffer->writeSimple(m_this->m_method.getData(), m_this->m_method.getSize());
m_headersWriteBuffer->writeSimple(" /", 2);
m_headersWriteBuffer->writeSimple(m_this->m_path.getData(), m_this->m_path.getSize());
m_headersWriteBuffer->writeSimple(" ", 1);
m_headersWriteBuffer->writeSimple("HTTP/1.1", 8);
m_headersWriteBuffer->writeSimple("\r\n", 2);
http::Utils::writeHeaders(m_this->m_headers, m_headersWriteBuffer.get());
m_headersWriteBuffer->writeSimple("\r\n", 2);
if(m_this->m_body) {
if(bodySize >= 0) {
if(bodySize + m_headersWriteBuffer->getCurrentPosition() < m_headersWriteBuffer->getCapacity()) {
m_headersWriteBuffer->writeSimple(m_this->m_body->getKnownData(), bodySize);
return oatpp::data::stream::BufferOutputStream::flushToStreamAsync(m_headersWriteBuffer, m_stream)
.next(finish());
} else {
return oatpp::data::stream::BufferOutputStream::flushToStreamAsync(m_headersWriteBuffer, m_stream)
.next(m_stream->writeExactSizeDataAsync(m_this->m_body->getKnownData(), bodySize))
.next(finish());
}
} else {
auto chunkedEncoder = std::make_shared<http::encoding::EncoderChunked>();
return oatpp::data::stream::BufferOutputStream::flushToStreamAsync(m_headersWriteBuffer, m_stream)
.next(data::stream::transferAsync(m_this->m_body, m_stream, 0, data::buffer::IOBuffer::createShared(), chunkedEncoder))
.next(finish());
}
} else {
return oatpp::data::stream::BufferOutputStream::flushToStreamAsync(m_headersWriteBuffer, m_stream)
.next(finish());
}
}
};
return SendAsyncCoroutine::start(std::move(_this), stream);
}
}}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/outgoing/Request.cpp
|
C++
|
apache-2.0
| 8,429
|
/***************************************************************************
*
* 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_Request_hpp
#define oatpp_web_protocol_http_outgoing_Request_hpp
#include "oatpp/web/protocol/http/outgoing/Body.hpp"
#include "oatpp/web/protocol/http/Http.hpp"
#include "oatpp/core/data/Bundle.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace outgoing {
/**
* Class http::outgoing::Request AKA OutgoingRequest represents client's outgoing request to server.
*/
class Request : public oatpp::base::Countable {
public:
/**
* Convenience typedef for &id:oatpp::web::protocol::http::Headers;.
*/
typedef protocol::http::Headers Headers;
private:
oatpp::data::share::StringKeyLabel m_method;
oatpp::data::share::StringKeyLabel m_path;
Headers m_headers;
std::shared_ptr<Body> m_body;
data::Bundle m_bundle;
public:
/**
* Constructor.
* @param method - http method. &id:oatpp::data::share::StringKeyLabel;.
* @param path - path to resource. &id:oatpp::data::share::StringKeyLabel;.
* @param headers - &l:Request::Headers;.
* @param body - `std::shared_ptr` to &id:oatpp::web::protocol::http::outgoing::Body;.
*/
Request(const oatpp::data::share::StringKeyLabel& method,
const oatpp::data::share::StringKeyLabel& path,
const Headers& headers,
const std::shared_ptr<Body>& body);
public:
/**
* Create shared Request.
* @param method - http method. &id:oatpp::data::share::StringKeyLabel;.
* @param path - path to resource. &id:oatpp::data::share::StringKeyLabel;.
* @param headers - &l:Request::Headers;.
* @param body - `std::shared_ptr` to &id:oatpp::web::protocol::http::outgoing::Body;.
* @return - `std::shared_ptr` to Request.
*/
static std::shared_ptr<Request> createShared(const oatpp::data::share::StringKeyLabel& method,
const oatpp::data::share::StringKeyLabel& path,
const Headers& headers,
const std::shared_ptr<Body>& body);
/**
* Get http method.
* @return - http method. &id:oatpp::data::share::StringKeyLabel;.
*/
const oatpp::data::share::StringKeyLabel& getMethod() const;
/**
* Get path to resource.
* @return - path to resource. &id:oatpp::data::share::StringKeyLabel;.
*/
const oatpp::data::share::StringKeyLabel& getPath() const;
/**
* Get headers map.
* @return - &l:Request::Headers;.
*/
Headers& getHeaders();
/**
* Add http header.
* @param key - &id:oatpp::String;.
* @param value - &id:oatpp::String;.
*/
void putHeader(const oatpp::String& key, const oatpp::String& value);
/**
* Add http header if not already exists.
* @param key - &id:oatpp::String;.
* @param value - &id:oatpp::String;.
* @return - `true` if header was added.
*/
bool putHeaderIfNotExists(const oatpp::String& key, const oatpp::String& value);
/**
* Replaces or adds header.
* @param key - &id:oatpp::String;.
* @param value - &id:oatpp::String;.
* @return - `true` if header was replaces, `false` if header was added.
*/
bool putOrReplaceHeader(const oatpp::String& key, const oatpp::String& value);
/**
* Replaces or adds header.
* @param key - &id:oatpp::data::share::StringKeyLabelCI;.
* @param value - &id:oatpp::data::share::StringKeyLabel;.
* @return - `true` if header was replaces, `false` if header was added.
*/
bool putOrReplaceHeader_Unsafe(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value);
/**
* Add http header.
* @param key - &id:oatpp::data::share::StringKeyLabelCI;.
* @param value - &id:oatpp::data::share::StringKeyLabel;.
*/
void putHeader_Unsafe(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value);
/**
* Add http header if not already exists.
* @param key - &id:oatpp::data::share::StringKeyLabelCI;.
* @param value - &id:oatpp::data::share::StringKeyLabel;.
* @return - `true` if header was added.
*/
bool putHeaderIfNotExists_Unsafe(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value);
/**
* Get header value
* @param headerName - &id:oatpp::data::share::StringKeyLabelCI;.
* @return - &id:oatpp::String;.
*/
oatpp::String getHeader(const oatpp::data::share::StringKeyLabelCI& headerName) const;
/**
* Put data to bundle.
* @param key
* @param polymorph
*/
void putBundleData(const oatpp::String& key, const oatpp::Void& polymorph);
/**
* Get data from bundle by key.
* @tparam WrapperType
* @param key
* @return
*/
template<typename WrapperType>
WrapperType getBundleData(const oatpp::String& key) const {
return m_bundle.template get<WrapperType>(key);
}
/**
* Get bundle object.
* @return
*/
const data::Bundle& getBundle() const;
/**
* Get http body.
* @return - &id:oatpp::web::protocol::http::outgoing::Body;.
*/
std::shared_ptr<Body> getBody();
/**
* Write request to stream.
* @param stream - &id:oatpp::data::stream::OutputStream;.
*/
void send(data::stream::OutputStream* stream);
/**
* Write request to stream in asynchronous manner.
* @param _this
* @param stream - &id:oatpp::data::stream::OutputStream;.
* @return - &id:oatpp::async::CoroutineStarter;.
*/
static oatpp::async::CoroutineStarter sendAsync(std::shared_ptr<Request> _this,
const std::shared_ptr<data::stream::OutputStream>& stream);
};
}}}}}
#endif /* oatpp_web_protocol_http_outgoing_Request_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/outgoing/Request.hpp
|
C++
|
apache-2.0
| 6,697
|
/***************************************************************************
*
* 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 "./Response.hpp"
#include "oatpp/web/protocol/http/encoding/Chunked.hpp"
#include "oatpp/core/utils/ConversionUtils.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace outgoing {
Response::Response(const Status& status,
const std::shared_ptr<Body>& body)
: m_status(status)
, m_body(body)
{}
std::shared_ptr<Response> Response::createShared(const Status& status,
const std::shared_ptr<Body>& body) {
return std::make_shared<Response>(status, body);
}
const Status& Response::getStatus() const {
return m_status;
}
protocol::http::Headers& Response::getHeaders() {
return m_headers;
}
std::shared_ptr<Body> Response::getBody() const {
return m_body;
}
void Response::putHeader(const oatpp::String& key, const oatpp::String& value) {
m_headers.put(key, value);
}
bool Response::putHeaderIfNotExists(const oatpp::String& key, const oatpp::String& value) {
return m_headers.putIfNotExists(key, value);
}
bool Response::putOrReplaceHeader(const String &key, const String &value) {
return m_headers.putOrReplace(key, value);
}
bool Response::putOrReplaceHeader_Unsafe(const data::share::StringKeyLabelCI& key,
const data::share::StringKeyLabel &value) {
return m_headers.putOrReplace(key, value);
}
void Response::putHeader_Unsafe(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value) {
m_headers.put(key, value);
}
bool Response::putHeaderIfNotExists_Unsafe(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value) {
return m_headers.putIfNotExists(key, value);
}
oatpp::String Response::getHeader(const oatpp::data::share::StringKeyLabelCI& headerName) const {
return m_headers.get(headerName);
}
void Response::putBundleData(const oatpp::String& key, const oatpp::Void& polymorph) {
m_bundle.put(key, polymorph);
}
const data::Bundle& Response::getBundle() const {
return m_bundle;
}
void Response::setConnectionUpgradeHandler(const std::shared_ptr<oatpp::network::ConnectionHandler>& handler) {
m_connectionUpgradeHandler = handler;
}
std::shared_ptr<oatpp::network::ConnectionHandler> Response::getConnectionUpgradeHandler() {
return m_connectionUpgradeHandler;
}
void Response::setConnectionUpgradeParameters(const std::shared_ptr<const ConnectionHandler::ParameterMap>& parameters) {
m_connectionUpgradeParameters = parameters;
}
std::shared_ptr<const Response::ConnectionHandler::ParameterMap> Response::getConnectionUpgradeParameters() {
return m_connectionUpgradeParameters;
}
void Response::send(data::stream::OutputStream* stream,
data::stream::BufferOutputStream* headersWriteBuffer,
http::encoding::EncoderProvider* contentEncoderProvider)
{
v_int64 bodySize = -1;
if(m_body){
m_body->declareHeaders(m_headers);
if(contentEncoderProvider == nullptr) {
bodySize = m_body->getKnownSize();
if (bodySize >= 0) {
m_headers.put_LockFree(Header::CONTENT_LENGTH, utils::conversion::int64ToStr(bodySize));
} else {
m_headers.put_LockFree(Header::TRANSFER_ENCODING, Header::Value::TRANSFER_ENCODING_CHUNKED);
}
} else {
m_headers.put_LockFree(Header::TRANSFER_ENCODING, Header::Value::TRANSFER_ENCODING_CHUNKED);
m_headers.put_LockFree(Header::CONTENT_ENCODING, contentEncoderProvider->getEncodingName());
}
} else {
m_headers.put_LockFree(Header::CONTENT_LENGTH, "0");
}
headersWriteBuffer->setCurrentPosition(0);
headersWriteBuffer->writeSimple("HTTP/1.1 ", 9);
headersWriteBuffer->writeAsString(m_status.code);
headersWriteBuffer->writeSimple(" ", 1);
headersWriteBuffer->writeSimple(m_status.description);
headersWriteBuffer->writeSimple("\r\n", 2);
http::Utils::writeHeaders(m_headers, headersWriteBuffer);
headersWriteBuffer->writeSimple("\r\n", 2);
if(m_body) {
if(contentEncoderProvider == nullptr) {
if (bodySize >= 0) {
if(m_body->getKnownData() == nullptr) {
headersWriteBuffer->flushToStream(stream);
/* Reuse headers buffer */
/* Transfer without chunked encoder */
data::stream::transfer(m_body, stream, 0, headersWriteBuffer->getData(), headersWriteBuffer->getCapacity());
} else {
if (bodySize + headersWriteBuffer->getCurrentPosition() < headersWriteBuffer->getCapacity()) {
headersWriteBuffer->writeSimple(m_body->getKnownData(), bodySize);
headersWriteBuffer->flushToStream(stream);
} else {
headersWriteBuffer->flushToStream(stream);
stream->writeExactSizeDataSimple(m_body->getKnownData(), bodySize);
}
}
} else {
headersWriteBuffer->flushToStream(stream);
http::encoding::EncoderChunked chunkedEncoder;
/* Reuse headers buffer */
data::stream::transfer(m_body, stream, 0, headersWriteBuffer->getData(), headersWriteBuffer->getCapacity(), &chunkedEncoder);
}
} else {
headersWriteBuffer->flushToStream(stream);
http::encoding::EncoderChunked chunkedEncoder;
auto contentEncoder = contentEncoderProvider->getProcessor();
data::buffer::ProcessingPipeline pipeline({
contentEncoder,
&chunkedEncoder
});
/* Reuse headers buffer */
data::stream::transfer(m_body, stream, 0, headersWriteBuffer->getData(), headersWriteBuffer->getCapacity(), &pipeline);
}
} else {
headersWriteBuffer->flushToStream(stream);
}
}
oatpp::async::CoroutineStarter Response::sendAsync(const std::shared_ptr<Response>& _this,
const std::shared_ptr<data::stream::OutputStream>& stream,
const std::shared_ptr<oatpp::data::stream::BufferOutputStream>& headersWriteBuffer,
const std::shared_ptr<http::encoding::EncoderProvider>& contentEncoder)
{
class SendAsyncCoroutine : public oatpp::async::Coroutine<SendAsyncCoroutine> {
private:
std::shared_ptr<Response> m_this;
std::shared_ptr<data::stream::OutputStream> m_stream;
std::shared_ptr<oatpp::data::stream::BufferOutputStream> m_headersWriteBuffer;
std::shared_ptr<http::encoding::EncoderProvider> m_contentEncoderProvider;
public:
SendAsyncCoroutine(const std::shared_ptr<Response>& _this,
const std::shared_ptr<data::stream::OutputStream>& stream,
const std::shared_ptr<oatpp::data::stream::BufferOutputStream>& headersWriteBuffer,
const std::shared_ptr<http::encoding::EncoderProvider>& contentEncoderProvider)
: m_this(_this)
, m_stream(stream)
, m_headersWriteBuffer(headersWriteBuffer)
, m_contentEncoderProvider(contentEncoderProvider)
{}
Action act() override {
v_buff_size bodySize = -1;
if(m_this->m_body){
m_this->m_body->declareHeaders(m_this->m_headers);
if(!m_contentEncoderProvider) {
bodySize = m_this->m_body->getKnownSize();
if (bodySize >= 0) {
m_this->m_headers.put_LockFree(Header::CONTENT_LENGTH, utils::conversion::int64ToStr(bodySize));
} else {
m_this->m_headers.put_LockFree(Header::TRANSFER_ENCODING, Header::Value::TRANSFER_ENCODING_CHUNKED);
}
} else {
m_this->m_headers.put_LockFree(Header::TRANSFER_ENCODING, Header::Value::TRANSFER_ENCODING_CHUNKED);
m_this->m_headers.put_LockFree(Header::CONTENT_ENCODING, m_contentEncoderProvider->getEncodingName());
}
} else {
m_this->m_headers.put_LockFree(Header::CONTENT_LENGTH, "0");
}
m_headersWriteBuffer->setCurrentPosition(0);
m_headersWriteBuffer->writeSimple("HTTP/1.1 ", 9);
m_headersWriteBuffer->writeAsString(m_this->m_status.code);
m_headersWriteBuffer->writeSimple(" ", 1);
m_headersWriteBuffer->writeSimple(m_this->m_status.description);
m_headersWriteBuffer->writeSimple("\r\n", 2);
http::Utils::writeHeaders(m_this->m_headers, m_headersWriteBuffer.get());
m_headersWriteBuffer->writeSimple("\r\n", 2);
if(m_this->m_body) {
if(!m_contentEncoderProvider) {
if (bodySize >= 0) {
if (bodySize + m_headersWriteBuffer->getCurrentPosition() < m_headersWriteBuffer->getCapacity()) {
m_headersWriteBuffer->writeSimple(m_this->m_body->getKnownData(), bodySize);
return oatpp::data::stream::BufferOutputStream::flushToStreamAsync(m_headersWriteBuffer, m_stream)
.next(finish());
} else {
return oatpp::data::stream::BufferOutputStream::flushToStreamAsync(m_headersWriteBuffer, m_stream)
.next(m_stream->writeExactSizeDataAsync(m_this->m_body->getKnownData(), bodySize))
.next(finish());
}
} else {
auto chunkedEncoder = std::make_shared<http::encoding::EncoderChunked>();
return oatpp::data::stream::BufferOutputStream::flushToStreamAsync(m_headersWriteBuffer, m_stream)
.next(data::stream::transferAsync(m_this->m_body, m_stream, 0, data::buffer::IOBuffer::createShared(), chunkedEncoder))
.next(finish());
}
} else {
auto chunkedEncoder = std::make_shared<http::encoding::EncoderChunked>();
auto contentEncoder = m_contentEncoderProvider->getProcessor();
auto pipeline = std::shared_ptr<data::buffer::ProcessingPipeline>(new data::buffer::ProcessingPipeline({
contentEncoder,
chunkedEncoder
}));
return oatpp::data::stream::BufferOutputStream::flushToStreamAsync(m_headersWriteBuffer, m_stream)
.next(data::stream::transferAsync(m_this->m_body, m_stream, 0, data::buffer::IOBuffer::createShared(), pipeline)
. next(finish()));
}
} else {
return oatpp::data::stream::BufferOutputStream::flushToStreamAsync(m_headersWriteBuffer, m_stream)
.next(finish());
}
}
};
return SendAsyncCoroutine::start(_this, stream, headersWriteBuffer, contentEncoder);
}
}}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/outgoing/Response.cpp
|
C++
|
apache-2.0
| 11,390
|
/***************************************************************************
*
* 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_Response_hpp
#define oatpp_web_protocol_http_outgoing_Response_hpp
#include "oatpp/web/protocol/http/outgoing/Body.hpp"
#include "oatpp/web/protocol/http/encoding/EncoderProvider.hpp"
#include "oatpp/web/protocol/http/Http.hpp"
#include "oatpp/network/ConnectionHandler.hpp"
#include "oatpp/core/async/Coroutine.hpp"
#include "oatpp/core/data/stream/BufferStream.hpp"
#include "oatpp/core/data/Bundle.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace outgoing {
/**
* Class which stores information of outgoing http Response.
*/
class Response : public oatpp::base::Countable {
public:
/**
* Convenience typedef for Headers. <br>
* See &id:oatpp::web::protocol::http::Headers;
*/
typedef http::Headers Headers;
/**
* Convenience typedef for &id:oatpp::network::ConnectionHandler;.
*/
typedef oatpp::network::ConnectionHandler ConnectionHandler;
private:
Status m_status;
Headers m_headers;
std::shared_ptr<Body> m_body;
std::shared_ptr<ConnectionHandler> m_connectionUpgradeHandler;
std::shared_ptr<const ConnectionHandler::ParameterMap> m_connectionUpgradeParameters;
data::Bundle m_bundle;
public:
/**
* Constructor.
* @param status - http status.
* @param body - response body.
*/
Response(const Status& status, const std::shared_ptr<Body>& body);
public:
/**
* Create shared outgoing response with status and body.
* @param status - http status.
* @param body - response body.
* @return
*/
static std::shared_ptr<Response> createShared(const Status& status, const std::shared_ptr<Body>& body);
/**
* Get status.
* @return - http status.
*/
const Status& getStatus() const;
/**
* Get headers.
* @return - &id:oatpp::web::protocol::http::Headers;
*/
Headers& getHeaders();
/**
* Get body
* @return - &id:oatpp::web::protocol::http::outgoing::Body;
*/
std::shared_ptr<Body> getBody() const;
/**
* Add http header.
* @param key - &id:oatpp::String;.
* @param value - &id:oatpp::String;.
*/
void putHeader(const oatpp::String& key, const oatpp::String& value);
/**
* Add http header if not already exists.
* @param key - &id:oatpp::String;.
* @param value - &id:oatpp::String;.
* @return - `true` if header was added.
*/
bool putHeaderIfNotExists(const oatpp::String& key, const oatpp::String& value);
/**
* Replaces or adds header.
* @param key - &id:oatpp::String;.
* @param value - &id:oatpp::String;.
* @return - `true` if header was replaces, `false` if header was added.
*/
bool putOrReplaceHeader(const oatpp::String& key, const oatpp::String& value);
/**
* Replaces or adds header.
* @param key - &id:oatpp::data::share::StringKeyLabelCI;.
* @param value - &id:oatpp::data::share::StringKeyLabel;.
* @return - `true` if header was replaces, `false` if header was added.
*/
bool putOrReplaceHeader_Unsafe(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value);
/**
* Add http header.
* @param key - &id:oatpp::data::share::StringKeyLabelCI;.
* @param value - &id:oatpp::data::share::StringKeyLabel;.
*/
void putHeader_Unsafe(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value);
/**
* Add http header if not already exists.
* @param key - &id:oatpp::data::share::StringKeyLabelCI;.
* @param value - &id:oatpp::data::share::StringKeyLabel;.
* @return - `true` if header was added.
*/
bool putHeaderIfNotExists_Unsafe(const oatpp::data::share::StringKeyLabelCI& key, const oatpp::data::share::StringKeyLabel& value);
/**
* Get header value
* @param headerName - &id:oatpp::data::share::StringKeyLabelCI;.
* @return - &id:oatpp::String;.
*/
oatpp::String getHeader(const oatpp::data::share::StringKeyLabelCI& headerName) const;
/**
* Put data to bundle.
* @param key
* @param polymorph
*/
void putBundleData(const oatpp::String& key, const oatpp::Void& polymorph);
/**
* Get data from bundle by key.
* @tparam WrapperType
* @param key
* @return
*/
template<typename WrapperType>
WrapperType getBundleData(const oatpp::String& key) const {
return m_bundle.template get<WrapperType>(key);
}
/**
* Get bundle object.
* @return
*/
const data::Bundle& getBundle() const;
/**
* Set connection upgreade header. <br>
* Use it together with corresponding headers being set when Response is created as: <br>
* Response(&id:oatpp::web::protocol::http::Status::CODE_101;, nullptr);<br>
* @param handler - `std::shared_ptr` to &id:oatpp::network::ConnectionHandler;.
*/
void setConnectionUpgradeHandler(const std::shared_ptr<ConnectionHandler>& handler);
/**
* Get currently set connection upgrade handler.
* @return - `std::shared_ptr` to &id:oatpp::network::ConnectionHandler;.
*/
std::shared_ptr<ConnectionHandler> getConnectionUpgradeHandler();
/**
* Set connection upgrade parameters. <br>
* Use it to set additional parameters for upgraded connection handling. See &l:Response::setConnectionUpgradeHandler ();.
* @param parameters - `std::shared_ptr` to const &id:oatpp::network::ConnectionHandler::ParameterMap;.
*/
void setConnectionUpgradeParameters(const std::shared_ptr<const ConnectionHandler::ParameterMap>& parameters);
/**
* Get connection upgrade parameters.
* @return - `std::shared_ptr` to const &id:oatpp::network::ConnectionHandler::ParametersMap;.
*/
std::shared_ptr<const ConnectionHandler::ParameterMap> getConnectionUpgradeParameters();
/**
* Write this Response to stream.
* @param stream - pointer to &id:oatpp::data::stream::OutputStream;.
* @param headersWriteBuffer - pointer to &id:oatpp::data::stream::BufferOutputStream;.
* @param contentEncoder - pointer to &id:oatpp::web::protocol::http::encoding::EncoderProvider;.
*/
void send(data::stream::OutputStream* stream,
data::stream::BufferOutputStream* headersWriteBuffer,
http::encoding::EncoderProvider* contentEncoderProvider);
/**
* Same as &l:Response::send (); but async.
* @param _this - `this` response.
* @param stream - `std::shared_ptr` to &id:oatpp::data::stream::OutputStream;.
* @param headersWriteBuffer - `std::shared_ptr` to &id:oatpp::data::stream::BufferOutputStream;.
* @param contentEncoderProvider - `std::shared_ptr` to &id:oatpp::web::protocol::http::encoding::EncoderProvider;.
* @return - &id:oatpp::async::CoroutineStarter;.
*/
static oatpp::async::CoroutineStarter sendAsync(const std::shared_ptr<Response>& _this,
const std::shared_ptr<data::stream::OutputStream>& stream,
const std::shared_ptr<data::stream::BufferOutputStream>& headersWriteBuffer,
const std::shared_ptr<http::encoding::EncoderProvider>& contentEncoderProvider);
};
}}}}}
#endif /* oatpp_web_protocol_http_outgoing_Response_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/outgoing/Response.hpp
|
C++
|
apache-2.0
| 8,165
|
/***************************************************************************
*
* 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 "./ResponseFactory.hpp"
#include "./BufferBody.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace outgoing {
std::shared_ptr<Response>
ResponseFactory::createResponse(const Status& status) {
return Response::createShared(status, nullptr);
}
std::shared_ptr<Response>
ResponseFactory::createResponse(const Status& status, const oatpp::String& text) {
return Response::createShared(status, BufferBody::createShared(text));
}
std::shared_ptr<Response>
ResponseFactory::createResponse(const Status& status,
const oatpp::Void& dto,
const std::shared_ptr<data::mapping::ObjectMapper>& objectMapper) {
return Response::createShared(status, BufferBody::createShared(
objectMapper->writeToString(dto),
objectMapper->getInfo().http_content_type
));
}
}}}}}
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/outgoing/ResponseFactory.cpp
|
C++
|
apache-2.0
| 1,877
|
/***************************************************************************
*
* 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_ResponseFactory_hpp
#define oatpp_web_protocol_http_outgoing_ResponseFactory_hpp
#include "./Response.hpp"
#include "oatpp/core/data/mapping/ObjectMapper.hpp"
#include "oatpp/core/data/mapping/type/Type.hpp"
namespace oatpp { namespace web { namespace protocol { namespace http { namespace outgoing {
/**
* Helper class to create http outgoing responses (&id:oatpp::web::protocol::http::outgoing::Response).
*/
class ResponseFactory {
public:
/**
* Create &id:oatpp::web::protocol::http::outgoing::Response; without a &id:oatpp::web::protocol::http::outgoing::Body;.
* @param status - &id:oatpp::web::protocol::http::Status;.
* @return - `std::shared_ptr` to &id:oatpp::web::protocol::http::outgoing::Response;.
*/
static std::shared_ptr<Response> createResponse(const Status &status);
/**
* Create &id:oatpp::web::protocol::http::outgoing::Response; with &id:oatpp::web::protocol::http::outgoing::BufferBody;.
* @param status - &id:oatpp::web::protocol::http::Status;.
* @param text - &id:oatpp::String;.
* @return - `std::shared_ptr` to &id:oatpp::web::protocol::http::outgoing::Response;.
*/
static std::shared_ptr<Response> createResponse(const Status& status, const oatpp::String& text);
/**
* Create &id:oatpp::web::protocol::http::outgoing::Response; with &id:oatpp::web::protocol::http::outgoing::DtoBody;.
* @param status - &id:oatpp::web::protocol::http::Status;.
* @param dto - see [Data Transfer Object (DTO)](https://oatpp.io/docs/components/dto/).
* @param objectMapper - &id:oatpp::data::mapping::ObjectMapper;.
* @return - `std::shared_ptr` to &id:oatpp::web::protocol::http::outgoing::Response;.
*/
static std::shared_ptr<Response> createResponse(const Status& status,
const oatpp::Void& dto,
const std::shared_ptr<data::mapping::ObjectMapper>& objectMapper);
};
}}}}}
#endif /* oatpp_web_protocol_http_outgoing_ResponseFactory_hpp */
|
vincent-in-black-sesame/oat
|
src/oatpp/web/protocol/http/outgoing/ResponseFactory.hpp
|
C++
|
apache-2.0
| 3,064
|