diff --git a/README.md b/README.md index 4cf7344..93ede1d 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ RewriteRule . index.html Contains base handler: ``` -WSJCppLightWebHttpHandlerRewriteFolder(sPrefixPath, sDirPath) +WsjcppLightWebHttpHandlerRewriteFolder(sPrefixPath, sDirPath) ``` Where * sPrefixPath - like "/app1/" -> "http://localhost:1234/app1/" @@ -61,10 +61,10 @@ Example init, add handler and start server #include ... -WSJCppLightWebServer httpServer; +WsjcppLightWebServer httpServer; httpServer.setPort(1234); httpServer.setMaxWorkers(1); -httpServer.addHandler((WSJCppLightWebHttpHandlerBase *)new WSJCppLightWebHttpHandlerRewriteFolder("/app1/", "./web")); +httpServer.addHandler((WsjcppLightWebHttpHandlerBase *)new WsjcppLightWebHttpHandlerRewriteFolder("/app1/", "./web")); httpServer.startSync(); // this method will be hold current thread, if you with you can call just start/stop command ``` @@ -74,7 +74,7 @@ After compile and start will be available on `http://localhost:1234/app1/` Contains base handler: ``` -WSJCppLightWebHttpHandlerWebFolder(sPrefixPath, sDirPath) +WsjcppLightWebHttpHandlerWebFolder(sPrefixPath, sDirPath) ``` Where @@ -88,10 +88,10 @@ Example init, add handler and start server #include ... -WSJCppLightWebServer httpServer; +WsjcppLightWebServer httpServer; httpServer.setPort(1234); httpServer.setMaxWorkers(1); -httpServer.addHandler((WSJCppLightWebHttpHandlerBase *)new WSJCppLightWebHttpHandlerWebFolder("/app2/", "./web")); +httpServer.addHandler((WsjcppLightWebHttpHandlerBase *)new WsjcppLightWebHttpHandlerWebFolder("/app2/", "./web")); httpServer.startSync(); // this method will be hold current thread, if you with you can call just start/stop command ``` @@ -108,11 +108,11 @@ header-file `http_handler_custom.h`: #include -class HttpHandlerCustom : WSJCppLightWebHttpHandlerBase { +class HttpHandlerCustom : WsjcppLightWebHttpHandlerBase { public: HttpHandlerCustom(); - virtual bool canHandle(const std::string &sWorkerId, WSJCppLightWebHttpRequest *pRequest); - virtual bool handle(const std::string &sWorkerId, WSJCppLightWebHttpRequest *pRequest); + virtual bool canHandle(const std::string &sWorkerId, WsjcppLightWebHttpRequest *pRequest); + virtual bool handle(const std::string &sWorkerId, WsjcppLightWebHttpRequest *pRequest); private: std::string TAG; @@ -128,13 +128,13 @@ source-file `http_handler_custom.cpp`: // ---------------------------------------------------------------------- HttpHandlerCustom::HttpHandlerCustom() -: WSJCppLightWebHttpHandlerBase("custom") { +: WsjcppLightWebHttpHandlerBase("custom") { TAG = "HttpHandlerCustom"; } // ---------------------------------------------------------------------- -bool HttpHandlerCustom::canHandle(const std::string &sWorkerId, WSJCppLightWebHttpRequest *pRequest) { +bool HttpHandlerCustom::canHandle(const std::string &sWorkerId, WsjcppLightWebHttpRequest *pRequest) { std::string _tag = TAG + "-" + sWorkerId; std::string sRequestPath = pRequest->getRequestPath(); @@ -149,12 +149,12 @@ bool HttpHandlerCustom::canHandle(const std::string &sWorkerId, WSJCppLightWebHt // ---------------------------------------------------------------------- -bool HttpHandlerCustom::handle(const std::string &sWorkerId, WSJCppLightWebHttpRequest *pRequest) { +bool HttpHandlerCustom::handle(const std::string &sWorkerId, WsjcppLightWebHttpRequest *pRequest) { std::string _tag = TAG + "-" + sWorkerId; std::string sRequestPath = pRequest->getRequestPath(); - // WSJCppLog::warn(_tag, sRequestPath); + // WsjcppLog::warn(_tag, sRequestPath); - WSJCppLightWebHttpResponse resp(pRequest->getSockFd()); + WsjcppLightWebHttpResponse resp(pRequest->getSockFd()); if (sRequestPath == "/custom" || sRequestPath == "/custom/") { resp.cacheSec(60).ok().sendText( "

This is custom

" @@ -175,10 +175,10 @@ bool HttpHandlerCustom::handle(const std::string &sWorkerId, WSJCppLightWebHttpR Example init, add handler and start server __order is important! Server will call canHandle & handle in same order as addHandler called__ ``` -WSJCppLightWebServer httpServer; +WsjcppLightWebServer httpServer; httpServer.setPort(1234); httpServer.setMaxWorkers(1); -httpServer.addHandler((WSJCppLightWebHttpHandlerBase *)new HttpHandlerCustom()); -httpServer.addHandler((WSJCppLightWebHttpHandlerBase *)new WSJCppLightWebHttpHandlerRewriteFolder("/", "./web")); +httpServer.addHandler((WsjcppLightWebHttpHandlerBase *)new HttpHandlerCustom()); +httpServer.addHandler((WsjcppLightWebHttpHandlerBase *)new WsjcppLightWebHttpHandlerRewriteFolder("/", "./web")); httpServer.startSync(); // this method will be hold current thread, if you with you can call just start/stop command ``` diff --git a/scripts.wsjcpp/generate.WsjcppLightWebHttpHandler b/scripts.wsjcpp/generate.WsjcppLightWebHttpHandler index 5237982..1fdc0b4 100644 --- a/scripts.wsjcpp/generate.WsjcppLightWebHttpHandler +++ b/scripts.wsjcpp/generate.WsjcppLightWebHttpHandler @@ -36,11 +36,11 @@ concat content_header "#ifndef " ifndef_header " #include -class " class_name " : public WSJCppLightWebHttpHandlerBase { +class " class_name " : public WsjcppLightWebHttpHandlerBase { public: " class_name "(); - virtual bool canHandle(const std::string &sWorkerId, WSJCppLightWebHttpRequest *pRequest); - virtual bool handle(const std::string &sWorkerId, WSJCppLightWebHttpRequest *pRequest); + virtual bool canHandle(const std::string &sWorkerId, WsjcppLightWebHttpRequest *pRequest); + virtual bool handle(const std::string &sWorkerId, WsjcppLightWebHttpRequest *pRequest); private: std::string TAG; @@ -58,29 +58,29 @@ concat content_source " // " class_name " " class_name "::" class_name "() -: WSJCppLightWebHttpHandlerBase(\"" http_handler_name "\") { +: WsjcppLightWebHttpHandlerBase(\"" http_handler_name "\") { TAG = \"" class_name "\"; } // --------------------------------------------------------------------- -bool " class_name "::canHandle(const std::string &sWorkerId, WSJCppLightWebHttpRequest *pRequest) { +bool " class_name "::canHandle(const std::string &sWorkerId, WsjcppLightWebHttpRequest *pRequest) { std::string _tag = TAG + \"-\" + sWorkerId; std::string sRequestPath = pRequest->getRequestPath(); - WSJCppLog::warn(_tag, \"canHandle: \" + sRequestPath); + WsjcppLog::warn(_tag, \"canHandle: \" + sRequestPath); // TODO - WSJCppLog::err(TAG, \"Not implemented\"); + WsjcppLog::err(TAG, \"Not implemented\"); return false; } // --------------------------------------------------------------------- -bool " class_name "::handle(const std::string &sWorkerId, WSJCppLightWebHttpRequest *pRequest) { +bool " class_name "::handle(const std::string &sWorkerId, WsjcppLightWebHttpRequest *pRequest) { std::string _tag = TAG + \"-\" + sWorkerId; std::string sRequestPath = pRequest->getRequestPath(); - WSJCppLog::warn(_tag, sRequestPath); - WSJCppLightWebHttpResponse resp(pRequest->getSockFd()); + WsjcppLog::warn(_tag, sRequestPath); + WsjcppLightWebHttpResponse resp(pRequest->getSockFd()); resp.noCache().notImplemented().sendEmpty(); return true; } diff --git a/src.wsjcpp/CMakeLists.txt b/src.wsjcpp/CMakeLists.txt index 0e22428..e5c7e13 100644 --- a/src.wsjcpp/CMakeLists.txt +++ b/src.wsjcpp/CMakeLists.txt @@ -1,7 +1,7 @@ # Automaticly generated by wsjcpp@v0.0.1 cmake_minimum_required(VERSION 3.0) -add_definitions(-DWSJCPP_VERSION="v0.0.1") +add_definitions(-DWSJCPP_VERSION="v0.1.0") add_definitions(-DWSJCPP_NAME="wsjcpp-light-web-server") if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin") @@ -17,7 +17,7 @@ set (WSJCPP_SOURCES "") find_package(Threads REQUIRED) list (APPEND WSJCPP_LIBRARIES ${CMAKE_THREAD_LIBS_INIT}) -# wsjcpp-core:v0.0.7 +# wsjcpp-core:v0.1.1 list (APPEND WSJCPP_INCLUDE_DIRS "./src.wsjcpp/wsjcpp_core/") list (APPEND WSJCPP_SOURCES "./src.wsjcpp/wsjcpp_core/wsjcpp_core.cpp") list (APPEND WSJCPP_SOURCES "./src.wsjcpp/wsjcpp_core/wsjcpp_core.h") diff --git a/src.wsjcpp/wsjcpp_core/wsjcpp.hold.yml b/src.wsjcpp/wsjcpp_core/wsjcpp.hold.yml index d804d4d..1d20668 100644 --- a/src.wsjcpp/wsjcpp_core/wsjcpp.hold.yml +++ b/src.wsjcpp/wsjcpp_core/wsjcpp.hold.yml @@ -3,7 +3,7 @@ cmake_cxx_standard: 11 cmake_minimum_required: 3.0 name: wsjcpp-core -version: v0.0.7 +version: v0.1.1 description: Basic Utils for wsjcpp issues: https://github.com/wsjcpp/wsjcpp-core/issues repositories: @@ -62,3 +62,9 @@ unit-tests: description: "Test split function" - name: "CreateEmptyFile" description: "Test create empty file" + - name: "ReadFileToBuffer" + description: "test for readFileToBuffer" + - name: "Join" + description: "Test join function" + - name: "getHumanSizeBytes" + description: "Test function get human size in bytes" diff --git a/src.wsjcpp/wsjcpp_core/wsjcpp_core.cpp b/src.wsjcpp/wsjcpp_core/wsjcpp_core.cpp index bd4b041..0256d53 100644 --- a/src.wsjcpp/wsjcpp_core/wsjcpp_core.cpp +++ b/src.wsjcpp/wsjcpp_core/wsjcpp_core.cpp @@ -21,8 +21,9 @@ #include // --------------------------------------------------------------------- +// WsjcppCore -bool WSJCppCore::init( +bool WsjcppCore::init( int argc, char** argv, const std::string &sApplicationName, const std::string &sApplicationVersion, @@ -31,13 +32,13 @@ bool WSJCppCore::init( ) { // init random std::srand(std::rand() + std::time(0)); - // WSJCppCore::initRandom(); + // WsjcppCore::initRandom(); return true; } // --------------------------------------------------------------------- -std::string WSJCppCore::doNormalizePath(const std::string & sPath) { +std::string WsjcppCore::doNormalizePath(const std::string & sPath) { // split path by / std::vector vNames; std::string s = ""; @@ -99,7 +100,7 @@ std::string WSJCppCore::doNormalizePath(const std::string & sPath) { // --------------------------------------------------------------------- -std::string WSJCppCore::extractFilename(const std::string &sPath) { +std::string WsjcppCore::extractFilename(const std::string &sPath) { // split path by / std::vector vNames; std::string s = ""; @@ -127,32 +128,32 @@ std::string WSJCppCore::extractFilename(const std::string &sPath) { // --------------------------------------------------------------------- -std::string WSJCppCore::getCurrentDirectory() { +std::string WsjcppCore::getCurrentDirectory() { char cwd[PATH_MAX]; if (getcwd(cwd, sizeof(cwd)) == NULL) { - WSJCppLog::throw_err("getCurrentDirectory", "Could not get current directory"); + WsjcppLog::throw_err("getCurrentDirectory", "Could not get current directory"); } return std::string(cwd) + "/"; } // --------------------------------------------------------------------- -long WSJCppCore::currentTime_milliseconds() { +long WsjcppCore::currentTime_milliseconds() { long nTimeStart = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); return nTimeStart; } // --------------------------------------------------------------------- -long WSJCppCore::currentTime_seconds() { +long WsjcppCore::currentTime_seconds() { long nTimeStart = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); return nTimeStart; } // --------------------------------------------------------------------- -std::string WSJCppCore::currentTime_logformat() { - long nTimeStart = WSJCppCore::currentTime_milliseconds(); +std::string WsjcppCore::currentTime_logformat() { + long nTimeStart = WsjcppCore::currentTime_milliseconds(); std::string sMilliseconds = std::to_string(int(nTimeStart % 1000)); nTimeStart = nTimeStart / 1000; @@ -169,7 +170,7 @@ std::string WSJCppCore::currentTime_logformat() { // --------------------------------------------------------------------- -std::string WSJCppCore::threadId() { +std::string WsjcppCore::threadId() { std::thread::id this_id = std::this_thread::get_id(); std::stringstream stream; stream << std::hex << this_id; @@ -178,7 +179,7 @@ std::string WSJCppCore::threadId() { // --------------------------------------------------------------------- -std::string WSJCppCore::formatTimeForWeb(long nTimeInSec) { +std::string WsjcppCore::formatTimeForWeb(long nTimeInSec) { std::time_t tm_ = long(nTimeInSec); // struct tm tstruct = *localtime(&tm_); struct tm tstruct = *gmtime ( &tm_ ); @@ -194,14 +195,14 @@ std::string WSJCppCore::formatTimeForWeb(long nTimeInSec) { // --------------------------------------------------------------------- -std::string WSJCppCore::currentTime_forFilename() { - long nTimeStart = WSJCppCore::currentTime_seconds(); - return WSJCppCore::formatTimeForFilename(nTimeStart); +std::string WsjcppCore::currentTime_forFilename() { + long nTimeStart = WsjcppCore::currentTime_seconds(); + return WsjcppCore::formatTimeForFilename(nTimeStart); } // --------------------------------------------------------------------- -std::string WSJCppCore::formatTimeForFilename(long nTimeInSec) { +std::string WsjcppCore::formatTimeForFilename(long nTimeInSec) { std::time_t tm_ = long(nTimeInSec); // struct tm tstruct = *localtime(&tm_); struct tm tstruct = *gmtime ( &tm_ ); @@ -215,7 +216,7 @@ std::string WSJCppCore::formatTimeForFilename(long nTimeInSec) { // --------------------------------------------------------------------- -std::string WSJCppCore::formatTimeUTC(int nTimeInSec) { +std::string WsjcppCore::formatTimeUTC(int nTimeInSec) { // datetime std::time_t tm_ = long(nTimeInSec); // struct tm tstruct = *localtime(&tm_); @@ -230,7 +231,7 @@ std::string WSJCppCore::formatTimeUTC(int nTimeInSec) { // --------------------------------------------------------------------- -bool WSJCppCore::fileExists(const std::string &sFilename) { +bool WsjcppCore::fileExists(const std::string &sFilename) { struct stat st; bool bExists = (stat(sFilename.c_str(), &st) == 0); if (bExists) { @@ -241,7 +242,7 @@ bool WSJCppCore::fileExists(const std::string &sFilename) { // --------------------------------------------------------------------- -bool WSJCppCore::dirExists(const std::string &sDirname) { +bool WsjcppCore::dirExists(const std::string &sDirname) { struct stat st; bool bExists = (stat(sDirname.c_str(), &st) == 0); if (bExists) { @@ -252,9 +253,9 @@ bool WSJCppCore::dirExists(const std::string &sDirname) { // --------------------------------------------------------------------- -std::vector WSJCppCore::listOfDirs(const std::string &sDirname) { +std::vector WsjcppCore::listOfDirs(const std::string &sDirname) { std::vector vDirs; - if (!WSJCppCore::dirExists(sDirname)) { + if (!WsjcppCore::dirExists(sDirname)) { return vDirs; } DIR *dir = opendir(sDirname.c_str()); @@ -274,9 +275,9 @@ std::vector WSJCppCore::listOfDirs(const std::string &sDirname) { // --------------------------------------------------------------------- -std::vector WSJCppCore::listOfFiles(const std::string &sDirname) { +std::vector WsjcppCore::listOfFiles(const std::string &sDirname) { std::vector vFiles; - if (!WSJCppCore::dirExists(sDirname)) { + if (!WsjcppCore::dirExists(sDirname)) { return vFiles; } DIR *dir = opendir(sDirname.c_str()); @@ -296,7 +297,7 @@ std::vector WSJCppCore::listOfFiles(const std::string &sDirname) { // --------------------------------------------------------------------- -bool WSJCppCore::makeDir(const std::string &sDirname) { +bool WsjcppCore::makeDir(const std::string &sDirname) { struct stat st; int nStatus = mkdir(sDirname.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (nStatus == 0) { @@ -312,12 +313,12 @@ bool WSJCppCore::makeDir(const std::string &sDirname) { // --------------------------------------------------------------------- -bool WSJCppCore::writeFile(const std::string &sFilename, const std::string &sContent) { +bool WsjcppCore::writeFile(const std::string &sFilename, const std::string &sContent) { // std::ofstream f(sFilename, std::ifstream::in); std::ofstream f(sFilename, std::ios::out); if (!f) { - WSJCppLog::err("WSJCppCore", "Could not create file to write '" + sFilename + "'"); + WsjcppLog::err("WsjcppCore", "Could not create file to write '" + sFilename + "'"); return false; } f << sContent << std::endl; @@ -327,7 +328,7 @@ bool WSJCppCore::writeFile(const std::string &sFilename, const std::string &sCon // --------------------------------------------------------------------- -bool WSJCppCore::readTextFile(const std::string &sFilename, std::string &sContent) { +bool WsjcppCore::readTextFile(const std::string &sFilename, std::string &sContent) { std::ifstream f(sFilename); if (!f) { @@ -345,7 +346,34 @@ bool WSJCppCore::readTextFile(const std::string &sFilename, std::string &sConten // --------------------------------------------------------------------- -bool WSJCppCore::writeFile(const std::string &sFilename, const char *pBuffer, const int nBufferSize) { +bool WsjcppCore::readFileToBuffer(const std::string &sFilename, char *pBuffer[], int &nBufferSize) { + std::ifstream f(sFilename, std::ifstream::binary); + if (!f) { + return false; + } + + // get length of file: + f.seekg (0, f.end); + nBufferSize = f.tellg(); + f.seekg (0, f.beg); + + *pBuffer = new char [nBufferSize]; + + // read data as a block: + f.read (*pBuffer, nBufferSize); + if (!f) { + WsjcppLog::err("WsjcppCore::readFileToBuffer", "Only " + std::to_string(f.gcount()) + " could be read"); + delete[] pBuffer; + f.close(); + return false; + } + f.close(); + return true; +} + +// --------------------------------------------------------------------- + +bool WsjcppCore::writeFile(const std::string &sFilename, const char *pBuffer, const int nBufferSize) { std::ofstream f(sFilename, std::ios::out | std::ios::binary); if (!f) { std::cout << "FAILED could not create file to wtite " << sFilename << std::endl; @@ -358,14 +386,14 @@ bool WSJCppCore::writeFile(const std::string &sFilename, const char *pBuffer, co // --------------------------------------------------------------------- -bool WSJCppCore::removeFile(const std::string &sFilename) { +bool WsjcppCore::removeFile(const std::string &sFilename) { return remove(sFilename.c_str()) == 0; } // --------------------------------------------------------------------- -bool WSJCppCore::createEmptyFile(const std::string &sFilename) { - if (WSJCppCore::fileExists(sFilename)) { +bool WsjcppCore::createEmptyFile(const std::string &sFilename) { + if (WsjcppCore::fileExists(sFilename)) { return false; } std::ofstream f(sFilename, std::ios::out | std::ios::binary); @@ -379,28 +407,28 @@ bool WSJCppCore::createEmptyFile(const std::string &sFilename) { // --------------------------------------------------------------------- -std::string& WSJCppCore::ltrim(std::string& str, const std::string& chars) { +std::string& WsjcppCore::ltrim(std::string& str, const std::string& chars) { str.erase(0, str.find_first_not_of(chars)); return str; } // --------------------------------------------------------------------- -std::string& WSJCppCore::rtrim(std::string& str, const std::string& chars) { +std::string& WsjcppCore::rtrim(std::string& str, const std::string& chars) { str.erase(str.find_last_not_of(chars) + 1); return str; } // --------------------------------------------------------------------- -std::string& WSJCppCore::trim(std::string& str, const std::string& chars) { - return WSJCppCore::ltrim(WSJCppCore::rtrim(str, chars), chars); +std::string& WsjcppCore::trim(std::string& str, const std::string& chars) { + return WsjcppCore::ltrim(WsjcppCore::rtrim(str, chars), chars); } // --------------------------------------------------------------------- // will worked only with latin -std::string WSJCppCore::toLower(const std::string& str) { +std::string WsjcppCore::toLower(const std::string& str) { std::string sRet = str; std::transform(sRet.begin(), sRet.end(), sRet.begin(), ::tolower); return sRet; @@ -409,7 +437,7 @@ std::string WSJCppCore::toLower(const std::string& str) { // --------------------------------------------------------------------- // will worked only with latin -std::string WSJCppCore::toUpper(const std::string& str) { +std::string WsjcppCore::toUpper(const std::string& str) { std::string sRet = str; std::transform(sRet.begin(), sRet.end(), sRet.begin(), ::toupper); return sRet; @@ -417,7 +445,7 @@ std::string WSJCppCore::toUpper(const std::string& str) { // --------------------------------------------------------------------- -void WSJCppCore::replaceAll(std::string& str, const std::string& sFrom, const std::string& sTo) { +void WsjcppCore::replaceAll(std::string& str, const std::string& sFrom, const std::string& sTo) { if (sFrom.empty()) { return; } @@ -430,7 +458,7 @@ void WSJCppCore::replaceAll(std::string& str, const std::string& sFrom, const st // --------------------------------------------------------------------- -std::vector WSJCppCore::split(const std::string& sWhat, const std::string& sDelim) { +std::vector WsjcppCore::split(const std::string& sWhat, const std::string& sDelim) { std::vector vRet; int nPos = 0; int nLen = sWhat.length(); @@ -455,13 +483,26 @@ std::vector WSJCppCore::split(const std::string& sWhat, const std:: // --------------------------------------------------------------------- -void WSJCppCore::initRandom() { +std::string WsjcppCore::join(const std::vector &vWhat, const std::string& sDelim) { + std::string sRet; + for (int i = 0; i < vWhat.size(); i++) { + if (i != 0) { + sRet += sDelim; + } + sRet += vWhat[i]; + } + return sRet; +} + +// --------------------------------------------------------------------- + +void WsjcppCore::initRandom() { std::srand(std::rand() + std::time(0)); } // --------------------------------------------------------------------- -std::string WSJCppCore::createUuid() { +std::string WsjcppCore::createUuid() { std::string sRet = "00000000-0000-0000-0000-000000000000"; const std::string sAlphabet = "0123456789abcdef"; // unsigned t = std::time(0); @@ -476,7 +517,7 @@ std::string WSJCppCore::createUuid() { // --------------------------------------------------------------------- -std::string WSJCppCore::uint2hexString(unsigned int n) { +std::string WsjcppCore::uint2hexString(unsigned int n) { std::string sRet; for (int i = 0; i < 8; i++) { sRet += "0123456789abcdef"[n % 16]; @@ -487,14 +528,14 @@ std::string WSJCppCore::uint2hexString(unsigned int n) { // --------------------------------------------------------------------- -unsigned long WSJCppCore::convertVoidToULong(void *p) { +unsigned long WsjcppCore::convertVoidToULong(void *p) { std::uintptr_t ret = reinterpret_cast(p); return (unsigned long)ret; } // --------------------------------------------------------------------- -std::string WSJCppCore::getPointerAsHex(void *p) { +std::string WsjcppCore::getPointerAsHex(void *p) { std::uintptr_t i = reinterpret_cast(p); std::stringstream stream; stream << std::hex << i; @@ -503,7 +544,7 @@ std::string WSJCppCore::getPointerAsHex(void *p) { // --------------------------------------------------------------------- -std::string WSJCppCore::extractURLProtocol(const std::string& sValue) { +std::string WsjcppCore::extractURLProtocol(const std::string& sValue) { std::string sRet = ""; int nPosProtocol = sValue.find("://"); if (nPosProtocol == std::string::npos) { @@ -515,7 +556,7 @@ std::string WSJCppCore::extractURLProtocol(const std::string& sValue) { // --------------------------------------------------------------------- -bool WSJCppCore::getEnv(const std::string& sName, std::string& sValue) { +bool WsjcppCore::getEnv(const std::string& sName, std::string& sValue) { if (const char* env_p = std::getenv(sName.c_str())) { sValue = std::string(env_p); return true; @@ -525,7 +566,7 @@ bool WSJCppCore::getEnv(const std::string& sName, std::string& sValue) { // --------------------------------------------------------------------- -std::string WSJCppCore::encodeUriComponent(const std::string& sValue) { +std::string WsjcppCore::encodeUriComponent(const std::string& sValue) { std::stringstream ssRet; for (int i = 0; i < sValue.length(); i++) { char c = sValue[i]; @@ -545,7 +586,7 @@ std::string WSJCppCore::encodeUriComponent(const std::string& sValue) { // --------------------------------------------------------------------- -std::string WSJCppCore::decodeUriComponent(const std::string& sValue) { +std::string WsjcppCore::decodeUriComponent(const std::string& sValue) { std::string sRet = ""; std::string sHex = ""; int nLen = sValue.length(); @@ -553,7 +594,7 @@ std::string WSJCppCore::decodeUriComponent(const std::string& sValue) { char c = sValue[i]; if (c == '%') { if (i+2 >= nLen) { - WSJCppLog::throw_err("WSJCppCore::decodeUriElement", "Wrong format of string"); + WsjcppLog::throw_err("WsjcppCore::decodeUriElement", "Wrong format of string"); } sHex = "0x"; sHex += sValue[i+1]; @@ -569,70 +610,95 @@ std::string WSJCppCore::decodeUriComponent(const std::string& sValue) { } // --------------------------------------------------------------------- -// WSJCppLog + +std::string WsjcppCore::getHumanSizeBytes(long nBytes) { + if (nBytes == 0) { + return "0B"; + } + std::string arrPrefix[] = {"B", "KB", "MB", "GB", "TB", "PB"}; + long n0 = nBytes; + long n1 = 0; + for (int i = 0; i < 6; i++) { + if (n0 >= 1 && n0 < 1000) { + return std::to_string(n0) + arrPrefix[i]; + } + n0 = nBytes / 1000; + n1 = nBytes - n0 * 1000; + n0 += n1 >= 500 ? 1 : 0; + + nBytes = nBytes / 1000; + if (n0 == 0 && n1 == 0) { + return "fuck"; + } + } + return std::to_string(nBytes) + "PB"; +} + +// --------------------------------------------------------------------- +// WsjcppLog // Last log messages -std::deque * WSJCppLog::g_WSJCPP_LOG_LAST_MESSAGES = nullptr; -std::mutex * WSJCppLog::g_WSJCPP_LOG_MUTEX = nullptr; -std::string WSJCppLog::g_WSJCPP_LOG_DIR = "./"; -std::string WSJCppLog::g_WSJCPP_LOG_FILE = ""; -std::string WSJCppLog::g_WSJCPP_LOG_PREFIX_FILE = ""; -long WSJCppLog::g_WSJCPP_LOG_START_TIME = 0; +std::deque * WsjcppLog::g_WSJCPP_LOG_LAST_MESSAGES = nullptr; +std::mutex * WsjcppLog::g_WSJCPP_LOG_MUTEX = nullptr; +std::string WsjcppLog::g_WSJCPP_LOG_DIR = "./"; +std::string WsjcppLog::g_WSJCPP_LOG_FILE = ""; +std::string WsjcppLog::g_WSJCPP_LOG_PREFIX_FILE = ""; +long WsjcppLog::g_WSJCPP_LOG_START_TIME = 0; // --------------------------------------------------------------------- -void WSJCppLog::doLogRotateUpdateFilename(bool bForce) { - long t = WSJCppCore::currentTime_seconds(); +void WsjcppLog::doLogRotateUpdateFilename(bool bForce) { + long t = WsjcppCore::currentTime_seconds(); long nEverySeconds = 51000; // rotate log if started now or if time left more then 1 day if (g_WSJCPP_LOG_START_TIME == 0 || t - g_WSJCPP_LOG_START_TIME > nEverySeconds || bForce) { g_WSJCPP_LOG_START_TIME = t; g_WSJCPP_LOG_FILE = g_WSJCPP_LOG_DIR + "/" - + WSJCppLog::g_WSJCPP_LOG_PREFIX_FILE + "_" - + WSJCppCore::formatTimeForFilename(g_WSJCPP_LOG_START_TIME) + ".log"; + + WsjcppLog::g_WSJCPP_LOG_PREFIX_FILE + "_" + + WsjcppCore::formatTimeForFilename(g_WSJCPP_LOG_START_TIME) + ".log"; } } // --------------------------------------------------------------------- -void WSJCppLog::info(const std::string & sTag, const std::string &sMessage) { - WSJCppColorModifier def(WSJCppColorCode::FG_DEFAULT); - WSJCppLog::add(def, "INFO", sTag, sMessage); +void WsjcppLog::info(const std::string & sTag, const std::string &sMessage) { + WsjcppColorModifier def(WsjcppColorCode::FG_DEFAULT); + WsjcppLog::add(def, "INFO", sTag, sMessage); } // --------------------------------------------------------------------- -void WSJCppLog::err(const std::string & sTag, const std::string &sMessage) { - WSJCppColorModifier red(WSJCppColorCode::FG_RED); - WSJCppLog::add(red, "ERR", sTag, sMessage); +void WsjcppLog::err(const std::string & sTag, const std::string &sMessage) { + WsjcppColorModifier red(WsjcppColorCode::FG_RED); + WsjcppLog::add(red, "ERR", sTag, sMessage); } // --------------------------------------------------------------------- -void WSJCppLog::throw_err(const std::string &sTag, const std::string &sMessage) { - WSJCppColorModifier red(WSJCppColorCode::FG_RED); - WSJCppLog::add(red, "ERR", sTag, sMessage); +void WsjcppLog::throw_err(const std::string &sTag, const std::string &sMessage) { + WsjcppColorModifier red(WsjcppColorCode::FG_RED); + WsjcppLog::add(red, "ERR", sTag, sMessage); throw std::runtime_error(sMessage); } // --------------------------------------------------------------------- -void WSJCppLog::warn(const std::string & sTag, const std::string &sMessage) { - WSJCppColorModifier yellow(WSJCppColorCode::FG_YELLOW); - WSJCppLog::add(yellow, "WARN",sTag, sMessage); +void WsjcppLog::warn(const std::string & sTag, const std::string &sMessage) { + WsjcppColorModifier yellow(WsjcppColorCode::FG_YELLOW); + WsjcppLog::add(yellow, "WARN",sTag, sMessage); } // --------------------------------------------------------------------- -void WSJCppLog::ok(const std::string &sTag, const std::string &sMessage) { - WSJCppColorModifier green(WSJCppColorCode::FG_GREEN); - WSJCppLog::add(green, "OK", sTag, sMessage); +void WsjcppLog::ok(const std::string &sTag, const std::string &sMessage) { + WsjcppColorModifier green(WsjcppColorCode::FG_GREEN); + WsjcppLog::add(green, "OK", sTag, sMessage); } // --------------------------------------------------------------------- -std::vector WSJCppLog::getLastLogMessages() { - WSJCppLog::initGlobalVariables(); - std::lock_guard lock(*WSJCppLog::g_WSJCPP_LOG_MUTEX); +std::vector WsjcppLog::getLastLogMessages() { + WsjcppLog::initGlobalVariables(); + std::lock_guard lock(*WsjcppLog::g_WSJCPP_LOG_MUTEX); std::vector vRet; for (int i = 0; i < g_WSJCPP_LOG_LAST_MESSAGES->size(); i++) { vRet.push_back(g_WSJCPP_LOG_LAST_MESSAGES->at(i)); @@ -642,43 +708,43 @@ std::vector WSJCppLog::getLastLogMessages() { // --------------------------------------------------------------------- -void WSJCppLog::setLogDirectory(const std::string &sDirectoryPath) { - WSJCppLog::g_WSJCPP_LOG_DIR = sDirectoryPath; - WSJCppLog::doLogRotateUpdateFilename(true); +void WsjcppLog::setLogDirectory(const std::string &sDirectoryPath) { + WsjcppLog::g_WSJCPP_LOG_DIR = sDirectoryPath; + WsjcppLog::doLogRotateUpdateFilename(true); } // --------------------------------------------------------------------- -void WSJCppLog::setPrefixLogFile(const std::string &sPrefixLogFile) { - WSJCppLog::g_WSJCPP_LOG_PREFIX_FILE = sPrefixLogFile; - WSJCppLog::doLogRotateUpdateFilename(true); +void WsjcppLog::setPrefixLogFile(const std::string &sPrefixLogFile) { + WsjcppLog::g_WSJCPP_LOG_PREFIX_FILE = sPrefixLogFile; + WsjcppLog::doLogRotateUpdateFilename(true); } // --------------------------------------------------------------------- -void WSJCppLog::initGlobalVariables() { +void WsjcppLog::initGlobalVariables() { // create deque if not created - if (WSJCppLog::g_WSJCPP_LOG_LAST_MESSAGES == nullptr) { - WSJCppLog::g_WSJCPP_LOG_LAST_MESSAGES = new std::deque(); - // std::cout << WSJCppCore::currentTime_logformat() + ", " + WSJCppCore::threadId() + " Init last messages deque\r\n"; + if (WsjcppLog::g_WSJCPP_LOG_LAST_MESSAGES == nullptr) { + WsjcppLog::g_WSJCPP_LOG_LAST_MESSAGES = new std::deque(); + // std::cout << WsjcppCore::currentTime_logformat() + ", " + WsjcppCore::threadId() + " Init last messages deque\r\n"; } // create mutex if not created - if (WSJCppLog::g_WSJCPP_LOG_MUTEX == nullptr) { - WSJCppLog::g_WSJCPP_LOG_MUTEX = new std::mutex(); - // std::cout << WSJCppCore::currentTime_logformat() + ", " + WSJCppCore::threadId() + " Init mutex for log\r\n"; + if (WsjcppLog::g_WSJCPP_LOG_MUTEX == nullptr) { + WsjcppLog::g_WSJCPP_LOG_MUTEX = new std::mutex(); + // std::cout << WsjcppCore::currentTime_logformat() + ", " + WsjcppCore::threadId() + " Init mutex for log\r\n"; } } // --------------------------------------------------------------------- -void WSJCppLog::add(WSJCppColorModifier &clr, const std::string &sType, const std::string &sTag, const std::string &sMessage) { - WSJCppLog::initGlobalVariables(); - WSJCppLog::doLogRotateUpdateFilename(); +void WsjcppLog::add(WsjcppColorModifier &clr, const std::string &sType, const std::string &sTag, const std::string &sMessage) { + WsjcppLog::initGlobalVariables(); + WsjcppLog::doLogRotateUpdateFilename(); - std::lock_guard lock(*WSJCppLog::g_WSJCPP_LOG_MUTEX); - WSJCppColorModifier def(WSJCppColorCode::FG_DEFAULT); + std::lock_guard lock(*WsjcppLog::g_WSJCPP_LOG_MUTEX); + WsjcppColorModifier def(WsjcppColorCode::FG_DEFAULT); - std::string sLogMessage = WSJCppCore::currentTime_logformat() + ", " + WSJCppCore::threadId() + std::string sLogMessage = WsjcppCore::currentTime_logformat() + ", " + WsjcppCore::threadId() + " [" + sType + "] " + sTag + ": " + sMessage; std::cout << clr << sLogMessage << def << std::endl; @@ -687,7 +753,7 @@ void WSJCppLog::add(WSJCppColorModifier &clr, const std::string &sType, const st g_WSJCPP_LOG_LAST_MESSAGES->pop_back(); } // TODO try create global variable - std::ofstream logFile(WSJCppLog::g_WSJCPP_LOG_FILE, std::ios::app); + std::ofstream logFile(WsjcppLog::g_WSJCPP_LOG_FILE, std::ios::app); if (!logFile) { std::cout << "Error Opening File" << std::endl; return; diff --git a/src.wsjcpp/wsjcpp_core/wsjcpp_core.h b/src.wsjcpp/wsjcpp_core/wsjcpp_core.h index 8cb293d..4884467 100644 --- a/src.wsjcpp/wsjcpp_core/wsjcpp_core.h +++ b/src.wsjcpp/wsjcpp_core/wsjcpp_core.h @@ -8,7 +8,7 @@ #include #include -class WSJCppCore { +class WsjcppCore { public: static bool init( int argc, char** argv, @@ -38,6 +38,7 @@ class WSJCppCore { static bool makeDir(const std::string &sDirname); static bool writeFile(const std::string &sFilename, const std::string &sContent); static bool readTextFile(const std::string &sFilename, std::string &sOutputContent); + static bool readFileToBuffer(const std::string &sFilename, char *pBuffer[], int &nBufferSize); static bool writeFile(const std::string &sFilename, const char *pBuffer, const int nBufferSize); static bool removeFile(const std::string &sFilename); static bool createEmptyFile(const std::string &sFilename); @@ -49,6 +50,7 @@ class WSJCppCore { static std::string toUpper(const std::string& str); static void replaceAll(std::string& str, const std::string& from, const std::string& to); static std::vector split(const std::string& sWhat, const std::string& sDelim); + static std::string join(const std::vector &vWhat, const std::string& sDelim); static void initRandom(); static std::string createUuid(); @@ -61,13 +63,13 @@ class WSJCppCore { static std::string encodeUriComponent(const std::string& sValue); static std::string decodeUriComponent(const std::string& sValue); - + static std::string getHumanSizeBytes(long nBytes); }; // --------------------------------------------------------------------- -enum WSJCppColorCode { +enum WsjcppColorCode { FG_RED = 31, FG_GREEN = 32, FG_YELLOW = 93, @@ -81,19 +83,19 @@ enum WSJCppColorCode { // --------------------------------------------------------------------- -class WSJCppColorModifier { - WSJCppColorCode code; +class WsjcppColorModifier { + WsjcppColorCode code; public: - WSJCppColorModifier(WSJCppColorCode pCode) : code(pCode) {} + WsjcppColorModifier(WsjcppColorCode pCode) : code(pCode) {} friend std::ostream& - operator<<(std::ostream& os, const WSJCppColorModifier& mod) { + operator<<(std::ostream& os, const WsjcppColorModifier& mod) { return os << "\033[" << mod.code << "m"; } }; // --------------------------------------------------------------------- -class WSJCppLog { +class WsjcppLog { public: static std::string g_WSJCPP_LOG_DIR; static std::string g_WSJCPP_LOG_PREFIX_FILE; @@ -114,7 +116,7 @@ class WSJCppLog { static void initGlobalVariables(); private: - static void add(WSJCppColorModifier &clr, const std::string &sType, const std::string &sTag, const std::string &sMessage); + static void add(WsjcppColorModifier &clr, const std::string &sType, const std::string &sTag, const std::string &sMessage); }; #endif // WSJCPP_CORE_H diff --git a/src.wsjcpp/wsjcpp_core/wsjcpp_unit_tests.cpp b/src.wsjcpp/wsjcpp_core/wsjcpp_unit_tests.cpp index 645833a..d675dac 100644 --- a/src.wsjcpp/wsjcpp_core/wsjcpp_unit_tests.cpp +++ b/src.wsjcpp/wsjcpp_core/wsjcpp_unit_tests.cpp @@ -1,32 +1,32 @@ #include "wsjcpp_unit_tests.h" -WSJCppUnitTestBase::WSJCppUnitTestBase(const std::string &sTestName) { +WsjcppUnitTestBase::WsjcppUnitTestBase(const std::string &sTestName) { m_sTestName = sTestName; TAG = m_sTestName; - WSJCppUnitTests::addUnitTest(sTestName, this); + WsjcppUnitTests::addUnitTest(sTestName, this); } // --------------------------------------------------------------------- -std::string WSJCppUnitTestBase::name() { +std::string WsjcppUnitTestBase::name() { return m_sTestName; } // --------------------------------------------------------------------- -void WSJCppUnitTestBase::compareS(bool &bTestSuccess, const std::string &sPoint, +void WsjcppUnitTestBase::compareS(bool &bTestSuccess, const std::string &sPoint, const std::string &sValue, const std::string &sExpected) { if (sValue != sExpected) { - WSJCppLog::err(TAG, " {" + sPoint + "} Expected '" + sExpected + "', but got '" + sValue + "'"); + WsjcppLog::err(TAG, " {" + sPoint + "} Expected '" + sExpected + "', but got '" + sValue + "'"); bTestSuccess = false; } } // --------------------------------------------------------------------- -bool WSJCppUnitTestBase::compareN(bool &bTestSuccess, const std::string &sPoint, int nValue, int nExpected) { +bool WsjcppUnitTestBase::compareN(bool &bTestSuccess, const std::string &sPoint, int nValue, int nExpected) { if (nValue != nExpected) { - WSJCppLog::err(TAG, " {" + sPoint + "} Expected '" + std::to_string(nExpected) + "', but got '" + std::to_string(nValue) + "'"); + WsjcppLog::err(TAG, " {" + sPoint + "} Expected '" + std::to_string(nExpected) + "', but got '" + std::to_string(nValue) + "'"); bTestSuccess = false; return false; } @@ -35,9 +35,9 @@ bool WSJCppUnitTestBase::compareN(bool &bTestSuccess, const std::string &sPoint, // --------------------------------------------------------------------- -bool WSJCppUnitTestBase::compareD(bool &bTestSuccess, const std::string &sPoint, double nValue, double nExpected) { +bool WsjcppUnitTestBase::compareD(bool &bTestSuccess, const std::string &sPoint, double nValue, double nExpected) { if (nValue != nExpected) { - WSJCppLog::err(TAG, " {" + sPoint + "} Expected '" + std::to_string(nExpected) + "', but got '" + std::to_string(nValue) + "'"); + WsjcppLog::err(TAG, " {" + sPoint + "} Expected '" + std::to_string(nExpected) + "', but got '" + std::to_string(nValue) + "'"); bTestSuccess = false; return false; } @@ -46,64 +46,42 @@ bool WSJCppUnitTestBase::compareD(bool &bTestSuccess, const std::string &sPoint, // --------------------------------------------------------------------- -void WSJCppUnitTestBase::compareB(bool &bTestSuccess, const std::string &sPoint, bool bValue, bool bExpected) { +void WsjcppUnitTestBase::compareB(bool &bTestSuccess, const std::string &sPoint, bool bValue, bool bExpected) { if (bValue != bExpected) { - WSJCppLog::err(TAG, " {" + sPoint + "} Expected '" + (bExpected ? "true" : "false") + "', but got '" + (bValue ? "true" : "false") + "'"); + WsjcppLog::err(TAG, " {" + sPoint + "} Expected '" + (bExpected ? "true" : "false") + "', but got '" + (bValue ? "true" : "false") + "'"); bTestSuccess = false; } } // --------------------------------------------------------------------- -std::vector *g_pUnitTests = NULL; +std::vector *g_pWsjcppUnitTests = nullptr; -void WSJCppUnitTests::initGlobalVariables() { - if (g_pUnitTests == NULL) { - // Log::info(std::string(), "Create handlers map"); - g_pUnitTests = new std::vector(); +void WsjcppUnitTests::initGlobalVariables() { + if (g_pWsjcppUnitTests == nullptr) { + // WsjcppLog::info(std::string(), "Create handlers map"); + g_pWsjcppUnitTests = new std::vector(); } } // --------------------------------------------------------------------- -void WSJCppUnitTests::addUnitTest(const std::string &sTestName, WSJCppUnitTestBase* pUnitTest) { - WSJCppUnitTests::initGlobalVariables(); +void WsjcppUnitTests::addUnitTest(const std::string &sTestName, WsjcppUnitTestBase* pUnitTest) { + WsjcppUnitTests::initGlobalVariables(); bool bFound = false; - for (int i = 0; i < g_pUnitTests->size(); i++) { - WSJCppUnitTestBase* p = g_pUnitTests->at(i); + for (int i = 0; i < g_pWsjcppUnitTests->size(); i++) { + WsjcppUnitTestBase* p = g_pWsjcppUnitTests->at(i); if (p->name() == sTestName) { bFound = true; } } if (bFound) { - WSJCppLog::err(sTestName, "Already registered"); + WsjcppLog::err(sTestName, "Already registered"); } else { - g_pUnitTests->push_back(pUnitTest); + g_pWsjcppUnitTests->push_back(pUnitTest); // Log::info(sCmd, "Registered"); } } -// --------------------------------------------------------------------- - -bool WSJCppUnitTests::runUnitTests() { - WSJCppUnitTests::initGlobalVariables(); - int nAll = g_pUnitTests->size(); - WSJCppLog::info("runUnitTests", "All tests count " + std::to_string(nAll)); - int nSuccess = 0; - for (int i = 0; i < g_pUnitTests->size(); i++) { - WSJCppUnitTestBase* pUnitTest = g_pUnitTests->at(i); - std::string sTestName = pUnitTest->name(); - WSJCppLog::info("runUnitTests", "Run test " + sTestName); - if (pUnitTest->run()) { - WSJCppLog::ok(sTestName, "Test passed"); - nSuccess++; - } else { - WSJCppLog::err(sTestName, "Test failed"); - } - } - WSJCppLog::info("WSJCpp::runUnitTests", "Passed tests " + std::to_string(nSuccess) + " / " + std::to_string(nAll)); - return nSuccess == nAll; -} - // --------------------------------------------------------------------- \ No newline at end of file diff --git a/src.wsjcpp/wsjcpp_core/wsjcpp_unit_tests.h b/src.wsjcpp/wsjcpp_core/wsjcpp_unit_tests.h index 46d4192..b3213db 100644 --- a/src.wsjcpp/wsjcpp_core/wsjcpp_unit_tests.h +++ b/src.wsjcpp/wsjcpp_core/wsjcpp_unit_tests.h @@ -5,9 +5,9 @@ #include #include -class WSJCppUnitTestBase { +class WsjcppUnitTestBase { public: - WSJCppUnitTestBase(const std::string &sTestName); + WsjcppUnitTestBase(const std::string &sTestName); std::string name(); virtual void init() = 0; virtual bool run() = 0; @@ -23,18 +23,17 @@ class WSJCppUnitTestBase { std::string m_sTestName; }; -extern std::vector *g_pUnitTests; +extern std::vector *g_pWsjcppUnitTests; -class WSJCppUnitTests { +class WsjcppUnitTests { public: static void initGlobalVariables(); - static void addUnitTest(const std::string &sTestName, WSJCppUnitTestBase* pCmdHandler); - static bool runUnitTests(); + static void addUnitTest(const std::string &sTestName, WsjcppUnitTestBase* pUnitTest); }; // RegistryCmdHandler -#define REGISTRY_UNIT_TEST( classname ) \ - static classname * pRegistryWSJCppUnitTest ## classname = new classname(); \ +#define REGISTRY_WSJCPP_UNIT_TEST( classname ) \ + static classname * pRegistryWsjcppUnitTest ## classname = new classname(); \ #endif // WSJCPP_UNIT_TESTS_H \ No newline at end of file diff --git a/src.wsjcpp/wsjcpp_core/wsjcpp_unit_tests_main.cpp b/src.wsjcpp/wsjcpp_core/wsjcpp_unit_tests_main.cpp index 32eb432..23fb13c 100644 --- a/src.wsjcpp/wsjcpp_core/wsjcpp_unit_tests_main.cpp +++ b/src.wsjcpp/wsjcpp_core/wsjcpp_unit_tests_main.cpp @@ -2,23 +2,93 @@ #include #include +void printHelp(const std::string &sProgramName) { + std::string sOutput = "\nHelp:\n"; + sOutput += + " '" + sProgramName + "' - run all unit-tests\n" + " '" + sProgramName + " help' - print this help\n" + " '" + sProgramName + " list' - print list of unit-tests\n" + " '" + sProgramName + " run ' - run single unit-test\n" + ; + WsjcppLog::info("UnitTests", sOutput); +} + int main(int argc, char** argv) { - WSJCppCore::initRandom(); + WsjcppCore::initRandom(); std::string TAG = "UnitTests"; - WSJCppLog::setPrefixLogFile("unit-tests"); + WsjcppLog::setPrefixLogFile("unit-tests"); std::string sLogDir = "./logs"; - if (!WSJCppCore::dirExists(sLogDir)) { - WSJCppCore::makeDir(sLogDir); + if (!WsjcppCore::dirExists(sLogDir)) { + WsjcppCore::makeDir(sLogDir); } - WSJCppLog::setLogDirectory(sLogDir); - if (!WSJCppCore::dirExists(sLogDir)) { - WSJCppLog::err(TAG, "Directory '" + sLogDir + "' did'not exists"); + WsjcppLog::setLogDirectory(sLogDir); + if (!WsjcppCore::dirExists(sLogDir)) { + WsjcppLog::err(TAG, "Directory '" + sLogDir + "' did'not exists"); return -1; } - if (!WSJCppUnitTests::runUnitTests()) { - WSJCppLog::err(TAG, "Some unit tests failed"); + WsjcppUnitTests::initGlobalVariables(); + std::string sProgramName(argv[0]); + + if (argc == 1) { + int nAll = g_pWsjcppUnitTests->size(); + WsjcppLog::info("runUnitTests", "All tests count " + std::to_string(nAll)); + int nSuccess = 0; + for (int i = 0; i < g_pWsjcppUnitTests->size(); i++) { + WsjcppUnitTestBase* pUnitTest = g_pWsjcppUnitTests->at(i); + std::string sTestName = pUnitTest->name(); + WsjcppLog::info("runUnitTests", "Run test " + sTestName); + if (pUnitTest->run()) { + WsjcppLog::ok(sTestName, "Test passed"); + nSuccess++; + } else { + WsjcppLog::err(sTestName, "Test failed"); + } + } + WsjcppLog::info(TAG, "Passed tests " + std::to_string(nSuccess) + " / " + std::to_string(nAll)); + bool bResult = nSuccess == nAll; + return bResult ? 0 : -1; + } else if (argc == 2) { + std::string sArg2(argv[1]); + if (sArg2 == "list") { + std::string sOutput = "\nList of unit-tests:\n"; + for (int i = 0; i < g_pWsjcppUnitTests->size(); i++) { + WsjcppUnitTestBase* pUnitTest = g_pWsjcppUnitTests->at(i); + sOutput += " - " + pUnitTest->name() + "\n"; + } + WsjcppLog::info(TAG, sOutput); + return -1; + } else if (sArg2 == "help") { + printHelp(sProgramName); + return -1; + } + } else if (argc == 3) { + std::string sArg2(argv[1]); + std::string sArg3(argv[2]); + if (sArg2 == "run") { + int nSuccess = 0; + bool bTestFound = false; + for (int i = 0; i < g_pWsjcppUnitTests->size(); i++) { + WsjcppUnitTestBase* pUnitTest = g_pWsjcppUnitTests->at(i); + if (pUnitTest->name() == sArg3) { + bTestFound = true; + if (pUnitTest->run()) { + WsjcppLog::ok(TAG, pUnitTest->name() + " Test passed"); + nSuccess++; + } else { + WsjcppLog::err(TAG, pUnitTest->name() + " Test failed"); + } + } + } + if (!bTestFound) { + WsjcppLog::err(TAG, "Test not found try help"); + } + return -1; + } + printHelp(sProgramName); return -1; } + + printHelp(sProgramName); return 0; } \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp index e65e0c3..e5a4ff5 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -7,11 +7,11 @@ int main(int argc, const char* argv[]) { std::string TAG = "MAIN"; std::string appName = std::string(WSJCPP_NAME); std::string appVersion = std::string(WSJCPP_VERSION); - if (!WSJCppCore::dirExists(".logs")) { - WSJCppCore::makeDir(".logs"); + if (!WsjcppCore::dirExists(".logs")) { + WsjcppCore::makeDir(".logs"); } - WSJCppLog::setPrefixLogFile("wsjcpp"); - WSJCppLog::setLogDirectory(".logs"); + WsjcppLog::setPrefixLogFile("wsjcpp"); + WsjcppLog::setLogDirectory(".logs"); if (argc != 3) { std::cout << "Usage: " << argv[0] << " [folder|rewrite] " << std::endl; @@ -25,15 +25,15 @@ int main(int argc, const char* argv[]) { std::string sDir = std::string(argv[2]); - WSJCppLightWebServer httpServer; + WsjcppLightWebServer httpServer; httpServer.setPort(1234); httpServer.setMaxWorkers(4); if (sType == "folder") { - httpServer.addHandler(new WSJCppLightWebHttpHandlerWebFolder("/app/", sDir)); - httpServer.addHandler(new WSJCppLightWebHttpHandlerWebFolder("/", sDir)); + httpServer.addHandler(new WsjcppLightWebHttpHandlerWebFolder("/app/", sDir)); + httpServer.addHandler(new WsjcppLightWebHttpHandlerWebFolder("/", sDir)); } else if (sType == "rewrite") { - httpServer.addHandler(new WSJCppLightWebHttpHandlerRewriteFolder("/app/", sDir)); - httpServer.addHandler(new WSJCppLightWebHttpHandlerRewriteFolder("/", sDir)); + httpServer.addHandler(new WsjcppLightWebHttpHandlerRewriteFolder("/app/", sDir)); + httpServer.addHandler(new WsjcppLightWebHttpHandlerRewriteFolder("/", sDir)); } httpServer.startSync(); return 0; diff --git a/src/wsjcpp_light_web_deque_http_requests.cpp b/src/wsjcpp_light_web_deque_http_requests.cpp index 9ac3732..2e2c6bb 100644 --- a/src/wsjcpp_light_web_deque_http_requests.cpp +++ b/src/wsjcpp_light_web_deque_http_requests.cpp @@ -3,20 +3,20 @@ #include // ---------------------------------------------------------------------- -// WSJCppLightWebDequeHttpRequests +// WsjcppLightWebDequeHttpRequests -WSJCppLightWebDequeHttpRequests::WSJCppLightWebDequeHttpRequests() { - TAG = "WSJCppLightWebDequeHttpRequests"; +WsjcppLightWebDequeHttpRequests::WsjcppLightWebDequeHttpRequests() { + TAG = "WsjcppLightWebDequeHttpRequests"; } // ---------------------------------------------------------------------- -WSJCppLightWebHttpRequest *WSJCppLightWebDequeHttpRequests::popRequest() { +WsjcppLightWebHttpRequest *WsjcppLightWebDequeHttpRequests::popRequest() { if (m_dequeRequests.size() == 0) { m_mtxWaiterRequests.lock(); } std::lock_guard guard(this->m_mtxDequeRequests); - WSJCppLightWebHttpRequest *pRequest = nullptr; + WsjcppLightWebHttpRequest *pRequest = nullptr; int nSize = m_dequeRequests.size(); if (nSize > 0) { pRequest = m_dequeRequests.back(); @@ -27,11 +27,11 @@ WSJCppLightWebHttpRequest *WSJCppLightWebDequeHttpRequests::popRequest() { // ---------------------------------------------------------------------- -void WSJCppLightWebDequeHttpRequests::pushRequest(WSJCppLightWebHttpRequest *pRequest) { +void WsjcppLightWebDequeHttpRequests::pushRequest(WsjcppLightWebHttpRequest *pRequest) { { std::lock_guard guard(this->m_mtxDequeRequests); if (m_dequeRequests.size() > 20) { - WSJCppLog::warn(TAG, " deque more than " + std::to_string(m_dequeRequests.size())); + WsjcppLog::warn(TAG, " deque more than " + std::to_string(m_dequeRequests.size())); } m_dequeRequests.push_front(pRequest); } @@ -43,7 +43,7 @@ void WSJCppLightWebDequeHttpRequests::pushRequest(WSJCppLightWebHttpRequest *pRe // ---------------------------------------------------------------------- -void WSJCppLightWebDequeHttpRequests::cleanup() { +void WsjcppLightWebDequeHttpRequests::cleanup() { std::lock_guard guard(this->m_mtxDequeRequests); while (m_dequeRequests.size() > 0) { delete m_dequeRequests.back(); diff --git a/src/wsjcpp_light_web_deque_http_requests.h b/src/wsjcpp_light_web_deque_http_requests.h index 75c0508..5ce14bb 100644 --- a/src/wsjcpp_light_web_deque_http_requests.h +++ b/src/wsjcpp_light_web_deque_http_requests.h @@ -9,11 +9,11 @@ // --------------------------------------------------------------------- -class WSJCppLightWebDequeHttpRequests { +class WsjcppLightWebDequeHttpRequests { public: - WSJCppLightWebDequeHttpRequests(); - WSJCppLightWebHttpRequest *popRequest(); - void pushRequest(WSJCppLightWebHttpRequest *pRequest); + WsjcppLightWebDequeHttpRequests(); + WsjcppLightWebHttpRequest *popRequest(); + void pushRequest(WsjcppLightWebHttpRequest *pRequest); void cleanup(); private: @@ -21,7 +21,7 @@ class WSJCppLightWebDequeHttpRequests { std::mutex m_mtxDequeRequests; std::mutex m_mtxWaiterRequests; - std::deque m_dequeRequests; + std::deque m_dequeRequests; }; #endif // WSJCPP_LIGHT_WEB_DEQUE_HTTP_REQUESTS_H diff --git a/src/wsjcpp_light_web_http_handler_rewrite_folder.cpp b/src/wsjcpp_light_web_http_handler_rewrite_folder.cpp index 46be094..4e0e6e8 100644 --- a/src/wsjcpp_light_web_http_handler_rewrite_folder.cpp +++ b/src/wsjcpp_light_web_http_handler_rewrite_folder.cpp @@ -3,19 +3,19 @@ // ---------------------------------------------------------------------- -WSJCppLightWebHttpHandlerRewriteFolder::WSJCppLightWebHttpHandlerRewriteFolder(const std::string &sPrefixPath, const std::string &sWebFolder) -: WSJCppLightWebHttpHandlerBase("rewrite-folder") { +WsjcppLightWebHttpHandlerRewriteFolder::WsjcppLightWebHttpHandlerRewriteFolder(const std::string &sPrefixPath, const std::string &sWebFolder) +: WsjcppLightWebHttpHandlerBase("rewrite-folder") { - TAG = "WSJCppLightWebHttpHandlerRewriteFolder"; - m_sPrefixPath = WSJCppCore::doNormalizePath(sPrefixPath + "/"); - m_sWebFolder = WSJCppCore::doNormalizePath(sWebFolder + "/"); + TAG = "WsjcppLightWebHttpHandlerRewriteFolder"; + m_sPrefixPath = WsjcppCore::doNormalizePath(sPrefixPath + "/"); + m_sWebFolder = WsjcppCore::doNormalizePath(sWebFolder + "/"); } // ---------------------------------------------------------------------- -bool WSJCppLightWebHttpHandlerRewriteFolder::canHandle(const std::string &sWorkerId, WSJCppLightWebHttpRequest *pRequest) { +bool WsjcppLightWebHttpHandlerRewriteFolder::canHandle(const std::string &sWorkerId, WsjcppLightWebHttpRequest *pRequest) { std::string _tag = TAG + "-" + sWorkerId; - // WSJCppLog::warn(_tag, "canHandle: " + pRequest->requestPath()); + // WsjcppLog::warn(_tag, "canHandle: " + pRequest->requestPath()); std::string sRequestPath = pRequest->getRequestPath(); if (m_sPrefixPath.length() > sRequestPath.length()) { @@ -27,28 +27,28 @@ bool WSJCppLightWebHttpHandlerRewriteFolder::canHandle(const std::string &sWorke return false; } - if (!WSJCppCore::dirExists(m_sWebFolder)) { - WSJCppLog::warn(_tag, "Directory " + m_sWebFolder + " does not exists"); + if (!WsjcppCore::dirExists(m_sWebFolder)) { + WsjcppLog::warn(_tag, "Directory " + m_sWebFolder + " does not exists"); } return true; } // ---------------------------------------------------------------------- -bool WSJCppLightWebHttpHandlerRewriteFolder::handle(const std::string &sWorkerId, WSJCppLightWebHttpRequest *pRequest) { +bool WsjcppLightWebHttpHandlerRewriteFolder::handle(const std::string &sWorkerId, WsjcppLightWebHttpRequest *pRequest) { std::string _tag = TAG + "-" + sWorkerId; std::string sRequestPath = pRequest->getRequestPath(); - // WSJCppLog::warn(_tag, pRequest->requestPath()); + // WsjcppLog::warn(_tag, pRequest->requestPath()); // cat subfolder std::string sRequestPath2 = sRequestPath.substr(m_sPrefixPath.length(), sRequestPath.length() - m_sPrefixPath.length()); std::string sFilePath = m_sWebFolder + sRequestPath2; - if (WSJCppCore::fileExists(sFilePath)) { - WSJCppLightWebHttpResponse resp(pRequest->getSockFd()); + if (WsjcppCore::fileExists(sFilePath)) { + WsjcppLightWebHttpResponse resp(pRequest->getSockFd()); resp.cacheSec(60).ok().sendFile(sFilePath); } else { std::string sFilePath = m_sWebFolder + "/index.html"; - WSJCppLightWebHttpResponse resp(pRequest->getSockFd()); + WsjcppLightWebHttpResponse resp(pRequest->getSockFd()); resp.cacheSec(60).ok().sendFile(sFilePath); } return true; diff --git a/src/wsjcpp_light_web_http_handler_rewrite_folder.h b/src/wsjcpp_light_web_http_handler_rewrite_folder.h index fb877cc..bf7a06e 100644 --- a/src/wsjcpp_light_web_http_handler_rewrite_folder.h +++ b/src/wsjcpp_light_web_http_handler_rewrite_folder.h @@ -3,11 +3,11 @@ #include -class WSJCppLightWebHttpHandlerRewriteFolder : public WSJCppLightWebHttpHandlerBase { +class WsjcppLightWebHttpHandlerRewriteFolder : public WsjcppLightWebHttpHandlerBase { public: - WSJCppLightWebHttpHandlerRewriteFolder(const std::string &sPrefixPath, const std::string &sWebFolder); - virtual bool canHandle(const std::string &sWorkerId, WSJCppLightWebHttpRequest *pRequest); - virtual bool handle(const std::string &sWorkerId, WSJCppLightWebHttpRequest *pRequest); + WsjcppLightWebHttpHandlerRewriteFolder(const std::string &sPrefixPath, const std::string &sWebFolder); + virtual bool canHandle(const std::string &sWorkerId, WsjcppLightWebHttpRequest *pRequest); + virtual bool handle(const std::string &sWorkerId, WsjcppLightWebHttpRequest *pRequest); private: std::string TAG; diff --git a/src/wsjcpp_light_web_http_handler_web_folder.cpp b/src/wsjcpp_light_web_http_handler_web_folder.cpp index c5fc26f..356bc4e 100644 --- a/src/wsjcpp_light_web_http_handler_web_folder.cpp +++ b/src/wsjcpp_light_web_http_handler_web_folder.cpp @@ -3,19 +3,19 @@ // ---------------------------------------------------------------------- -WSJCppLightWebHttpHandlerWebFolder::WSJCppLightWebHttpHandlerWebFolder(const std::string &sPrefixPath, const std::string &sWebFolder) -: WSJCppLightWebHttpHandlerBase("web-folder") { +WsjcppLightWebHttpHandlerWebFolder::WsjcppLightWebHttpHandlerWebFolder(const std::string &sPrefixPath, const std::string &sWebFolder) +: WsjcppLightWebHttpHandlerBase("web-folder") { - TAG = "WSJCppLightWebHttpHandlerWebFolder"; - m_sPrefixPath = WSJCppCore::doNormalizePath(sPrefixPath + "/"); - m_sWebFolder = WSJCppCore::doNormalizePath(sWebFolder + "/"); + TAG = "WsjcppLightWebHttpHandlerWebFolder"; + m_sPrefixPath = WsjcppCore::doNormalizePath(sPrefixPath + "/"); + m_sWebFolder = WsjcppCore::doNormalizePath(sWebFolder + "/"); } // ---------------------------------------------------------------------- -bool WSJCppLightWebHttpHandlerWebFolder::canHandle(const std::string &sWorkerId, WSJCppLightWebHttpRequest *pRequest) { +bool WsjcppLightWebHttpHandlerWebFolder::canHandle(const std::string &sWorkerId, WsjcppLightWebHttpRequest *pRequest) { std::string _tag = TAG + "-" + sWorkerId; - // WSJCppLog::warn(_tag, "canHandle: " + pRequest->requestPath()); + // WsjcppLog::warn(_tag, "canHandle: " + pRequest->requestPath()); std::string sRequestPath = pRequest->getRequestPath(); if (m_sPrefixPath.length() > sRequestPath.length()) { @@ -27,31 +27,31 @@ bool WSJCppLightWebHttpHandlerWebFolder::canHandle(const std::string &sWorkerId, return false; } - if (!WSJCppCore::dirExists(m_sWebFolder)) { - WSJCppLog::warn(_tag, "Directory " + m_sWebFolder + " does not exists"); + if (!WsjcppCore::dirExists(m_sWebFolder)) { + WsjcppLog::warn(_tag, "Directory " + m_sWebFolder + " does not exists"); } return true; } // ---------------------------------------------------------------------- -bool WSJCppLightWebHttpHandlerWebFolder::handle(const std::string &sWorkerId, WSJCppLightWebHttpRequest *pRequest) { +bool WsjcppLightWebHttpHandlerWebFolder::handle(const std::string &sWorkerId, WsjcppLightWebHttpRequest *pRequest) { std::string _tag = TAG + "-" + sWorkerId; std::string sRequestPath = pRequest->getRequestPath(); - // WSJCppLog::warn(_tag, sRequestPath); + // WsjcppLog::warn(_tag, sRequestPath); std::string sRequestPath2 = sRequestPath.substr(m_sPrefixPath.length(), sRequestPath.length() - m_sPrefixPath.length()); - // WSJCppLog::warn(_tag, sRequestPath2); + // WsjcppLog::warn(_tag, sRequestPath2); if (sRequestPath2 == "") { sRequestPath2 = "index.html"; } std::string sFilePath = m_sWebFolder + sRequestPath2; - // WSJCppLog::warn(_tag, sFilePath); + // WsjcppLog::warn(_tag, sFilePath); - if (WSJCppCore::fileExists(sFilePath)) { - WSJCppLightWebHttpResponse resp(pRequest->getSockFd()); + if (WsjcppCore::fileExists(sFilePath)) { + WsjcppLightWebHttpResponse resp(pRequest->getSockFd()); resp.cacheSec(60).ok().sendFile(sFilePath); } else { - WSJCppLightWebHttpResponse resp(pRequest->getSockFd()); + WsjcppLightWebHttpResponse resp(pRequest->getSockFd()); resp.noCache().notFound().sendEmpty(); } return true; diff --git a/src/wsjcpp_light_web_http_handler_web_folder.h b/src/wsjcpp_light_web_http_handler_web_folder.h index c98ff20..8ad7221 100644 --- a/src/wsjcpp_light_web_http_handler_web_folder.h +++ b/src/wsjcpp_light_web_http_handler_web_folder.h @@ -3,11 +3,11 @@ #include -class WSJCppLightWebHttpHandlerWebFolder : public WSJCppLightWebHttpHandlerBase { +class WsjcppLightWebHttpHandlerWebFolder : public WsjcppLightWebHttpHandlerBase { public: - WSJCppLightWebHttpHandlerWebFolder(const std::string &sPrefixPath, const std::string &sWebFolder); - virtual bool canHandle(const std::string &sWorkerId, WSJCppLightWebHttpRequest *pRequest); - virtual bool handle(const std::string &sWorkerId, WSJCppLightWebHttpRequest *pRequest); + WsjcppLightWebHttpHandlerWebFolder(const std::string &sPrefixPath, const std::string &sWebFolder); + virtual bool canHandle(const std::string &sWorkerId, WsjcppLightWebHttpRequest *pRequest); + virtual bool handle(const std::string &sWorkerId, WsjcppLightWebHttpRequest *pRequest); private: std::string TAG; diff --git a/src/wsjcpp_light_web_http_request.cpp b/src/wsjcpp_light_web_http_request.cpp index 44a7aea..b14404a 100644 --- a/src/wsjcpp_light_web_http_request.cpp +++ b/src/wsjcpp_light_web_http_request.cpp @@ -5,93 +5,93 @@ // ---------------------------------------------------------------------- -WSJCppLightWebHttpRequestQueryValue::WSJCppLightWebHttpRequestQueryValue(const std::string &sName, const std::string &sValue) { +WsjcppLightWebHttpRequestQueryValue::WsjcppLightWebHttpRequestQueryValue(const std::string &sName, const std::string &sValue) { m_sName = sName; m_sValue = sValue; } // ---------------------------------------------------------------------- -std::string WSJCppLightWebHttpRequestQueryValue::getName() const { +std::string WsjcppLightWebHttpRequestQueryValue::getName() const { return m_sName; } // ---------------------------------------------------------------------- -std::string WSJCppLightWebHttpRequestQueryValue::getValue() const { +std::string WsjcppLightWebHttpRequestQueryValue::getValue() const { return m_sValue; } // ---------------------------------------------------------------------- -// WSJCppLightWebHttpRequest +// WsjcppLightWebHttpRequest -WSJCppLightWebHttpRequest::WSJCppLightWebHttpRequest(int nSockFd, const std::string &sAddress) { - TAG = "WSJCppLightWebHttpRequest"; - m_sUniqueId = WSJCppCore::createUuid(); +WsjcppLightWebHttpRequest::WsjcppLightWebHttpRequest(int nSockFd, const std::string &sAddress) { + TAG = "WsjcppLightWebHttpRequest"; + m_sUniqueId = WsjcppCore::createUuid(); m_nSockFd = nSockFd; m_sAddress = sAddress; m_bClosed = false; m_sRequest = ""; m_nParserState = EnumParserState::START; - long nSec = WSJCppCore::currentTime_seconds(); - m_sLastModified = WSJCppCore::formatTimeForWeb(nSec); + long nSec = WsjcppCore::currentTime_seconds(); + m_sLastModified = WsjcppCore::formatTimeForWeb(nSec); m_nContentLength = 0; } // ---------------------------------------------------------------------- -int WSJCppLightWebHttpRequest::getSockFd() const { +int WsjcppLightWebHttpRequest::getSockFd() const { return m_nSockFd; } // ---------------------------------------------------------------------- -std::string WSJCppLightWebHttpRequest::getUniqueId() const { +std::string WsjcppLightWebHttpRequest::getUniqueId() const { return m_sUniqueId; } // ---------------------------------------------------------------------- -std::string WSJCppLightWebHttpRequest::getRequestType() const { +std::string WsjcppLightWebHttpRequest::getRequestType() const { return m_sRequestType; } // ---------------------------------------------------------------------- -std::string WSJCppLightWebHttpRequest::getRequestPath() const { +std::string WsjcppLightWebHttpRequest::getRequestPath() const { return m_sRequestPath; } -std::string WSJCppLightWebHttpRequest::getRequestBody() const { +std::string WsjcppLightWebHttpRequest::getRequestBody() const { return m_sRequestBody; } // ---------------------------------------------------------------------- -std::string WSJCppLightWebHttpRequest::getRequestHttpVersion() const { +std::string WsjcppLightWebHttpRequest::getRequestHttpVersion() const { return m_sRequestHttpVersion; } // ---------------------------------------------------------------------- -const std::vector &WSJCppLightWebHttpRequest::getRequestQueryParams() { +const std::vector &WsjcppLightWebHttpRequest::getRequestQueryParams() { return m_vRequestQueryParams; } // ---------------------------------------------------------------------- -std::string WSJCppLightWebHttpRequest::getAddress() const { +std::string WsjcppLightWebHttpRequest::getAddress() const { return m_sAddress; } // ---------------------------------------------------------------------- -void WSJCppLightWebHttpRequest::appendRecieveRequest(const std::string &sRequestPart) { +void WsjcppLightWebHttpRequest::appendRecieveRequest(const std::string &sRequestPart) { m_sRequest += sRequestPart; const std::string sContentLengthPrefix = "content-length:"; if (m_nParserState == EnumParserState::START) { m_vHeaders.clear(); - // WSJCppLog::info(TAG, "START \n>>>\n" + m_sRequest + "\n<<<\n"); + // WsjcppLog::info(TAG, "START \n>>>\n" + m_sRequest + "\n<<<\n"); std::istringstream f(m_sRequest); std::string sLine = ""; @@ -99,18 +99,18 @@ void WSJCppLightWebHttpRequest::appendRecieveRequest(const std::string &sRequest bool bHeadersEnded = false; while (getline(f, sLine, '\n')) { nSize += sLine.length() + 1; - WSJCppCore::trim(sLine); - // WSJCppLog::info(TAG, "Line: {" + sLine + "}, size=" + std::to_string(sLine.length())); + WsjcppCore::trim(sLine); + // WsjcppLog::info(TAG, "Line: {" + sLine + "}, size=" + std::to_string(sLine.length())); if (sLine.length() == 0) { bHeadersEnded = true; break; } m_vHeaders.push_back(sLine); - sLine = WSJCppCore::toLower(sLine); + sLine = WsjcppCore::toLower(sLine); if (!sLine.compare(0, sContentLengthPrefix.size(), sContentLengthPrefix)) { m_nContentLength = atoi(sLine.substr(sContentLengthPrefix.size()).c_str()); - // WSJCppLog::warn(TAG, "Content-Length: " + std::to_string(m_nContentLength)); + // WsjcppLog::warn(TAG, "Content-Length: " + std::to_string(m_nContentLength)); } } @@ -119,10 +119,10 @@ void WSJCppLightWebHttpRequest::appendRecieveRequest(const std::string &sRequest this->parseFirstLine(m_vHeaders[0]); } m_sRequest.erase(0, nSize); - // WSJCppLog::info(TAG, "AFTER ERASE \n>>>\n" + m_sRequest + "\n<<<\n"); + // WsjcppLog::info(TAG, "AFTER ERASE \n>>>\n" + m_sRequest + "\n<<<\n"); m_nParserState = EnumParserState::BODY; } else { - // WSJCppLog::info(TAG, "Not ended"); + // WsjcppLog::info(TAG, "Not ended"); } } @@ -134,13 +134,13 @@ void WSJCppLightWebHttpRequest::appendRecieveRequest(const std::string &sRequest // ---------------------------------------------------------------------- -bool WSJCppLightWebHttpRequest::isEnoughAppendReceived() const { +bool WsjcppLightWebHttpRequest::isEnoughAppendReceived() const { return m_nParserState == EnumParserState::ENDED; } // ---------------------------------------------------------------------- -void WSJCppLightWebHttpRequest::parseFirstLine(const std::string &sHeader) { +void WsjcppLightWebHttpRequest::parseFirstLine(const std::string &sHeader) { if (sHeader.size() > 0) { std::istringstream f(sHeader); std::vector params; @@ -165,11 +165,11 @@ void WSJCppLightWebHttpRequest::parseFirstLine(const std::string &sHeader) { if (m_sRequestPath.length() == 0) { m_sRequestPath = "/"; } - m_sRequestPath = WSJCppCore::doNormalizePath(m_sRequestPath); + m_sRequestPath = WsjcppCore::doNormalizePath(m_sRequestPath); // TODO url path encoding while (m_sRequestPath.length() > 2 && m_sRequestPath.substr(0,2) == "..") { - m_sRequestPath = WSJCppCore::doNormalizePath("/erase/" + m_sRequestPath); + m_sRequestPath = WsjcppCore::doNormalizePath("/erase/" + m_sRequestPath); } // parse query @@ -183,9 +183,9 @@ void WSJCppLightWebHttpRequest::parseFirstLine(const std::string &sHeader) { std::size_t nFound2 = sParam.find("="); std::string sValue = sParam.substr(nFound2+1); std::string sName = sParam.substr(0, nFound2); - m_vRequestQueryParams.push_back(WSJCppLightWebHttpRequestQueryValue( - WSJCppCore::decodeUriComponent(sName), - WSJCppCore::decodeUriComponent(sValue) + m_vRequestQueryParams.push_back(WsjcppLightWebHttpRequestQueryValue( + WsjcppCore::decodeUriComponent(sName), + WsjcppCore::decodeUriComponent(sValue) )); } } diff --git a/src/wsjcpp_light_web_http_request.h b/src/wsjcpp_light_web_http_request.h index 8a76723..6a3f833 100644 --- a/src/wsjcpp_light_web_http_request.h +++ b/src/wsjcpp_light_web_http_request.h @@ -7,9 +7,9 @@ // --------------------------------------------------------------------- -class WSJCppLightWebHttpRequestQueryValue { +class WsjcppLightWebHttpRequestQueryValue { public: - WSJCppLightWebHttpRequestQueryValue(const std::string &sName, const std::string &sValue); + WsjcppLightWebHttpRequestQueryValue(const std::string &sName, const std::string &sValue); std::string getName() const; std::string getValue() const; private: @@ -19,13 +19,13 @@ class WSJCppLightWebHttpRequestQueryValue { // --------------------------------------------------------------------- -class WSJCppLightWebHttpRequest { +class WsjcppLightWebHttpRequest { public: - WSJCppLightWebHttpRequest( + WsjcppLightWebHttpRequest( int nSockFd, const std::string &sAddress ); - ~WSJCppLightWebHttpRequest() {}; + ~WsjcppLightWebHttpRequest() {}; int getSockFd() const; std::string getUniqueId() const; @@ -37,7 +37,7 @@ class WSJCppLightWebHttpRequest { std::string getRequestPath() const; std::string getRequestBody() const; std::string getRequestHttpVersion() const; - const std::vector &getRequestQueryParams(); + const std::vector &getRequestQueryParams(); private: std::string TAG; @@ -60,7 +60,7 @@ class WSJCppLightWebHttpRequest { std::string m_sRequestType; std::string m_sRequestPath; std::string m_sRequestBody; - std::vector m_vRequestQueryParams; + std::vector m_vRequestQueryParams; std::string m_sRequestHttpVersion; std::string m_sResponseCacheControl; diff --git a/src/wsjcpp_light_web_http_response.cpp b/src/wsjcpp_light_web_http_response.cpp index 4a5607e..b319135 100644 --- a/src/wsjcpp_light_web_http_response.cpp +++ b/src/wsjcpp_light_web_http_response.cpp @@ -6,110 +6,110 @@ #include // ---------------------------------------------------------------------- -// WSJCppLightWebHttpResponse +// WsjcppLightWebHttpResponse // enum for http responses -std::map *WSJCppLightWebHttpResponse::g_mapReponseDescription = nullptr; +std::map *WsjcppLightWebHttpResponse::g_mapReponseDescription = nullptr; // ---------------------------------------------------------------------- -WSJCppLightWebHttpResponse::WSJCppLightWebHttpResponse(int nSockFd) { - TAG = "WSJCppLightWebHttpResponse"; - if (WSJCppLightWebHttpResponse::g_mapReponseDescription == nullptr) { - WSJCppLightWebHttpResponse::g_mapReponseDescription = new std::map(); - WSJCppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair(200,"HTTP/1.1 200 OK")); - WSJCppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair(400, "HTTP/1.1 400 Bad Request")); - WSJCppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair(403, "HTTP/1.1 403 Forbidden")); - WSJCppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair(404, "HTTP/1.1 404 Not Found")); - WSJCppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair(413, "HTTP/1.1 413 Payload Too Large")); - WSJCppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair(500, "HTTP/1.1 500 Internal Server Error")); - WSJCppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair(501, "HTTP/1.1 501 Not Implemented")); - WSJCppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair(408, "HTTP/1.1 408 Request Time-out")); +WsjcppLightWebHttpResponse::WsjcppLightWebHttpResponse(int nSockFd) { + TAG = "WsjcppLightWebHttpResponse"; + if (WsjcppLightWebHttpResponse::g_mapReponseDescription == nullptr) { + WsjcppLightWebHttpResponse::g_mapReponseDescription = new std::map(); + WsjcppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair(200,"HTTP/1.1 200 OK")); + WsjcppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair(400, "HTTP/1.1 400 Bad Request")); + WsjcppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair(403, "HTTP/1.1 403 Forbidden")); + WsjcppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair(404, "HTTP/1.1 404 Not Found")); + WsjcppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair(413, "HTTP/1.1 413 Payload Too Large")); + WsjcppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair(500, "HTTP/1.1 500 Internal Server Error")); + WsjcppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair(501, "HTTP/1.1 501 Not Implemented")); + WsjcppLightWebHttpResponse::g_mapReponseDescription->insert(std::pair(408, "HTTP/1.1 408 Request Time-out")); } m_nSockFd = nSockFd; m_bClosed = false; noCache(); - long nSec = WSJCppCore::currentTime_seconds(); - m_sLastModified = WSJCppCore::formatTimeForWeb(nSec); + long nSec = WsjcppCore::currentTime_seconds(); + m_sLastModified = WsjcppCore::formatTimeForWeb(nSec); m_nResponseCode = 500; m_sDataType = "text/html"; } // ---------------------------------------------------------------------- -WSJCppLightWebHttpResponse &WSJCppLightWebHttpResponse::ok() { +WsjcppLightWebHttpResponse &WsjcppLightWebHttpResponse::ok() { m_nResponseCode = 200; return *this; } // ---------------------------------------------------------------------- -WSJCppLightWebHttpResponse &WSJCppLightWebHttpResponse::badRequest() { +WsjcppLightWebHttpResponse &WsjcppLightWebHttpResponse::badRequest() { m_nResponseCode = 400; return *this; } // ---------------------------------------------------------------------- -WSJCppLightWebHttpResponse &WSJCppLightWebHttpResponse::forbidden() { +WsjcppLightWebHttpResponse &WsjcppLightWebHttpResponse::forbidden() { m_nResponseCode = 403; return *this; } // ---------------------------------------------------------------------- -WSJCppLightWebHttpResponse &WSJCppLightWebHttpResponse::notFound() { +WsjcppLightWebHttpResponse &WsjcppLightWebHttpResponse::notFound() { m_nResponseCode = 404; return *this; } // ---------------------------------------------------------------------- -WSJCppLightWebHttpResponse &WSJCppLightWebHttpResponse::payloadTooLarge() { +WsjcppLightWebHttpResponse &WsjcppLightWebHttpResponse::payloadTooLarge() { m_nResponseCode = 413; return *this; } // ---------------------------------------------------------------------- -WSJCppLightWebHttpResponse &WSJCppLightWebHttpResponse::internalServerError() { +WsjcppLightWebHttpResponse &WsjcppLightWebHttpResponse::internalServerError() { m_nResponseCode = 500; return *this; } // ---------------------------------------------------------------------- -WSJCppLightWebHttpResponse &WSJCppLightWebHttpResponse::notImplemented() { +WsjcppLightWebHttpResponse &WsjcppLightWebHttpResponse::notImplemented() { m_nResponseCode = 501; return *this; } // ---------------------------------------------------------------------- -WSJCppLightWebHttpResponse &WSJCppLightWebHttpResponse::requestTimeout() { +WsjcppLightWebHttpResponse &WsjcppLightWebHttpResponse::requestTimeout() { m_nResponseCode = 408; return *this; } // ---------------------------------------------------------------------- -WSJCppLightWebHttpResponse &WSJCppLightWebHttpResponse::noCache() { +WsjcppLightWebHttpResponse &WsjcppLightWebHttpResponse::noCache() { m_sCacheControl = "no-cache, no-store, must-revalidate"; return *this; } // ---------------------------------------------------------------------- -WSJCppLightWebHttpResponse &WSJCppLightWebHttpResponse::cacheSec(int nCacheSec) { +WsjcppLightWebHttpResponse &WsjcppLightWebHttpResponse::cacheSec(int nCacheSec) { m_sCacheControl = "max-age=" + std::to_string(nCacheSec); return *this; } // ---------------------------------------------------------------------- -std::string WSJCppLightWebHttpResponse::prepareHeaders(int nLength) { - std::string sResponseCode = WSJCppLightWebHttpResponse::g_mapReponseDescription->at(m_nResponseCode); +std::string WsjcppLightWebHttpResponse::prepareHeaders(int nLength) { + std::string sResponseCode = WsjcppLightWebHttpResponse::g_mapReponseDescription->at(m_nResponseCode); return sResponseCode + "\r\n" "Date: " + m_sLastModified + "\r\n" "Server: wsjcpp\r\n" @@ -123,7 +123,7 @@ std::string WSJCppLightWebHttpResponse::prepareHeaders(int nLength) { // ---------------------------------------------------------------------- -std::string WSJCppLightWebHttpResponse::detectTypeOfFile(const std::string &sFilePath) { +std::string WsjcppLightWebHttpResponse::detectTypeOfFile(const std::string &sFilePath) { // TODO cache: check file in cache std::string sFileExt = sFilePath.substr(sFilePath.find_last_of(".") + 1); @@ -154,19 +154,19 @@ std::string WSJCppLightWebHttpResponse::detectTypeOfFile(const std::string &sFil // ---------------------------------------------------------------------- -void WSJCppLightWebHttpResponse::sendText(const std::string &sBody) { +void WsjcppLightWebHttpResponse::sendText(const std::string &sBody) { m_sDataType = "text/html"; std::string sResponse = prepareHeaders(sBody.length()) + "\r\n" + sBody; if (m_bClosed) { - WSJCppLog::warn(TAG, "Already sended response"); + WsjcppLog::warn(TAG, "Already sended response"); return; } m_bClosed = true; - WSJCppLog::info(TAG, "\nResponse: \n>>>\n" + sResponse + "\n<<<"); + WsjcppLog::info(TAG, "\nResponse: \n>>>\n" + sResponse + "\n<<<"); send(m_nSockFd, sResponse.c_str(), sResponse.length(),0); close(m_nSockFd); @@ -174,19 +174,19 @@ void WSJCppLightWebHttpResponse::sendText(const std::string &sBody) { // ---------------------------------------------------------------------- -void WSJCppLightWebHttpResponse::sendJson(const nlohmann::json &json) { +void WsjcppLightWebHttpResponse::sendJson(const nlohmann::json &json) { m_sDataType = "application/json"; std::string sBody = json.dump(); std::string sResponse = prepareHeaders(sBody.length()) + "\r\n" + sBody; if (m_bClosed) { - WSJCppLog::warn(TAG, "Already sended response"); + WsjcppLog::warn(TAG, "Already sended response"); return; } m_bClosed = true; - WSJCppLog::info(TAG, "\nResponse: \n>>>\n" + sResponse + "\n<<<"); + WsjcppLog::info(TAG, "\nResponse: \n>>>\n" + sResponse + "\n<<<"); send(m_nSockFd, sResponse.c_str(), sResponse.length(),0); close(m_nSockFd); @@ -194,25 +194,25 @@ void WSJCppLightWebHttpResponse::sendJson(const nlohmann::json &json) { // ---------------------------------------------------------------------- -void WSJCppLightWebHttpResponse::sendEmpty() { +void WsjcppLightWebHttpResponse::sendEmpty() { this->sendText(""); } // ---------------------------------------------------------------------- -void WSJCppLightWebHttpResponse::sendOptions(const std::string &sOptions) { +void WsjcppLightWebHttpResponse::sendOptions(const std::string &sOptions) { m_sDataType = "text/html"; std::string sResponse = prepareHeaders(0) + "Access-Control-Allow-Methods: " + sOptions + "\r\n\r\n"; if (m_bClosed) { - WSJCppLog::warn(TAG, "Already sended response"); + WsjcppLog::warn(TAG, "Already sended response"); return; } m_bClosed = true; - WSJCppLog::info(TAG, "\nResponse: \n>>>\n" + sResponse + "\n<<<"); + WsjcppLog::info(TAG, "\nResponse: \n>>>\n" + sResponse + "\n<<<"); send(m_nSockFd, sResponse.c_str(), sResponse.length(),0); close(m_nSockFd); @@ -220,7 +220,7 @@ void WSJCppLightWebHttpResponse::sendOptions(const std::string &sOptions) { // ---------------------------------------------------------------------- -void WSJCppLightWebHttpResponse::sendFile(const std::string &sFilePath) { +void WsjcppLightWebHttpResponse::sendFile(const std::string &sFilePath) { // read data from file std::ifstream f(sFilePath, std::ios::binary | std::ios::ate); @@ -249,7 +249,7 @@ void WSJCppLightWebHttpResponse::sendFile(const std::string &sFilePath) { // ---------------------------------------------------------------------- -void WSJCppLightWebHttpResponse::sendBuffer(const std::string &sFilePath, const char *pBuffer, const int nBufferSize) { +void WsjcppLightWebHttpResponse::sendBuffer(const std::string &sFilePath, const char *pBuffer, const int nBufferSize) { // TODO cache: check file in cache m_sDataType = detectTypeOfFile(sFilePath); @@ -258,7 +258,7 @@ void WSJCppLightWebHttpResponse::sendBuffer(const std::string &sFilePath, const + "\r\n"; if (m_bClosed) { - WSJCppLog::warn(TAG, "Already sended response"); + WsjcppLog::warn(TAG, "Already sended response"); // delete[] pData; return; } diff --git a/src/wsjcpp_light_web_http_response.h b/src/wsjcpp_light_web_http_response.h index 624815d..025f415 100644 --- a/src/wsjcpp_light_web_http_response.h +++ b/src/wsjcpp_light_web_http_response.h @@ -7,23 +7,23 @@ // --------------------------------------------------------------------- -class WSJCppLightWebHttpResponse { +class WsjcppLightWebHttpResponse { public: static std::map *g_mapReponseDescription; - WSJCppLightWebHttpResponse(int nSockFd); - - WSJCppLightWebHttpResponse &ok(); - WSJCppLightWebHttpResponse &badRequest(); - WSJCppLightWebHttpResponse &forbidden(); - WSJCppLightWebHttpResponse ¬Found(); - WSJCppLightWebHttpResponse &payloadTooLarge(); - WSJCppLightWebHttpResponse &internalServerError(); - WSJCppLightWebHttpResponse ¬Implemented(); - WSJCppLightWebHttpResponse &requestTimeout(); - - WSJCppLightWebHttpResponse &noCache(); - WSJCppLightWebHttpResponse &cacheSec(int nCacheSec); + WsjcppLightWebHttpResponse(int nSockFd); + + WsjcppLightWebHttpResponse &ok(); + WsjcppLightWebHttpResponse &badRequest(); + WsjcppLightWebHttpResponse &forbidden(); + WsjcppLightWebHttpResponse ¬Found(); + WsjcppLightWebHttpResponse &payloadTooLarge(); + WsjcppLightWebHttpResponse &internalServerError(); + WsjcppLightWebHttpResponse ¬Implemented(); + WsjcppLightWebHttpResponse &requestTimeout(); + + WsjcppLightWebHttpResponse &noCache(); + WsjcppLightWebHttpResponse &cacheSec(int nCacheSec); void sendText(const std::string &sBody); void sendJson(const nlohmann::json &json); diff --git a/src/wsjcpp_light_web_server.cpp b/src/wsjcpp_light_web_server.cpp index 843012c..14fae43 100644 --- a/src/wsjcpp_light_web_server.cpp +++ b/src/wsjcpp_light_web_server.cpp @@ -4,23 +4,23 @@ #include // --------------------------------------------------------------------- -// WSJCppLightWebHttpHandlerBase +// WsjcppLightWebHttpHandlerBase -WSJCppLightWebHttpHandlerBase::WSJCppLightWebHttpHandlerBase(const std::string &sName) { +WsjcppLightWebHttpHandlerBase::WsjcppLightWebHttpHandlerBase(const std::string &sName) { m_sName = sName; } // --------------------------------------------------------------------- -const std::string &WSJCppLightWebHttpHandlerBase::name() { +const std::string &WsjcppLightWebHttpHandlerBase::name() { return m_sName; } // ---------------------------------------------------------------------- -// WSJCppLightWebHttpThreadWorker +// WsjcppLightWebHttpThreadWorker void* processRequest(void *arg) { - WSJCppLightWebHttpThreadWorker *pWorker = (WSJCppLightWebHttpThreadWorker *)arg; + WsjcppLightWebHttpThreadWorker *pWorker = (WsjcppLightWebHttpThreadWorker *)arg; pthread_detach(pthread_self()); pWorker->run(); return 0; @@ -28,12 +28,12 @@ void* processRequest(void *arg) { // ---------------------------------------------------------------------- -WSJCppLightWebHttpThreadWorker::WSJCppLightWebHttpThreadWorker( +WsjcppLightWebHttpThreadWorker::WsjcppLightWebHttpThreadWorker( const std::string &sName, - WSJCppLightWebDequeHttpRequests *pDeque, - std::vector *pVHandlers + WsjcppLightWebDequeHttpRequests *pDeque, + std::vector *pVHandlers ) { - TAG = "WSJCppLightWebHttpThreadWorker-" + sName; + TAG = "WsjcppLightWebHttpThreadWorker-" + sName; m_pDeque = pDeque; m_bStop = false; m_bStopped = true; @@ -43,33 +43,33 @@ WSJCppLightWebHttpThreadWorker::WSJCppLightWebHttpThreadWorker( // ---------------------------------------------------------------------- -void WSJCppLightWebHttpThreadWorker::start() { +void WsjcppLightWebHttpThreadWorker::start() { m_bStop = false; m_bStopped = false; - WSJCppLog::info(TAG, "Start"); + WsjcppLog::info(TAG, "Start"); pthread_create(&m_serverThread, NULL, &processRequest, (void *)this); } // ---------------------------------------------------------------------- -void WSJCppLightWebHttpThreadWorker::stop() { +void WsjcppLightWebHttpThreadWorker::stop() { m_bStop = true; } // ---------------------------------------------------------------------- -void WSJCppLightWebHttpThreadWorker::run() { +void WsjcppLightWebHttpThreadWorker::run() { const int nMaxPackageSize = 4096; while (1) { if (m_bStop) { m_bStopped = true; return; } - WSJCppLightWebHttpRequest *pInfo = m_pDeque->popRequest(); + WsjcppLightWebHttpRequest *pInfo = m_pDeque->popRequest(); if (pInfo != nullptr) { int nSockFd = pInfo->getSockFd(); - WSJCppLog::info(TAG, "IP-address: " + pInfo->getAddress()); + WsjcppLog::info(TAG, "IP-address: " + pInfo->getAddress()); // set timeout options struct timeval timeout; @@ -77,7 +77,7 @@ void WSJCppLightWebHttpThreadWorker::run() { timeout.tv_usec = 0; setsockopt(nSockFd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); - WSJCppLightWebHttpResponse *pResponse = new WSJCppLightWebHttpResponse(nSockFd); + WsjcppLightWebHttpResponse *pResponse = new WsjcppLightWebHttpResponse(nSockFd); int n; // int newsockfd = (long)arg; char msg[nMaxPackageSize]; @@ -102,7 +102,7 @@ void WSJCppLightWebHttpThreadWorker::run() { //close(nSockFd); break; } - WSJCppLog::info(TAG, "Readed " + std::to_string(n) + " bytes..."); + WsjcppLog::info(TAG, "Readed " + std::to_string(n) + " bytes..."); msg[n] = 0; sRequest = std::string(msg); @@ -117,7 +117,7 @@ void WSJCppLightWebHttpThreadWorker::run() { } // TODO read and replace X-Forwarded-IP // TODO read and replace X-Forwarded-Host - WSJCppLog::info(TAG, "\nRequest: \n>>>\n" + sRequest + "\n<<<"); + WsjcppLog::info(TAG, "\nRequest: \n>>>\n" + sRequest + "\n<<<"); if (bErrorRead) { pResponse->requestTimeout().noCache().sendText( "

408 Request Time-out

" @@ -133,7 +133,7 @@ void WSJCppLightWebHttpThreadWorker::run() { pResponse->notFound().sendEmpty(); } else { // TODO resp internal error - // this->response(WSJCppLightWebHttpResponse::RESP_INTERNAL_SERVER_ERROR); + // this->response(WsjcppLightWebHttpResponse::RESP_INTERNAL_SERVER_ERROR); } } delete pInfo; @@ -149,15 +149,15 @@ void WSJCppLightWebHttpThreadWorker::run() { // ---------------------------------------------------------------------- -bool WSJCppLightWebHttpThreadWorker::handle(WSJCppLightWebHttpRequest *pRequest) { - std::vector::iterator it; +bool WsjcppLightWebHttpThreadWorker::handle(WsjcppLightWebHttpRequest *pRequest) { + std::vector::iterator it; for (it = m_pVHandlers->begin(); it < m_pVHandlers->end(); it++) { - WSJCppLightWebHttpHandlerBase *pHandler = *it; + WsjcppLightWebHttpHandlerBase *pHandler = *it; if (pHandler->canHandle(m_sName, pRequest)) { if (pHandler->handle(m_sName, pRequest)) { return true; } else { - WSJCppLog::warn(TAG, pHandler->name() + " - could not handle request '" + pRequest->getRequestPath() + "'"); + WsjcppLog::warn(TAG, pHandler->name() + " - could not handle request '" + pRequest->getRequestPath() + "'"); } } } @@ -165,52 +165,52 @@ bool WSJCppLightWebHttpThreadWorker::handle(WSJCppLightWebHttpRequest *pRequest) } // ---------------------------------------------------------------------- -// WSJCppLightWebServer +// WsjcppLightWebServer -WSJCppLightWebServer::WSJCppLightWebServer() { - TAG = "WSJCppLightWebServer"; +WsjcppLightWebServer::WsjcppLightWebServer() { + TAG = "WsjcppLightWebServer"; m_nMaxWorkers = 4; - m_pDeque = new WSJCppLightWebDequeHttpRequests(); - m_pVHandlers = new std::vector(); + m_pDeque = new WsjcppLightWebDequeHttpRequests(); + m_pVHandlers = new std::vector(); m_bStop = false; m_nPort = 8080; } // ---------------------------------------------------------------------- -void WSJCppLightWebServer::setPort(int nPort) { +void WsjcppLightWebServer::setPort(int nPort) { // TODO use a port validators if (nPort > 10 && nPort < 65536) { m_nPort = nPort; } else { - WSJCppLog::throw_err(TAG, "Port must be 10...65535"); + WsjcppLog::throw_err(TAG, "Port must be 10...65535"); } m_nPort = nPort; } // ---------------------------------------------------------------------- -void WSJCppLightWebServer::setMaxWorkers(int nMaxWorkers) { +void WsjcppLightWebServer::setMaxWorkers(int nMaxWorkers) { // TODO number validator if (nMaxWorkers > 0 && nMaxWorkers <= 100) { m_nMaxWorkers = nMaxWorkers; } else { - WSJCppLog::warn(TAG, "Max workers must be 1...100"); + WsjcppLog::warn(TAG, "Max workers must be 1...100"); } } // ---------------------------------------------------------------------- -void WSJCppLightWebServer::startSync() { +void WsjcppLightWebServer::startSync() { m_nSockFd = socket(AF_INET, SOCK_STREAM, 0); if (m_nSockFd <= 0) { - WSJCppLog::err(TAG, "Failed to establish socket connection"); + WsjcppLog::err(TAG, "Failed to establish socket connection"); return; } int enable = 1; if (setsockopt(m_nSockFd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) { - WSJCppLog::err(TAG, "setsockopt(SO_REUSEADDR) failed"); + WsjcppLog::err(TAG, "setsockopt(SO_REUSEADDR) failed"); return; } @@ -219,11 +219,11 @@ void WSJCppLightWebServer::startSync() { m_serverAddress.sin_addr.s_addr = htonl(INADDR_ANY); m_serverAddress.sin_port = htons(m_nPort); if (bind(m_nSockFd, (struct sockaddr *)&m_serverAddress, sizeof(m_serverAddress)) == -1) { - WSJCppLog::err(TAG, "Error binding to port " + std::to_string(m_nPort)); + WsjcppLog::err(TAG, "Error binding to port " + std::to_string(m_nPort)); return; } listen(m_nSockFd, 5); - WSJCppLog::info("LightHttpServer", "Light Http Server started on " + std::to_string(m_nPort) + " port."); + WsjcppLog::info("LightHttpServer", "Light Http Server started on " + std::to_string(m_nPort) + " port."); std::string str; m_bStop = false; @@ -233,8 +233,8 @@ void WSJCppLightWebServer::startSync() { socklen_t sosize = sizeof(clientAddress); int nSockFd = accept(m_nSockFd,(struct sockaddr*)&clientAddress,&sosize); std::string sAddress = inet_ntoa(clientAddress.sin_addr); - WSJCppLog::info(TAG, "Connected " + sAddress); - WSJCppLightWebHttpRequest *pInfo = new WSJCppLightWebHttpRequest(nSockFd, sAddress); + WsjcppLog::info(TAG, "Connected " + sAddress); + WsjcppLightWebHttpRequest *pInfo = new WsjcppLightWebHttpRequest(nSockFd, sAddress); // info will be removed inside a thread m_pDeque->pushRequest(pInfo); // here will be unlocked workers // this->checkAndRestartWorkers(); @@ -251,7 +251,7 @@ void WSJCppLightWebServer::startSync() { // ---------------------------------------------------------------------- void* processWebServerStart(void *arg) { - WSJCppLightWebServer *pLightWebServer = (WSJCppLightWebServer *)arg; + WsjcppLightWebServer *pLightWebServer = (WsjcppLightWebServer *)arg; pthread_detach(pthread_self()); pLightWebServer->startSync(); return 0; @@ -259,36 +259,36 @@ void* processWebServerStart(void *arg) { // ---------------------------------------------------------------------- -void WSJCppLightWebServer::start() { +void WsjcppLightWebServer::start() { m_bStop = false; pthread_create(&m_serverThread, NULL, &processWebServerStart, (void *)this); } // ---------------------------------------------------------------------- -void WSJCppLightWebServer::stop() { +void WsjcppLightWebServer::stop() { m_bStop = true; } // ---------------------------------------------------------------------- -void WSJCppLightWebServer::addHandler(WSJCppLightWebHttpHandlerBase *pHandler) { +void WsjcppLightWebServer::addHandler(WsjcppLightWebHttpHandlerBase *pHandler) { m_pVHandlers->push_back(pHandler); } // ---------------------------------------------------------------------- -void WSJCppLightWebServer::checkAndRestartWorkers() { +void WsjcppLightWebServer::checkAndRestartWorkers() { if (!m_bStop) { if (m_vWorkers.size() < m_nMaxWorkers) { int nSize = m_vWorkers.size(); for (int i = nSize; i < m_nMaxWorkers; i++) { - m_vWorkers.push_back(new WSJCppLightWebHttpThreadWorker("worker" + std::to_string(i), m_pDeque, m_pVHandlers)); + m_vWorkers.push_back(new WsjcppLightWebHttpThreadWorker("worker" + std::to_string(i), m_pDeque, m_pVHandlers)); } } for (int i = 0; i < m_vWorkers.size(); i++) { - WSJCppLightWebHttpThreadWorker *pWorker = m_vWorkers[i]; + WsjcppLightWebHttpThreadWorker *pWorker = m_vWorkers[i]; pWorker->start(); } } @@ -296,7 +296,7 @@ void WSJCppLightWebServer::checkAndRestartWorkers() { // ---------------------------------------------------------------------- -void WSJCppLightWebServer::stopAndRemoveWorkers() { +void WsjcppLightWebServer::stopAndRemoveWorkers() { if (m_bStop) { for (int i = 0; i < m_vWorkers.size(); i++) { m_vWorkers[i]->stop(); @@ -308,7 +308,7 @@ void WSJCppLightWebServer::stopAndRemoveWorkers() { // ---------------------------------------------------------------------- -std::string WSJCppLightWebServer::readAddress(int nSockFd) { +std::string WsjcppLightWebServer::readAddress(int nSockFd) { struct sockaddr_in addr; socklen_t addr_size = sizeof(struct sockaddr_in); int res = getpeername(nSockFd, (struct sockaddr *)&addr, &addr_size); diff --git a/src/wsjcpp_light_web_server.h b/src/wsjcpp_light_web_server.h index 866968f..6a96940 100644 --- a/src/wsjcpp_light_web_server.h +++ b/src/wsjcpp_light_web_server.h @@ -11,12 +11,12 @@ // --------------------------------------------------------------------- -class WSJCppLightWebHttpHandlerBase { +class WsjcppLightWebHttpHandlerBase { public: - WSJCppLightWebHttpHandlerBase(const std::string &sName); + WsjcppLightWebHttpHandlerBase(const std::string &sName); const std::string &name(); - virtual bool canHandle(const std::string &sWorkerId, WSJCppLightWebHttpRequest *pRequest) = 0; - virtual bool handle(const std::string &sWorkerId, WSJCppLightWebHttpRequest *pRequest) = 0; + virtual bool canHandle(const std::string &sWorkerId, WsjcppLightWebHttpRequest *pRequest) = 0; + virtual bool handle(const std::string &sWorkerId, WsjcppLightWebHttpRequest *pRequest) = 0; private: std::string m_sName; @@ -24,13 +24,13 @@ class WSJCppLightWebHttpHandlerBase { // --------------------------------------------------------------------- -class WSJCppLightWebHttpThreadWorker { +class WsjcppLightWebHttpThreadWorker { public: - WSJCppLightWebHttpThreadWorker( + WsjcppLightWebHttpThreadWorker( const std::string &sName, - WSJCppLightWebDequeHttpRequests *pDeque, - std::vector *pVHandlers + WsjcppLightWebDequeHttpRequests *pDeque, + std::vector *pVHandlers ); void start(); @@ -38,11 +38,11 @@ class WSJCppLightWebHttpThreadWorker { void run(); private: - bool handle(WSJCppLightWebHttpRequest *pRequest); + bool handle(WsjcppLightWebHttpRequest *pRequest); std::string TAG; std::string m_sName; - WSJCppLightWebDequeHttpRequests *m_pDeque; - std::vector *m_pVHandlers; + WsjcppLightWebDequeHttpRequests *m_pDeque; + std::vector *m_pVHandlers; bool m_bStop; bool m_bStopped; pthread_t m_serverThread; @@ -50,29 +50,29 @@ class WSJCppLightWebHttpThreadWorker { // --------------------------------------------------------------------- -class WSJCppLightWebServer { +class WsjcppLightWebServer { public: - WSJCppLightWebServer(); + WsjcppLightWebServer(); void setPort(int nPort); void setMaxWorkers(int nMaxWorkers); void startSync(); void start(); void stop(); - void addHandler(WSJCppLightWebHttpHandlerBase *pHandler); + void addHandler(WsjcppLightWebHttpHandlerBase *pHandler); private: void checkAndRestartWorkers(); void stopAndRemoveWorkers(); std::string readAddress(int nSockFd); std::string TAG; - WSJCppLightWebDequeHttpRequests *m_pDeque; + WsjcppLightWebDequeHttpRequests *m_pDeque; bool m_bStop; int m_nMaxWorkers; int m_nPort; - std::vector *m_pVHandlers; - std::vector m_vWorkers; + std::vector *m_pVHandlers; + std::vector m_vWorkers; int m_nSockFd; struct sockaddr_in m_serverAddress; diff --git a/unit-tests.wsjcpp/CMakeLists.txt b/unit-tests.wsjcpp/CMakeLists.txt index cf4c86e..22ba6d4 100644 --- a/unit-tests.wsjcpp/CMakeLists.txt +++ b/unit-tests.wsjcpp/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.0) project(unit-tests C CXX) -add_definitions(-DWSJCPP_VERSION="ut-v0.0.1") +add_definitions(-DWSJCPP_VERSION="ut-v0.1.0") add_definitions(-DWSJCPP_NAME="unit-tests-wsjcpp-light-web-server") if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin") @@ -19,7 +19,7 @@ set (WSJCPP_SOURCES "") find_package(Threads REQUIRED) list (APPEND WSJCPP_LIBRARIES ${CMAKE_THREAD_LIBS_INIT}) -# wsjcpp-core:v0.0.7 +# wsjcpp-core:v0.1.1 list (APPEND WSJCPP_INCLUDE_DIRS "../src.wsjcpp/wsjcpp_core/") list (APPEND WSJCPP_SOURCES "../src.wsjcpp/wsjcpp_core/wsjcpp_core.cpp") list (APPEND WSJCPP_SOURCES "../src.wsjcpp/wsjcpp_core/wsjcpp_core.h") @@ -31,7 +31,7 @@ list (APPEND WSJCPP_SOURCES "../src.wsjcpp/wsjcpp_core/wsjcpp_unit_tests_main.cp list (APPEND WSJCPP_INCLUDE_DIRS "../src.wsjcpp/nlohmann_json/") list (APPEND WSJCPP_SOURCES "../src.wsjcpp/nlohmann_json/json.hpp") -# wsjcpp-light-web-server:v0.0.1 +# wsjcpp-light-web-server:v0.1.0 list (APPEND WSJCPP_INCLUDE_DIRS "../src") list (APPEND WSJCPP_SOURCES "../src/wsjcpp_light_web_http_request.h") list (APPEND WSJCPP_SOURCES "../src/wsjcpp_light_web_http_request.cpp") diff --git a/unit-tests.wsjcpp/src/unit_test_parse_http_request.cpp b/unit-tests.wsjcpp/src/unit_test_parse_http_request.cpp index 3221336..3480a27 100644 --- a/unit-tests.wsjcpp/src/unit_test_parse_http_request.cpp +++ b/unit-tests.wsjcpp/src/unit_test_parse_http_request.cpp @@ -3,10 +3,10 @@ #include #include -REGISTRY_UNIT_TEST(UnitTestParseHttpRequest) +REGISTRY_WSJCPP_UNIT_TEST(UnitTestParseHttpRequest) UnitTestParseHttpRequest::UnitTestParseHttpRequest() - : WSJCppUnitTestBase("UnitTestParseHttpRequest") { + : WsjcppUnitTestBase("UnitTestParseHttpRequest") { } // --------------------------------------------------------------------- @@ -111,7 +111,7 @@ bool UnitTestParseHttpRequest::run() { for (int i = 0; i < tests.size(); i++) { LTest test = tests[i]; - WSJCppLightWebHttpRequest request(test.sockFd, test.address); + WsjcppLightWebHttpRequest request(test.sockFd, test.address); std::string sNTest = "test" + std::to_string(i) + "#"; compareS(bTestSuccess, sNTest + " request address", request.getAddress(), test.address); @@ -127,9 +127,9 @@ bool UnitTestParseHttpRequest::run() { compareS(bTestSuccess, sNTest + " request expected body", request.getRequestBody(), test.expectedBody); compareS(bTestSuccess, sNTest + " request expected body", request.getRequestHttpVersion(), test.expectedHttpVersion); - std::vector params = request.getRequestQueryParams(); + std::vector params = request.getRequestQueryParams(); for (int i = 0; i < params.size(); i++) { - WSJCppLightWebHttpRequestQueryValue qv = params[i]; + WsjcppLightWebHttpRequestQueryValue qv = params[i]; std::string sExpectedName = ""; std::string sExpectedValue = ""; if (i < test.expectedQueryParams.size()) { diff --git a/unit-tests.wsjcpp/src/unit_test_parse_http_request.h b/unit-tests.wsjcpp/src/unit_test_parse_http_request.h index 1d3a3c5..6836ab1 100644 --- a/unit-tests.wsjcpp/src/unit_test_parse_http_request.h +++ b/unit-tests.wsjcpp/src/unit_test_parse_http_request.h @@ -4,7 +4,7 @@ #include // Description: TODO -class UnitTestParseHttpRequest : public WSJCppUnitTestBase { +class UnitTestParseHttpRequest : public WsjcppUnitTestBase { public: UnitTestParseHttpRequest(); virtual void init(); diff --git a/wsjcpp.yml b/wsjcpp.yml index 0886f15..164ebc8 100644 --- a/wsjcpp.yml +++ b/wsjcpp.yml @@ -1,5 +1,5 @@ name: "wsjcpp-light-web-server" -version: "v0.0.2" +version: "v0.1.0" cmake_minimum_required: "3.0" cmake_cxx_standard: "11" description: "C++ Light Web Server (Only GET)" @@ -19,7 +19,7 @@ keywords: dependencies: - name: "wsjcpp-core" - version: "v0.0.7" + version: "v0.1.1" url: "https://github.com/wsjcpp/wsjcpp-core:master" origin: "https://github.com/" installation-dir: "./src.wsjcpp/wsjcpp_core"