From d5ede2277d849f1a9d2dc111c4ec3ea652bd31ec Mon Sep 17 00:00:00 2001 From: Peter Spiess-Knafl Date: Sat, 23 Oct 2021 13:09:46 +0200 Subject: [PATCH] Run clang-format over whole codebase --- .clang-format | 115 +++++++++ Makefile | 2 +- src/catch/CMakeLists.txt | 14 +- src/examples/CMakeLists.txt | 90 +++---- src/examples/filedescriptorserver.cpp | 15 +- src/examples/index.html | 59 ++--- src/examples/redisserver.cpp | 12 +- src/examples/serialportserver.cpp | 15 +- src/examples/simpleserver.cpp | 12 +- src/examples/spec.json | 106 ++++---- src/examples/stubserver.cpp | 15 +- src/examples/tcpsocketserver.cpp | 12 +- src/examples/unixdomainsocketserver.cpp | 15 +- src/examples/xbmc_remote.json | 36 +-- src/examples/xbmcremote.cpp | 3 +- src/jsonrpccpp/CMakeLists.txt | 184 +++++++------- src/jsonrpccpp/client.h | 1 - src/jsonrpccpp/client/batchcall.cpp | 3 +- src/jsonrpccpp/client/batchcall.h | 38 ++- src/jsonrpccpp/client/batchresponse.cpp | 9 +- src/jsonrpccpp/client/batchresponse.h | 79 +++--- src/jsonrpccpp/client/client.cpp | 26 +- src/jsonrpccpp/client/client.h | 39 ++- .../connectors/filedescriptorclient.cpp | 20 +- .../client/connectors/filedescriptorclient.h | 22 +- .../client/connectors/httpclient.cpp | 21 +- src/jsonrpccpp/client/connectors/httpclient.h | 44 ++-- .../connectors/linuxserialportclient.cpp | 12 +- .../client/connectors/linuxserialportclient.h | 78 +++--- .../connectors/linuxtcpsocketclient.cpp | 32 +-- .../client/connectors/linuxtcpsocketclient.h | 112 +++++---- .../client/connectors/redisclient.cpp | 43 ++-- .../client/connectors/redisclient.h | 123 +++++----- .../client/connectors/streamreader.h | 6 +- .../client/connectors/tcpsocketclient.cpp | 6 +- .../client/connectors/tcpsocketclient.h | 68 +++--- .../connectors/unixdomainsocketclient.cpp | 21 +- .../connectors/unixdomainsocketclient.h | 20 +- .../connectors/windowstcpsocketclient.cpp | 42 +--- .../connectors/windowstcpsocketclient.h | 126 +++++----- src/jsonrpccpp/client/iclientconnector.h | 16 +- src/jsonrpccpp/client/rpcprotocolclient.cpp | 44 +--- src/jsonrpccpp/client/rpcprotocolclient.h | 109 ++++----- src/jsonrpccpp/common/errors.cpp | 20 +- src/jsonrpccpp/common/errors.h | 88 ++++--- src/jsonrpccpp/common/exception.cpp | 20 +- src/jsonrpccpp/common/exception.h | 52 ++-- src/jsonrpccpp/common/procedure.cpp | 50 ++-- src/jsonrpccpp/common/procedure.h | 193 +++++++-------- src/jsonrpccpp/common/sharedconstants.h | 6 +- src/jsonrpccpp/common/specification.h | 45 ++-- src/jsonrpccpp/common/specificationparser.cpp | 60 ++--- src/jsonrpccpp/common/specificationparser.h | 34 ++- src/jsonrpccpp/common/specificationwriter.cpp | 16 +- src/jsonrpccpp/common/specificationwriter.h | 21 +- src/jsonrpccpp/common/streamreader.cpp | 6 +- src/jsonrpccpp/common/streamreader.h | 15 +- src/jsonrpccpp/common/streamwriter.cpp | 3 +- src/jsonrpccpp/common/streamwriter.h | 12 +- src/jsonrpccpp/server.h | 3 +- .../server/abstractprotocolhandler.cpp | 34 +-- .../server/abstractprotocolhandler.h | 50 ++-- src/jsonrpccpp/server/abstractserver.h | 132 +++++----- .../server/abstractserverconnector.cpp | 11 +- .../server/abstractserverconnector.h | 52 ++-- .../server/abstractthreadedserver.cpp | 9 +- .../server/abstractthreadedserver.h | 76 +++--- .../connectors/filedescriptorserver.cpp | 6 +- .../server/connectors/filedescriptorserver.h | 66 ++--- .../server/connectors/httpserver.cpp | 79 ++---- src/jsonrpccpp/server/connectors/httpserver.h | 87 ++++--- .../connectors/linuxserialportserver.cpp | 6 +- .../server/connectors/linuxserialportserver.h | 60 +++-- .../connectors/linuxtcpsocketserver.cpp | 18 +- .../server/connectors/linuxtcpsocketserver.h | 117 +++++---- .../server/connectors/redisserver.cpp | 15 +- .../server/connectors/redisserver.h | 166 ++++++------- .../server/connectors/tcpsocketserver.cpp | 4 +- .../server/connectors/tcpsocketserver.h | 108 ++++----- .../connectors/unixdomainsocketserver.cpp | 14 +- .../connectors/unixdomainsocketserver.h | 38 +-- .../connectors/windowstcpsocketserver.cpp | 56 ++--- .../connectors/windowstcpsocketserver.h | 227 +++++++++--------- .../server/iclientconnectionhandler.h | 28 +-- .../server/iprocedureinvokationhandler.h | 20 +- .../server/requesthandlerfactory.cpp | 3 +- src/jsonrpccpp/server/requesthandlerfactory.h | 13 +- src/jsonrpccpp/server/rpcprotocolserver12.cpp | 20 +- src/jsonrpccpp/server/rpcprotocolserver12.h | 21 +- src/jsonrpccpp/server/rpcprotocolserverv1.cpp | 28 +-- src/jsonrpccpp/server/rpcprotocolserverv1.h | 26 +- src/jsonrpccpp/server/rpcprotocolserverv2.cpp | 51 ++-- src/jsonrpccpp/server/rpcprotocolserverv2.h | 45 ++-- src/jsonrpccpp/server/threadpool.h | 123 +++++----- src/stubgenerator/CMakeLists.txt | 46 ++-- .../client/cppclientstubgenerator.cpp | 36 +-- .../client/cppclientstubgenerator.h | 28 +-- .../client/jsclientstubgenerator.cpp | 33 +-- .../client/jsclientstubgenerator.h | 22 +- .../client/pyclientstubgenerator.cpp | 40 +-- .../client/pyclientstubgenerator.h | 42 ++-- src/stubgenerator/codegenerator.cpp | 11 +- src/stubgenerator/codegenerator.h | 46 ++-- src/stubgenerator/helper/cpphelper.cpp | 26 +- src/stubgenerator/helper/cpphelper.h | 53 ++-- src/stubgenerator/main.cpp | 3 +- .../server/cppserverstubgenerator.cpp | 103 +++----- .../server/cppserverstubgenerator.h | 30 ++- src/stubgenerator/servertemplate.h | 18 +- src/stubgenerator/stubgenerator.cpp | 20 +- src/stubgenerator/stubgenerator.h | 35 ++- src/stubgenerator/stubgeneratorfactory.cpp | 85 ++----- src/stubgenerator/stubgeneratorfactory.h | 14 +- src/stubgenerator/stubhelper.h | 1 - src/test/CMakeLists.txt | 80 +++--- src/test/checkexception.h | 12 +- src/test/mockclientconnectionhandler.cpp | 6 +- src/test/mockclientconnectionhandler.h | 23 +- src/test/mockclientconnector.cpp | 7 +- src/test/mockclientconnector.h | 23 +- src/test/mockserverconnector.h | 26 +- src/test/spec.json | 94 ++++---- src/test/test_client.cpp | 118 ++++----- src/test/test_common.cpp | 82 ++----- src/test/test_connector_filedescriptor.cpp | 67 +++--- src/test/test_connector_http.cpp | 43 ++-- src/test/test_connector_redis.cpp | 88 +++---- src/test/test_connector_tcpsocket.cpp | 31 ++- src/test/test_connector_unixdomainsocket.cpp | 35 ++- src/test/test_integration.cpp | 19 +- src/test/test_server.cpp | 62 ++--- src/test/test_stubgenerator.cpp | 128 ++++------ src/test/testhttpserver.cpp | 26 +- src/test/testhttpserver.h | 39 ++- src/test/testredisserver.cpp | 5 +- src/test/testredisserver.h | 102 ++++---- src/test/testserver.cpp | 70 ++---- src/test/testserver.h | 57 +++-- src/test/testspec1.json | 3 +- src/test/testspec2.json | 12 +- src/test/testspec3.json | 13 +- src/test/testspec4.json | 14 +- src/test/testspec5.json | 52 ++-- src/test/testspec6.json | 96 +++++--- 144 files changed, 2883 insertions(+), 3560 deletions(-) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000..8b96a9f3 --- /dev/null +++ b/.clang-format @@ -0,0 +1,115 @@ +Language: Cpp +# BasedOnStyle: LLVM +AccessModifierOffset: -2 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlines: Right +AlignOperands: true +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: Yes +BinPackArguments: true +BinPackParameters: true +BraceWrapping: + AfterClass: false + AfterControlStatement: false + AfterEnum: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Attach +BreakBeforeInheritanceComma: false +BreakInheritanceList: BeforeColon +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 160 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + - Regex: '.*' + Priority: 1 +IncludeIsMainRegex: '(Test)?$' +IndentCaseLabels: false +IndentPPDirectives: None +IndentWidth: 2 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: All +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Right +ReflowComments: true +SortIncludes: true +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Cpp11 +TabWidth: 2 +UseTab: Never \ No newline at end of file diff --git a/Makefile b/Makefile index 1eb36aa5..6a1c449c 100644 --- a/Makefile +++ b/Makefile @@ -13,7 +13,7 @@ coverage: test gcovr -r . -d -e "build" -e "src/test" -e "src/examples" -e "src/stubgenerator/main.cpp" --html --html-details -o reports/coverage.html format: - find . -name "*.h" -o -name "*.cpp" -exec clang-format -style=LLVM -i {} \; + find src/ -name "*.h" -o -name "*.cpp" -exec clang-format -i {} \; check-format: format git diff --exit-code diff --git a/src/catch/CMakeLists.txt b/src/catch/CMakeLists.txt index 5e928714..6da4c104 100644 --- a/src/catch/CMakeLists.txt +++ b/src/catch/CMakeLists.txt @@ -3,13 +3,13 @@ project(catch_builder CXX) include(ExternalProject) ExternalProject_Add( - catch - PREFIX ${CMAKE_BINARY_DIR}/catch - URL https://github.com/catchorg/Catch2/archive/v2.7.0.tar.gz - URL_HASH SHA1=6df37d5b64a71b840a6a9d8c79c3705aa8a3f56e - CONFIGURE_COMMAND "" - BUILD_COMMAND "" - INSTALL_COMMAND "" + catch + PREFIX ${CMAKE_BINARY_DIR}/catch + URL https://github.com/catchorg/Catch2/archive/v2.7.0.tar.gz + URL_HASH SHA1=6df37d5b64a71b840a6a9d8c79c3705aa8a3f56e + CONFIGURE_COMMAND "" + BUILD_COMMAND "" + INSTALL_COMMAND "" ) ExternalProject_Get_Property(catch source_dir) diff --git a/src/examples/CMakeLists.txt b/src/examples/CMakeLists.txt index 9a964d58..d344baad 100644 --- a/src/examples/CMakeLists.txt +++ b/src/examples/CMakeLists.txt @@ -1,101 +1,101 @@ file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/gen) add_custom_command( - OUTPUT ${CMAKE_BINARY_DIR}/gen/abstractstubserver.h - COMMAND jsonrpcstub ARGS ${CMAKE_CURRENT_SOURCE_DIR}/spec.json --cpp-server=AbstractStubServer --cpp-server-file=${CMAKE_BINARY_DIR}/gen/abstractstubserver.h - MAIN_DEPENDENCY spec.json - DEPENDS jsonrpcstub - COMMENT "Generating Server Stubfiles" - VERBATIM + OUTPUT ${CMAKE_BINARY_DIR}/gen/abstractstubserver.h + COMMAND jsonrpcstub ARGS ${CMAKE_CURRENT_SOURCE_DIR}/spec.json --cpp-server=AbstractStubServer --cpp-server-file=${CMAKE_BINARY_DIR}/gen/abstractstubserver.h + MAIN_DEPENDENCY spec.json + DEPENDS jsonrpcstub + COMMENT "Generating Server Stubfiles" + VERBATIM ) add_custom_command( - OUTPUT ${CMAKE_BINARY_DIR}/gen/stubclient.h - COMMAND jsonrpcstub ARGS ${CMAKE_CURRENT_SOURCE_DIR}/spec.json --cpp-client=StubClient --cpp-client-file=${CMAKE_BINARY_DIR}/gen/stubclient.h - MAIN_DEPENDENCY spec.json - DEPENDS jsonrpcstub - COMMENT "Generating Client Stubfile" - VERBATIM + OUTPUT ${CMAKE_BINARY_DIR}/gen/stubclient.h + COMMAND jsonrpcstub ARGS ${CMAKE_CURRENT_SOURCE_DIR}/spec.json --cpp-client=StubClient --cpp-client-file=${CMAKE_BINARY_DIR}/gen/stubclient.h + MAIN_DEPENDENCY spec.json + DEPENDS jsonrpcstub + COMMENT "Generating Client Stubfile" + VERBATIM ) add_custom_target(common_stubs - DEPENDS ${CMAKE_BINARY_DIR}/gen/abstractstubserver.h ${CMAKE_BINARY_DIR}/gen/stubclient.h -) + DEPENDS ${CMAKE_BINARY_DIR}/gen/abstractstubserver.h ${CMAKE_BINARY_DIR}/gen/stubclient.h + ) add_custom_command( - OUTPUT ${CMAKE_BINARY_DIR}/gen/xbmcremote.h - COMMAND jsonrpcstub ARGS ${CMAKE_CURRENT_SOURCE_DIR}/xbmc_remote.json --cpp-client=XbmcRemoteClient --cpp-client-file=${CMAKE_BINARY_DIR}/gen/xbmcremote.h - MAIN_DEPENDENCY xbmc_remote.json - DEPENDS jsonrpcstub - COMMENT "Generating Client XBMC Stubfile" - VERBATIM + OUTPUT ${CMAKE_BINARY_DIR}/gen/xbmcremote.h + COMMAND jsonrpcstub ARGS ${CMAKE_CURRENT_SOURCE_DIR}/xbmc_remote.json --cpp-client=XbmcRemoteClient --cpp-client-file=${CMAKE_BINARY_DIR}/gen/xbmcremote.h + MAIN_DEPENDENCY xbmc_remote.json + DEPENDS jsonrpcstub + COMMENT "Generating Client XBMC Stubfile" + VERBATIM ) include_directories(..) include_directories(${CMAKE_BINARY_DIR}) include_directories(${MHD_INCLUDE_DIRS}) -if(UNIX) - if(UNIX_DOMAIN_SOCKET_SERVER AND UNIX_DOMAIN_SOCKET_CLIENT) +if (UNIX) + if (UNIX_DOMAIN_SOCKET_SERVER AND UNIX_DOMAIN_SOCKET_CLIENT) add_executable(unixdomainsocketserversample unixdomainsocketserver.cpp) target_link_libraries(unixdomainsocketserversample jsonrpcserver) add_executable(unixdomainsocketclientsample unixdomainsocketclient.cpp) target_link_libraries(unixdomainsocketclientsample jsonrpcclient) - endif() + endif () - if(FILE_DESCRIPTOR_SERVER AND FILE_DESCRIPTOR_CLIENT) - add_executable(filedescriptorserversample filedescriptorserver.cpp) - target_link_libraries(filedescriptorserversample jsonrpcserver) - add_executable(filedescriptorclientsample filedescriptorclient.cpp) - target_link_libraries(filedescriptorclientsample jsonrpcclient) - endif() -endif(UNIX) + if (FILE_DESCRIPTOR_SERVER AND FILE_DESCRIPTOR_CLIENT) + add_executable(filedescriptorserversample filedescriptorserver.cpp) + target_link_libraries(filedescriptorserversample jsonrpcserver) + add_executable(filedescriptorclientsample filedescriptorclient.cpp) + target_link_libraries(filedescriptorclientsample jsonrpcclient) + endif () +endif (UNIX) if (TCP_SOCKET_SERVER AND TCP_SOCKET_CLIENT) add_executable(tcpsocketclient tcpsocketclient.cpp) target_link_libraries(tcpsocketclient jsonrpcclient) add_executable(tcpsocketserver tcpsocketserver.cpp) target_link_libraries(tcpsocketserver jsonrpcserver) -endif() +endif () if (SERIAL_PORT_SERVER AND SERIAL_PORT_CLIENT) add_executable(serialportclient serialportclient.cpp) target_link_libraries(serialportclient jsonrpcclient) add_executable(serialportserver serialportserver.cpp) target_link_libraries(serialportserver jsonrpcserver) -endif() +endif () -if(HTTP_SERVER) +if (HTTP_SERVER) add_executable(simpleserversample simpleserver.cpp) target_link_libraries(simpleserversample jsonrpcserver) -endif() +endif () -if(HTTP_CLIENT) +if (HTTP_CLIENT) add_executable(simpleclientsample simpleclient.cpp) target_link_libraries(simpleclientsample jsonrpcclient) -endif() +endif () -if(REDIS_SERVER) +if (REDIS_SERVER) add_executable(redisserversample redisserver.cpp) target_link_libraries(redisserversample jsonrpcserver) -endif() +endif () -if(REDIS_CLIENT) +if (REDIS_CLIENT) add_executable(redisclientsample redisclient.cpp) target_link_libraries(redisclientsample jsonrpcclient) -endif() +endif () if (COMPILE_STUBGEN) - if(HTTP_CLIENT) + if (HTTP_CLIENT) add_executable(stubclientsample stubclient.cpp ${CMAKE_BINARY_DIR}/gen/stubclient.h) target_link_libraries(stubclientsample jsonrpcclient) add_executable(xbmcremote xbmcremote.cpp ${CMAKE_BINARY_DIR}/gen/xbmcremote.h) target_link_libraries(xbmcremote jsonrpcclient) - endif() + endif () - if(HTTP_SERVER) + if (HTTP_SERVER) add_executable(stubserversample stubserver.cpp ${CMAKE_BINARY_DIR}/gen/abstractstubserver.h) target_link_libraries(stubserversample jsonrpcserver) - endif() -endif() + endif () +endif () diff --git a/src/examples/filedescriptorserver.cpp b/src/examples/filedescriptorserver.cpp index a897063d..fae9d2e0 100644 --- a/src/examples/filedescriptorserver.cpp +++ b/src/examples/filedescriptorserver.cpp @@ -43,20 +43,13 @@ using namespace std; class SampleServer : public AbstractServer { public: - SampleServer(FileDescriptorServer &server) - : AbstractServer(server) { - this->bindAndAddMethod(Procedure("sayHello", PARAMS_BY_NAME, JSON_STRING, - "name", JSON_STRING, NULL), - &SampleServer::sayHello); - this->bindAndAddNotification( - Procedure("notifyServer", PARAMS_BY_NAME, NULL), - &SampleServer::notifyServer); + SampleServer(FileDescriptorServer &server) : AbstractServer(server) { + this->bindAndAddMethod(Procedure("sayHello", PARAMS_BY_NAME, JSON_STRING, "name", JSON_STRING, NULL), &SampleServer::sayHello); + this->bindAndAddNotification(Procedure("notifyServer", PARAMS_BY_NAME, NULL), &SampleServer::notifyServer); } // method - void sayHello(const Json::Value &request, Json::Value &response) { - response = "Hello: " + request["name"].asString(); - } + void sayHello(const Json::Value &request, Json::Value &response) { response = "Hello: " + request["name"].asString(); } // notification void notifyServer(const Json::Value &request) { diff --git a/src/examples/index.html b/src/examples/index.html index c235c990..10b55832 100644 --- a/src/examples/index.html +++ b/src/examples/index.html @@ -1,38 +1,39 @@ - + - -Title of the document - - - - + + + + client.sayHello("Peter", showResult, showError); + client.addNumbers(3, 4, showResult, showError); + client.isEqual("3", "3", showResult, showError); + client.isEqual("3", 4, showResult, showError); //invalid params error + client.notifyServer(); + }); + + function displayResult(result) { + alert(JSON.stringify(result)); + } + diff --git a/src/examples/redisserver.cpp b/src/examples/redisserver.cpp index 9fc7f8c3..b106ad6d 100644 --- a/src/examples/redisserver.cpp +++ b/src/examples/redisserver.cpp @@ -17,18 +17,12 @@ using namespace std; class SampleServer : public AbstractServer { public: SampleServer(RedisServer &server) : AbstractServer(server) { - this->bindAndAddMethod(Procedure("sayHello", PARAMS_BY_NAME, JSON_STRING, - "name", JSON_STRING, NULL), - &SampleServer::sayHello); - this->bindAndAddNotification( - Procedure("notifyServer", PARAMS_BY_NAME, NULL), - &SampleServer::notifyServer); + this->bindAndAddMethod(Procedure("sayHello", PARAMS_BY_NAME, JSON_STRING, "name", JSON_STRING, NULL), &SampleServer::sayHello); + this->bindAndAddNotification(Procedure("notifyServer", PARAMS_BY_NAME, NULL), &SampleServer::notifyServer); } // method - void sayHello(const Json::Value &request, Json::Value &response) { - response = "Hello: " + request["name"].asString(); - } + void sayHello(const Json::Value &request, Json::Value &response) { response = "Hello: " + request["name"].asString(); } // notification void notifyServer(const Json::Value &request) { diff --git a/src/examples/serialportserver.cpp b/src/examples/serialportserver.cpp index 360121d6..061bb26e 100644 --- a/src/examples/serialportserver.cpp +++ b/src/examples/serialportserver.cpp @@ -17,20 +17,13 @@ using namespace std; class SampleServer : public AbstractServer { public: - SampleServer(LinuxSerialPortServer &server) - : AbstractServer(server) { - this->bindAndAddMethod(Procedure("sayHello", PARAMS_BY_NAME, JSON_STRING, - "name", JSON_STRING, NULL), - &SampleServer::sayHello); - this->bindAndAddNotification( - Procedure("notifyServer", PARAMS_BY_NAME, NULL), - &SampleServer::notifyServer); + SampleServer(LinuxSerialPortServer &server) : AbstractServer(server) { + this->bindAndAddMethod(Procedure("sayHello", PARAMS_BY_NAME, JSON_STRING, "name", JSON_STRING, NULL), &SampleServer::sayHello); + this->bindAndAddNotification(Procedure("notifyServer", PARAMS_BY_NAME, NULL), &SampleServer::notifyServer); } // method - void sayHello(const Json::Value &request, Json::Value &response) { - response = "Hello: " + request["name"].asString(); - } + void sayHello(const Json::Value &request, Json::Value &response) { response = "Hello: " + request["name"].asString(); } // notification void notifyServer(const Json::Value &request) { diff --git a/src/examples/simpleserver.cpp b/src/examples/simpleserver.cpp index 5cfb104b..43de2a53 100644 --- a/src/examples/simpleserver.cpp +++ b/src/examples/simpleserver.cpp @@ -17,18 +17,12 @@ using namespace std; class SampleServer : public AbstractServer { public: SampleServer(HttpServer &server) : AbstractServer(server) { - this->bindAndAddMethod(Procedure("sayHello", PARAMS_BY_NAME, JSON_STRING, - "name", JSON_STRING, NULL), - &SampleServer::sayHello); - this->bindAndAddNotification( - Procedure("notifyServer", PARAMS_BY_NAME, NULL), - &SampleServer::notifyServer); + this->bindAndAddMethod(Procedure("sayHello", PARAMS_BY_NAME, JSON_STRING, "name", JSON_STRING, NULL), &SampleServer::sayHello); + this->bindAndAddNotification(Procedure("notifyServer", PARAMS_BY_NAME, NULL), &SampleServer::notifyServer); } // method - void sayHello(const Json::Value &request, Json::Value &response) { - response = "Hello: " + request["name"].asString(); - } + void sayHello(const Json::Value &request, Json::Value &response) { response = "Hello: " + request["name"].asString(); } // notification void notifyServer(const Json::Value &request) { diff --git a/src/examples/spec.json b/src/examples/spec.json index 9e57396b..065b46e1 100644 --- a/src/examples/spec.json +++ b/src/examples/spec.json @@ -1,58 +1,58 @@ [ - { - "name": "sayHello", - "params": { - "name": "Peter" - }, - "returns": "Hello Peter" + { + "name": "sayHello", + "params": { + "name": "Peter" }, - { - "name": "notifyServer" + "returns": "Hello Peter" + }, + { + "name": "notifyServer" + }, + { + "name": "addNumbers", + "params": [ + 3, + 4 + ], + "returns": 7 + }, + { + "name": "addNumbers2", + "params": [ + 3.2, + 4.1 + ], + "returns": 7.5 + }, + { + "name": "calculate", + "params": { + "args": {} }, - { - "name": "addNumbers", - "params": [ - 3, - 4 - ], - "returns": 7 - }, - { - "name": "addNumbers2", - "params": [ - 3.2, - 4.1 - ], - "returns": 7.5 - }, - { - "name": "calculate", - "params": { - "args": {} - }, - "returns": [] - }, - { - "name": "isEqual", - "params": [ - "string1", - "string2" - ], - "returns": false - }, - { - "name": "buildObject", - "params": [ - "peter", - 1990 - ], - "returns": { - "name": "peter", - "year": 1990 - } - }, - { - "name" : "methodWithoutParameters", - "returns": "String" + "returns": [] + }, + { + "name": "isEqual", + "params": [ + "string1", + "string2" + ], + "returns": false + }, + { + "name": "buildObject", + "params": [ + "peter", + 1990 + ], + "returns": { + "name": "peter", + "year": 1990 } + }, + { + "name": "methodWithoutParameters", + "returns": "String" + } ] \ No newline at end of file diff --git a/src/examples/stubserver.cpp b/src/examples/stubserver.cpp index 38a85787..17ae34ce 100644 --- a/src/examples/stubserver.cpp +++ b/src/examples/stubserver.cpp @@ -29,9 +29,7 @@ class MyStubServer : public AbstractStubServer { virtual std::string methodWithoutParameters(); }; -MyStubServer::MyStubServer(AbstractServerConnector &connector, - serverVersion_t type) - : AbstractStubServer(connector, type) {} +MyStubServer::MyStubServer(AbstractServerConnector &connector, serverVersion_t type) : AbstractStubServer(connector, type) {} void MyStubServer::notifyServer() { cout << "Server got notified" << endl; } @@ -43,18 +41,13 @@ string MyStubServer::sayHello(const string &name) { int MyStubServer::addNumbers(int param1, int param2) { return param1 + param2; } -double MyStubServer::addNumbers2(double param1, double param2) { - return param1 + param2; -} +double MyStubServer::addNumbers2(double param1, double param2) { return param1 + param2; } -bool MyStubServer::isEqual(const string &str1, const string &str2) { - return str1 == str2; -} +bool MyStubServer::isEqual(const string &str1, const string &str2) { return str1 == str2; } Json::Value MyStubServer::calculate(const Json::Value &args) { Json::Value result; - if ((args.isMember("arg1") && args["arg1"].isInt()) && - (args.isMember("arg2") && args["arg2"].isInt()) && + if ((args.isMember("arg1") && args["arg1"].isInt()) && (args.isMember("arg2") && args["arg2"].isInt()) && (args.isMember("operator") && args["operator"].isString())) { int calculated = 0; diff --git a/src/examples/tcpsocketserver.cpp b/src/examples/tcpsocketserver.cpp index 70f0ce07..e16690ed 100644 --- a/src/examples/tcpsocketserver.cpp +++ b/src/examples/tcpsocketserver.cpp @@ -18,18 +18,12 @@ using namespace std; class SampleServer : public AbstractServer { public: SampleServer(TcpSocketServer &server) : AbstractServer(server) { - this->bindAndAddMethod(Procedure("sayHello", PARAMS_BY_NAME, JSON_STRING, - "name", JSON_STRING, NULL), - &SampleServer::sayHello); - this->bindAndAddNotification( - Procedure("notifyServer", PARAMS_BY_NAME, NULL), - &SampleServer::notifyServer); + this->bindAndAddMethod(Procedure("sayHello", PARAMS_BY_NAME, JSON_STRING, "name", JSON_STRING, NULL), &SampleServer::sayHello); + this->bindAndAddNotification(Procedure("notifyServer", PARAMS_BY_NAME, NULL), &SampleServer::notifyServer); } // method - void sayHello(const Json::Value &request, Json::Value &response) { - response = "Hello: " + request["name"].asString(); - } + void sayHello(const Json::Value &request, Json::Value &response) { response = "Hello: " + request["name"].asString(); } // notification void notifyServer(const Json::Value &request) { diff --git a/src/examples/unixdomainsocketserver.cpp b/src/examples/unixdomainsocketserver.cpp index 94a3cfe2..879f221c 100644 --- a/src/examples/unixdomainsocketserver.cpp +++ b/src/examples/unixdomainsocketserver.cpp @@ -16,20 +16,13 @@ using namespace std; class SampleServer : public AbstractServer { public: - SampleServer(UnixDomainSocketServer &server) - : AbstractServer(server) { - this->bindAndAddMethod(Procedure("sayHello", PARAMS_BY_NAME, JSON_STRING, - "name", JSON_STRING, NULL), - &SampleServer::sayHello); - this->bindAndAddNotification( - Procedure("notifyServer", PARAMS_BY_NAME, NULL), - &SampleServer::notifyServer); + SampleServer(UnixDomainSocketServer &server) : AbstractServer(server) { + this->bindAndAddMethod(Procedure("sayHello", PARAMS_BY_NAME, JSON_STRING, "name", JSON_STRING, NULL), &SampleServer::sayHello); + this->bindAndAddNotification(Procedure("notifyServer", PARAMS_BY_NAME, NULL), &SampleServer::notifyServer); } // method - void sayHello(const Json::Value &request, Json::Value &response) { - response = "Hello: " + request["name"].asString(); - } + void sayHello(const Json::Value &request, Json::Value &response) { response = "Hello: " + request["name"].asString(); } // notification void notifyServer(const Json::Value &request) { diff --git a/src/examples/xbmc_remote.json b/src/examples/xbmc_remote.json index 79116a78..45b602ad 100644 --- a/src/examples/xbmc_remote.json +++ b/src/examples/xbmc_remote.json @@ -1,26 +1,26 @@ [ -{ + { "name": "Input.Left", - "returns": "string" -}, -{ + "returns": "string" + }, + { "name": "Input.Right", - "returns": "string" -}, -{ + "returns": "string" + }, + { "name": "Input.Up", - "returns": "string" -}, -{ + "returns": "string" + }, + { "name": "Input.Down", - "returns": "string" -}, -{ + "returns": "string" + }, + { "name": "Input.Back", - "returns": "string" -}, -{ + "returns": "string" + }, + { "name": "Input.Select", - "returns": "string" -} + "returns": "string" + } ] diff --git a/src/examples/xbmcremote.cpp b/src/examples/xbmcremote.cpp index 8a7df755..f71b9458 100644 --- a/src/examples/xbmcremote.cpp +++ b/src/examples/xbmcremote.cpp @@ -52,8 +52,7 @@ int kbhit() { int main(int argc, char **argv) { if (argc < 2) { - cerr << "Provide XBMC API URL as argument! e.g.: " << argv[0] - << " http://127.0.0.1:8080/jsonrpc" << endl; + cerr << "Provide XBMC API URL as argument! e.g.: " << argv[0] << " http://127.0.0.1:8080/jsonrpc" << endl; return -1; } else { cout << "XBMC Remote control" << endl; diff --git a/src/jsonrpccpp/CMakeLists.txt b/src/jsonrpccpp/CMakeLists.txt index 66e5a258..2d047d70 100644 --- a/src/jsonrpccpp/CMakeLists.txt +++ b/src/jsonrpccpp/CMakeLists.txt @@ -5,51 +5,51 @@ file(GLOB jsonrpc_source_common common/*.c*) # setup server headers and sources file(GLOB jsonrpc_install_header_server - server/requesthandlerfactory.h - server/abstractserver.h - server/abstractserverconnector.h + server/requesthandlerfactory.h + server/abstractserver.h + server/abstractserverconnector.h server/abstractthreadedserver.h - server/iprocedureinvokationhandler.h - server/iclientconnectionhandler.h + server/iprocedureinvokationhandler.h + server/iclientconnectionhandler.h server/threadpool.h -) + ) file(GLOB jsonrpc_header_server server/*.h) file(GLOB jsonrpc_source_server server/*.c*) # setup client headers and sources file(GLOB jsonrpc_install_header_client - client/batchcall.h - client/batchresponse.h - client/client.h - client/iclientconnector.h -) + client/batchcall.h + client/batchresponse.h + client/client.h + client/iclientconnector.h + ) file(GLOB jsonrpc_header_client client/*.h) file(GLOB jsonrpc_source_client client/*.c*) # setup connector variables defaults set(client_connector_source "") set(client_connector_header "") -set(client_connector_libs "") +set(client_connector_libs "") set(server_connector_source "") set(server_connector_header "") -set(server_connector_libs "") +set(server_connector_libs "") set(SERVER_LIBS "") set(CLIENT_LIBS "") # setup sources for http connectors if (HTTP_CLIENT) - list(APPEND client_connector_header "client/connectors/httpclient.h") - list(APPEND client_connector_source "client/connectors/httpclient.cpp") + list(APPEND client_connector_header "client/connectors/httpclient.h") + list(APPEND client_connector_source "client/connectors/httpclient.cpp") list(APPEND client_connector_libs ${CURL_LIBRARIES}) set(CLIENT_LIBS "${CLIENT_LIBS} -lcurl") -endif() +endif () if (HTTP_SERVER) - list(APPEND server_connector_header "server/connectors/httpserver.h") - list(APPEND server_connector_source "server/connectors/httpserver.cpp") + list(APPEND server_connector_header "server/connectors/httpserver.h") + list(APPEND server_connector_source "server/connectors/httpserver.cpp") list(APPEND server_connector_libs ${CMAKE_THREAD_LIBS_INIT} ${MHD_LIBRARIES}) set(SERVER_LIBS "${SERVER_LIBS} -lmicrohttpd") -endif() +endif () # setup sources for redis connectors if (REDIS_CLIENT) @@ -58,26 +58,26 @@ if (REDIS_CLIENT) list(APPEND client_connector_libs ${HIREDIS_LIBRARIES}) include_directories(${HIREDIS_INCLUDE_DIRS}) set(CLIENT_LIBS "${CLIENT_LIBS} -lhiredis") -endif() +endif () if (REDIS_SERVER) list(APPEND server_connector_header "server/connectors/redisserver.h") list(APPEND server_connector_source "server/connectors/redisserver.cpp") list(APPEND server_connector_libs ${CMAKE_THREAD_LIBS_INIT} ${HIREDIS_LIBRARIES}) set(SERVER_LIBS "${SERVER_LIBS} -lhiredis") -endif() +endif () # setup sources for unix domain socket connectors if (UNIX_DOMAIN_SOCKET_SERVER) list(APPEND server_connector_header "server/connectors/unixdomainsocketserver.h") list(APPEND server_connector_source "server/connectors/unixdomainsocketserver.cpp") list(APPEND server_connector_libs ${CMAKE_THREAD_LIBS_INIT}) -endif() +endif () if (UNIX_DOMAIN_SOCKET_CLIENT) list(APPEND client_connector_header "client/connectors/unixdomainsocketclient.h") list(APPEND client_connector_source "client/connectors/unixdomainsocketclient.cpp") -endif() +endif () # setup sources for tcp socket connectors if (TCP_SOCKET_SERVER) @@ -87,13 +87,13 @@ if (TCP_SOCKET_SERVER) list(APPEND server_connector_header "server/connectors/windowstcpsocketserver.h") list(APPEND server_connector_source "server/connectors/windowstcpsocketserver.cpp") list(APPEND server_connector_libs ws2_32) - endif() - if(UNIX) + endif () + if (UNIX) list(APPEND server_connector_header "server/connectors/linuxtcpsocketserver.h") list(APPEND server_connector_source "server/connectors/linuxtcpsocketserver.cpp") - endif() + endif () list(APPEND server_connector_libs ${CMAKE_THREAD_LIBS_INIT}) -endif() +endif () if (TCP_SOCKET_CLIENT) list(APPEND client_connector_header "client/connectors/tcpsocketclient.h") @@ -102,41 +102,41 @@ if (TCP_SOCKET_CLIENT) list(APPEND client_connector_header "client/connectors/windowstcpsocketclient.h") list(APPEND client_connector_source "client/connectors/windowstcpsocketclient.cpp") list(APPEND client_connector_libs ws2_32) - endif() - if(UNIX) + endif () + if (UNIX) list(APPEND client_connector_header "client/connectors/linuxtcpsocketclient.h") list(APPEND client_connector_source "client/connectors/linuxtcpsocketclient.cpp") - endif() + endif () list(APPEND client_connector_libs ${CMAKE_THREAD_LIBS_INIT}) -endif() +endif () if (SERIAL_PORT_SERVER) - if(UNIX) + if (UNIX) list(APPEND server_connector_header "server/connectors/linuxserialportserver.h") list(APPEND server_connector_source "server/connectors/linuxserialportserver.cpp") - endif() + endif () list(APPEND server_connector_libs ${CMAKE_THREAD_LIBS_INIT}) -endif() +endif () if (SERIAL_PORT_CLIENT) - if(UNIX) + if (UNIX) list(APPEND client_connector_header "client/connectors/linuxserialportclient.h") list(APPEND client_connector_source "client/connectors/linuxserialportclient.cpp") - endif() + endif () list(APPEND client_connector_libs ${CMAKE_THREAD_LIBS_INIT}) -endif() +endif () if (FILE_DESCRIPTOR_SERVER) list(APPEND server_connector_header "server/connectors/filedescriptorserver.h") list(APPEND server_connector_source "server/connectors/filedescriptorserver.cpp") list(APPEND server_connector_libs ${CMAKE_THREAD_LIBS_INIT}) -endif() +endif () if (FILE_DESCRIPTOR_CLIENT) list(APPEND client_connector_header "client/connectors/filedescriptorclient.h") list(APPEND client_connector_source "client/connectors/filedescriptorclient.cpp") list(APPEND client_connector_libs ${CMAKE_THREAD_LIBS_INIT}) -endif() +endif () # configure a header file to pass some of the CMake settings to the source code file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/gen/jsonrpccpp/common") @@ -152,21 +152,21 @@ include_directories(${MHD_INCLUDE_DIRS}) # setup shared common library if (BUILD_SHARED_LIBS) - add_library(jsonrpccommon SHARED ${jsonrpc_source_common} ${jsonrpc_header} ${jsonrpc_helper_source_common}) - target_link_libraries(jsonrpccommon ${JSONCPP_LIBRARY}) - set_target_properties(jsonrpccommon PROPERTIES OUTPUT_NAME jsonrpccpp-common) -endif() + add_library(jsonrpccommon SHARED ${jsonrpc_source_common} ${jsonrpc_header} ${jsonrpc_helper_source_common}) + target_link_libraries(jsonrpccommon ${JSONCPP_LIBRARY}) + set_target_properties(jsonrpccommon PROPERTIES OUTPUT_NAME jsonrpccpp-common) +endif () # setup static common library if (BUILD_STATIC_LIBS OR MSVC) - add_library(common STATIC ${jsonrpc_source_common} ${jsonrpc_header} ${jsonrpc_helper_source_common}) - target_link_libraries(common jsoncpp_lib_static) - set_target_properties(common PROPERTIES OUTPUT_NAME jsonrpccpp-common) + add_library(common STATIC ${jsonrpc_source_common} ${jsonrpc_header} ${jsonrpc_helper_source_common}) + target_link_libraries(common jsoncpp_lib_static) + set_target_properties(common PROPERTIES OUTPUT_NAME jsonrpccpp-common) - if (NOT BUILD_SHARED_LIBS) - add_library(jsonrpccommon ALIAS common) - endif() -endif() + if (NOT BUILD_SHARED_LIBS) + add_library(jsonrpccommon ALIAS common) + endif () +endif () # setup shared client library if (BUILD_SHARED_LIBS) @@ -174,18 +174,18 @@ if (BUILD_SHARED_LIBS) add_dependencies(jsonrpcclient jsonrpccommon) target_link_libraries(jsonrpcclient jsonrpccommon ${client_connector_libs}) set_target_properties(jsonrpcclient PROPERTIES OUTPUT_NAME jsonrpccpp-client) -endif() +endif () # setup static client library if (BUILD_STATIC_LIBS OR MSVC) - add_library(client STATIC ${jsonrpc_source_client} ${jsonrpc_header} ${jsonrpc_header_client} ${client_connector_source}) - target_link_libraries(client common ${client_connector_libs}) - set_target_properties(client PROPERTIES OUTPUT_NAME jsonrpccpp-client) + add_library(client STATIC ${jsonrpc_source_client} ${jsonrpc_header} ${jsonrpc_header_client} ${client_connector_source}) + target_link_libraries(client common ${client_connector_libs}) + set_target_properties(client PROPERTIES OUTPUT_NAME jsonrpccpp-client) - if (NOT BUILD_SHARED_LIBS) - add_library(jsonrpcclient ALIAS client) - endif() -endif() + if (NOT BUILD_SHARED_LIBS) + add_library(jsonrpcclient ALIAS client) + endif () +endif () # setup shared server library if (BUILD_SHARED_LIBS) @@ -193,58 +193,58 @@ if (BUILD_SHARED_LIBS) add_dependencies(jsonrpcserver jsonrpccommon) target_link_libraries(jsonrpcserver jsonrpccommon ${server_connector_libs}) set_target_properties(jsonrpcserver PROPERTIES OUTPUT_NAME jsonrpccpp-server) -endif() +endif () # setup static server library if (BUILD_STATIC_LIBS OR MSVC) - add_library(server STATIC ${jsonrpc_source_server} ${jsonrpc_header} ${jsonrpc_header_server} ${server_connector_source}) - target_link_libraries(server common ${server_connector_libs}) - set_target_properties(server PROPERTIES OUTPUT_NAME jsonrpccpp-server) + add_library(server STATIC ${jsonrpc_source_server} ${jsonrpc_header} ${jsonrpc_header_server} ${server_connector_source}) + target_link_libraries(server common ${server_connector_libs}) + set_target_properties(server PROPERTIES OUTPUT_NAME jsonrpccpp-server) - if (NOT BUILD_SHARED_LIBS) - add_library(jsonrpcserver ALIAS server) - endif() -endif() + if (NOT BUILD_SHARED_LIBS) + add_library(jsonrpcserver ALIAS server) + endif () +endif () set(ALL_LIBS) if (BUILD_SHARED_LIBS OR NOT BUILD_STATIC_LIBS) list(APPEND ALL_LIBS jsonrpccommon jsonrpcclient jsonrpcserver) -endif() +endif () if (BUILD_STATIC_LIBS OR MSVC) - list(APPEND ALL_LIBS common client server) -endif() + list(APPEND ALL_LIBS common client server) +endif () # setup version set(VERSION_STRING ${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_VERSION}) set_target_properties( - ${ALL_LIBS} - PROPERTIES VERSION "${VERSION_STRING}" SOVERSION "${SO_VERSION}" + ${ALL_LIBS} + PROPERTIES VERSION "${VERSION_STRING}" SOVERSION "${SO_VERSION}" ) # install libraries -install(FILES ${jsonrpc_header} DESTINATION include/jsonrpccpp) -install(FILES ${jsonrpc_header_common} DESTINATION include/jsonrpccpp/common) -install(FILES ${jsonrpc_helper_header_common} DESTINATION include/jsonrpccpp/common/helper) -install(FILES ${jsonrpc_install_header_client} DESTINATION include/jsonrpccpp/client) -install(FILES ${jsonrpc_install_header_server} DESTINATION include/jsonrpccpp/server) -install(FILES ${client_connector_header} DESTINATION include/jsonrpccpp/client/connectors) -install(FILES ${server_connector_header} DESTINATION include/jsonrpccpp/server/connectors) +install(FILES ${jsonrpc_header} DESTINATION include/jsonrpccpp) +install(FILES ${jsonrpc_header_common} DESTINATION include/jsonrpccpp/common) +install(FILES ${jsonrpc_helper_header_common} DESTINATION include/jsonrpccpp/common/helper) +install(FILES ${jsonrpc_install_header_client} DESTINATION include/jsonrpccpp/client) +install(FILES ${jsonrpc_install_header_server} DESTINATION include/jsonrpccpp/server) +install(FILES ${client_connector_header} DESTINATION include/jsonrpccpp/client/connectors) +install(FILES ${server_connector_header} DESTINATION include/jsonrpccpp/server/connectors) if (WIN32 AND NOT HUNTER_ENABLED) - # On Windows copy manually installed dependencies unless Hunter is used. - file(GLOB win32_libs ${CMAKE_SOURCE_DIR}/win32-deps/lib/*.dll) - file(COPY ${win32_libs} DESTINATION ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) - install(FILES ${win32_libs} DESTINATION bin) - install(DIRECTORY ${CMAKE_SOURCE_DIR}/win32-deps/include DESTINATION .) -endif() + # On Windows copy manually installed dependencies unless Hunter is used. + file(GLOB win32_libs ${CMAKE_SOURCE_DIR}/win32-deps/lib/*.dll) + file(COPY ${win32_libs} DESTINATION ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) + install(FILES ${win32_libs} DESTINATION bin) + install(DIRECTORY ${CMAKE_SOURCE_DIR}/win32-deps/include DESTINATION .) +endif () install(TARGETS ${ALL_LIBS} EXPORT libjson-rpc-cppTargets - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - RUNTIME DESTINATION bin -) + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION bin + ) #set pkg-config get_filename_component(FULL_PATH_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}" ABSOLUTE) @@ -256,7 +256,7 @@ configure_file(${PROJECT_SOURCE_DIR}/cmake/libjsonrpccpp-server.pc.cmake ${CMAKE configure_file(${PROJECT_SOURCE_DIR}/cmake/libjsonrpccpp-common.pc.cmake ${CMAKE_BINARY_DIR}/libjsonrpccpp-common.pc) INSTALL(FILES - "${CMAKE_BINARY_DIR}/libjsonrpccpp-server.pc" - "${CMAKE_BINARY_DIR}/libjsonrpccpp-client.pc" - "${CMAKE_BINARY_DIR}/libjsonrpccpp-common.pc" - DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") + "${CMAKE_BINARY_DIR}/libjsonrpccpp-server.pc" + "${CMAKE_BINARY_DIR}/libjsonrpccpp-client.pc" + "${CMAKE_BINARY_DIR}/libjsonrpccpp-common.pc" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") diff --git a/src/jsonrpccpp/client.h b/src/jsonrpccpp/client.h index d5225fd6..a23b46a9 100644 --- a/src/jsonrpccpp/client.h +++ b/src/jsonrpccpp/client.h @@ -13,5 +13,4 @@ #include #include - #endif /* JSONRPCCPP_CLIENT_H_ */ diff --git a/src/jsonrpccpp/client/batchcall.cpp b/src/jsonrpccpp/client/batchcall.cpp index 92b47bf6..3013263d 100644 --- a/src/jsonrpccpp/client/batchcall.cpp +++ b/src/jsonrpccpp/client/batchcall.cpp @@ -15,8 +15,7 @@ using namespace std; BatchCall::BatchCall() : id(1) {} -int BatchCall::addCall(const string &methodname, const Json::Value ¶ms, - bool isNotification) { +int BatchCall::addCall(const string &methodname, const Json::Value ¶ms, bool isNotification) { Json::Value call; call[RpcProtocolClient::KEY_PROTOCOL_VERSION] = "2.0"; call[RpcProtocolClient::KEY_PROCEDURE_NAME] = methodname; diff --git a/src/jsonrpccpp/client/batchcall.h b/src/jsonrpccpp/client/batchcall.h index b255fd64..6c46193e 100644 --- a/src/jsonrpccpp/client/batchcall.h +++ b/src/jsonrpccpp/client/batchcall.h @@ -12,27 +12,25 @@ #include -namespace jsonrpc -{ - class BatchCall - { - public: - BatchCall (); +namespace jsonrpc { + class BatchCall { + public: + BatchCall(); - /** - * @brief addCall - * @param methodname - * @param params - * @param isNotification - * @return the id of the geneared request inside the batchcall - */ - int addCall (const std::string &methodname, const Json::Value ¶ms, bool isNotification = false); - std::string toString (bool fast = true) const; + /** + * @brief addCall + * @param methodname + * @param params + * @param isNotification + * @return the id of the geneared request inside the batchcall + */ + int addCall(const std::string &methodname, const Json::Value ¶ms, bool isNotification = false); + std::string toString(bool fast = true) const; - private: - Json::Value result; - int id; - }; -} + private: + Json::Value result; + int id; + }; +} // namespace jsonrpc #endif // JSONRPC_CPP_BATCHCALL_H diff --git a/src/jsonrpccpp/client/batchresponse.cpp b/src/jsonrpccpp/client/batchresponse.cpp index f68f01b7..2d27456a 100644 --- a/src/jsonrpccpp/client/batchresponse.cpp +++ b/src/jsonrpccpp/client/batchresponse.cpp @@ -15,8 +15,7 @@ using namespace std; BatchResponse::BatchResponse() {} -void BatchResponse::addResponse(Json::Value &id, Json::Value response, - bool isError) { +void BatchResponse::addResponse(Json::Value &id, Json::Value response, bool isError) { if (isError) { errorResponses.push_back(id); } @@ -38,16 +37,14 @@ void BatchResponse::getResult(Json::Value &id, Json::Value &result) { } int BatchResponse::getErrorCode(Json::Value &id) { - if (std::find(errorResponses.begin(), errorResponses.end(), id) != - errorResponses.end()) { + if (std::find(errorResponses.begin(), errorResponses.end(), id) != errorResponses.end()) { return responses[id]["code"].asInt(); } return 0; } string BatchResponse::getErrorMessage(Json::Value &id) { - if (std::find(errorResponses.begin(), errorResponses.end(), id) != - errorResponses.end()) { + if (std::find(errorResponses.begin(), errorResponses.end(), id) != errorResponses.end()) { return responses[id]["message"].asString(); } return ""; diff --git a/src/jsonrpccpp/client/batchresponse.h b/src/jsonrpccpp/client/batchresponse.h index 928218c1..a8dd991f 100644 --- a/src/jsonrpccpp/client/batchresponse.h +++ b/src/jsonrpccpp/client/batchresponse.h @@ -10,60 +10,57 @@ #ifndef JSONRPC_BATCHRESPONSE_H #define JSONRPC_BATCHRESPONSE_H -#include #include +#include namespace jsonrpc { + /** + * @brief The BatchResponse class provides a simple interface for handling batch responses. + */ + class BatchResponse { + public: + BatchResponse(); + /** - * @brief The BatchResponse class provides a simple interface for handling batch responses. + * @brief addResponse method is used only internally by the framework + * @param id + * @param response + * @param isError */ - class BatchResponse - { - public: - BatchResponse(); - - /** - * @brief addResponse method is used only internally by the framework - * @param id - * @param response - * @param isError - */ - void addResponse(Json::Value& id, Json::Value response, bool isError = false); - - /** - * @brief getResult method gets the result for a given request id (returned by BatchCall::addCall. - * You should always invoke getErrorCode() first to check if the result is valid. - * @param id - * @return - */ - Json::Value getResult(int id); - + void addResponse(Json::Value &id, Json::Value response, bool isError = false); - void getResult(Json::Value& id, Json::Value &result); + /** + * @brief getResult method gets the result for a given request id (returned by BatchCall::addCall. + * You should always invoke getErrorCode() first to check if the result is valid. + * @param id + * @return + */ + Json::Value getResult(int id); - /** - * @brief getErrorCode method checks if for a given id, an error occurred in the batch request. - * @param id - */ - int getErrorCode(Json::Value& id); + void getResult(Json::Value &id, Json::Value &result); - /** - * @brief getErrorMessage method gets the corresponding error message. - * @param id - * @return the error message in case of an error, an empty string if no error was found for the provided id. - */ - std::string getErrorMessage(Json::Value& id); + /** + * @brief getErrorCode method checks if for a given id, an error occurred in the batch request. + * @param id + */ + int getErrorCode(Json::Value &id); - std::string getErrorMessage(int id); + /** + * @brief getErrorMessage method gets the corresponding error message. + * @param id + * @return the error message in case of an error, an empty string if no error was found for the provided id. + */ + std::string getErrorMessage(Json::Value &id); - bool hasErrors(); + std::string getErrorMessage(int id); - private: - std::map responses; - std::vector errorResponses; + bool hasErrors(); - }; + private: + std::map responses; + std::vector errorResponses; + }; } // namespace jsonrpc diff --git a/src/jsonrpccpp/client/client.cpp b/src/jsonrpccpp/client/client.cpp index 8e37f6cc..6436f65d 100644 --- a/src/jsonrpccpp/client/client.cpp +++ b/src/jsonrpccpp/client/client.cpp @@ -12,16 +12,13 @@ using namespace jsonrpc; -Client::Client(IClientConnector &connector, clientVersion_t version, - bool omitEndingLineFeed) - : connector(connector) { +Client::Client(IClientConnector &connector, clientVersion_t version, bool omitEndingLineFeed) : connector(connector) { this->protocol = new RpcProtocolClient(version, omitEndingLineFeed); } Client::~Client() { delete this->protocol; } -void Client::CallMethod(const std::string &name, const Json::Value ¶meter, - Json::Value &result) { +void Client::CallMethod(const std::string &name, const Json::Value ¶meter, Json::Value &result) { std::string request, response; protocol->BuildRequest(name, parameter, request, false); connector.SendRPCMessage(request, response); @@ -37,21 +34,17 @@ void Client::CallProcedures(const BatchCall &calls, BatchResponse &result) { try { if (!reader.parse(response, tmpresult) || !tmpresult.isArray()) { - throw JsonRpcException(Errors::ERROR_CLIENT_INVALID_RESPONSE, - "Array expected."); + throw JsonRpcException(Errors::ERROR_CLIENT_INVALID_RESPONSE, "Array expected."); } } catch (const Json::Exception &e) { - throw JsonRpcException( - Errors::ERROR_RPC_JSON_PARSE_ERROR, - Errors::GetErrorMessage(Errors::ERROR_RPC_JSON_PARSE_ERROR), response); + throw JsonRpcException(Errors::ERROR_RPC_JSON_PARSE_ERROR, Errors::GetErrorMessage(Errors::ERROR_RPC_JSON_PARSE_ERROR), response); } for (unsigned int i = 0; i < tmpresult.size(); i++) { if (tmpresult[i].isObject()) { Json::Value singleResult; try { - Json::Value id = - this->protocol->HandleResponse(tmpresult[i], singleResult); + Json::Value id = this->protocol->HandleResponse(tmpresult[i], singleResult); result.addResponse(id, singleResult, false); } catch (JsonRpcException &ex) { Json::Value id = -1; @@ -60,8 +53,7 @@ void Client::CallProcedures(const BatchCall &calls, BatchResponse &result) { result.addResponse(id, tmpresult[i]["error"], true); } } else - throw JsonRpcException(Errors::ERROR_CLIENT_INVALID_RESPONSE, - "Object in Array expected."); + throw JsonRpcException(Errors::ERROR_CLIENT_INVALID_RESPONSE, "Object in Array expected."); } } @@ -71,15 +63,13 @@ BatchResponse Client::CallProcedures(const BatchCall &calls) { return result; } -Json::Value Client::CallMethod(const std::string &name, - const Json::Value ¶meter) { +Json::Value Client::CallMethod(const std::string &name, const Json::Value ¶meter) { Json::Value result; this->CallMethod(name, parameter, result); return result; } -void Client::CallNotification(const std::string &name, - const Json::Value ¶meter) { +void Client::CallNotification(const std::string &name, const Json::Value ¶meter) { std::string request, response; protocol->BuildRequest(name, parameter, request, true); connector.SendRPCMessage(request, response); diff --git a/src/jsonrpccpp/client/client.h b/src/jsonrpccpp/client/client.h index 540425e4..b5d223f8 100644 --- a/src/jsonrpccpp/client/client.h +++ b/src/jsonrpccpp/client/client.h @@ -10,39 +10,36 @@ #ifndef JSONRPC_CPP_CLIENT_H_ #define JSONRPC_CPP_CLIENT_H_ -#include "iclientconnector.h" #include "batchcall.h" #include "batchresponse.h" +#include "iclientconnector.h" #include -#include #include +#include -namespace jsonrpc -{ - class RpcProtocolClient; - - typedef enum {JSONRPC_CLIENT_V1, JSONRPC_CLIENT_V2} clientVersion_t; +namespace jsonrpc { + class RpcProtocolClient; - class Client - { - public: - Client(IClientConnector &connector, clientVersion_t version = JSONRPC_CLIENT_V2, bool omitEndingLineFeed = false); - virtual ~Client(); + typedef enum { JSONRPC_CLIENT_V1, JSONRPC_CLIENT_V2 } clientVersion_t; - void CallMethod (const std::string &name, const Json::Value ¶meter, Json::Value& result) ; - Json::Value CallMethod (const std::string &name, const Json::Value ¶meter) ; + class Client { + public: + Client(IClientConnector &connector, clientVersion_t version = JSONRPC_CLIENT_V2, bool omitEndingLineFeed = false); + virtual ~Client(); - void CallProcedures (const BatchCall &calls, BatchResponse &response) ; - BatchResponse CallProcedures (const BatchCall &calls) ; + void CallMethod(const std::string &name, const Json::Value ¶meter, Json::Value &result); + Json::Value CallMethod(const std::string &name, const Json::Value ¶meter); - void CallNotification (const std::string& name, const Json::Value& parameter) ; + void CallProcedures(const BatchCall &calls, BatchResponse &response); + BatchResponse CallProcedures(const BatchCall &calls); - private: - IClientConnector &connector; - RpcProtocolClient *protocol; + void CallNotification(const std::string &name, const Json::Value ¶meter); - }; + private: + IClientConnector &connector; + RpcProtocolClient *protocol; + }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_CLIENT_H_ */ diff --git a/src/jsonrpccpp/client/connectors/filedescriptorclient.cpp b/src/jsonrpccpp/client/connectors/filedescriptorclient.cpp index a7d269c3..351c23cd 100644 --- a/src/jsonrpccpp/client/connectors/filedescriptorclient.cpp +++ b/src/jsonrpccpp/client/connectors/filedescriptorclient.cpp @@ -25,32 +25,25 @@ using namespace jsonrpc; using namespace std; -FileDescriptorClient::FileDescriptorClient(int inputfd, int outputfd) - : inputfd(inputfd), outputfd(outputfd) {} +FileDescriptorClient::FileDescriptorClient(int inputfd, int outputfd) : inputfd(inputfd), outputfd(outputfd) {} FileDescriptorClient::~FileDescriptorClient() {} -void FileDescriptorClient::SendRPCMessage(const std::string &message, - std::string &result) { +void FileDescriptorClient::SendRPCMessage(const std::string &message, std::string &result) { string toSend = message + DEFAULT_DELIMITER_CHAR; StreamWriter writer; if (!writer.Write(toSend, outputfd)) { - throw JsonRpcException( - Errors::ERROR_CLIENT_CONNECTOR, - "Unknown error occurred while writing to the output file descriptor"); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Unknown error occurred while writing to the output file descriptor"); } if (!IsReadable(inputfd)) - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "The input file descriptor is not readable"); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "The input file descriptor is not readable"); StreamReader reader(DEFAULT_BUFFER_SIZE); if (!reader.Read(result, inputfd, DEFAULT_DELIMITER_CHAR)) { - throw JsonRpcException( - Errors::ERROR_CLIENT_CONNECTOR, - "Unknown error occurred while reading from input file descriptor"); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Unknown error occurred while reading from input file descriptor"); } } @@ -59,6 +52,5 @@ bool FileDescriptorClient::IsReadable(int fd) { int ret = fcntl(fd, F_GETFL, &o_accmode); if (ret == -1) return false; - return ((o_accmode & O_ACCMODE) == O_RDONLY || - (o_accmode & O_ACCMODE) == O_RDWR); + return ((o_accmode & O_ACCMODE) == O_RDONLY || (o_accmode & O_ACCMODE) == O_RDWR); } diff --git a/src/jsonrpccpp/client/connectors/filedescriptorclient.h b/src/jsonrpccpp/client/connectors/filedescriptorclient.h index cbce16d5..b0d9d1de 100644 --- a/src/jsonrpccpp/client/connectors/filedescriptorclient.h +++ b/src/jsonrpccpp/client/connectors/filedescriptorclient.h @@ -13,20 +13,18 @@ #include "../iclientconnector.h" #include -namespace jsonrpc -{ - class FileDescriptorClient : public IClientConnector - { - public: - FileDescriptorClient(int inputfd, int outputfd); - virtual ~FileDescriptorClient(); - virtual void SendRPCMessage(const std::string& message, std::string& result) ; +namespace jsonrpc { + class FileDescriptorClient : public IClientConnector { + public: + FileDescriptorClient(int inputfd, int outputfd); + virtual ~FileDescriptorClient(); + virtual void SendRPCMessage(const std::string &message, std::string &result); - protected: - int inputfd; - int outputfd; + protected: + int inputfd; + int outputfd; - bool IsReadable(int fd); + bool IsReadable(int fd); }; } /* namespace jsonrpc */ diff --git a/src/jsonrpccpp/client/connectors/httpclient.cpp b/src/jsonrpccpp/client/connectors/httpclient.cpp index 2dca349a..fbd272d2 100644 --- a/src/jsonrpccpp/client/connectors/httpclient.cpp +++ b/src/jsonrpccpp/client/connectors/httpclient.cpp @@ -35,8 +35,7 @@ struct string { size_t len; }; -static size_t writefunc(void *ptr, size_t size, size_t nmemb, - struct string *s) { +static size_t writefunc(void *ptr, size_t size, size_t nmemb, struct string *s) { size_t new_len = s->len + size * nmemb; s->ptr = (char *)realloc(s->ptr, new_len + 1); memcpy(s->ptr + s->len, ptr, size * nmemb); @@ -58,8 +57,7 @@ HttpClient::HttpClient(const std::string &url) : url(url) { HttpClient::~HttpClient() { curl_easy_cleanup(curl); } -void HttpClient::SendRPCMessage(const std::string &message, - std::string &result) { +void HttpClient::SendRPCMessage(const std::string &message, std::string &result) { curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(curl, CURLOPT_URL, this->url.c_str()); @@ -72,11 +70,8 @@ void HttpClient::SendRPCMessage(const std::string &message, struct curl_slist *headers = NULL; - for (std::map::iterator header = - this->headers.begin(); - header != this->headers.end(); ++header) { - headers = curl_slist_append( - headers, (header->first + ": " + header->second).c_str()); + for (std::map::iterator header = this->headers.begin(); header != this->headers.end(); ++header) { + headers = curl_slist_append(headers, (header->first + ": " + header->second).c_str()); } headers = curl_slist_append(headers, "Content-Type: application/json"); @@ -115,10 +110,6 @@ void HttpClient::SetUrl(const std::string &url) { this->url = url; } void HttpClient::SetTimeout(long timeout) { this->timeout = timeout; } -void HttpClient::AddHeader(const std::string &attr, const std::string &val) { - this->headers[attr] = val; -} +void HttpClient::AddHeader(const std::string &attr, const std::string &val) { this->headers[attr] = val; } -void HttpClient::RemoveHeader(const std::string &attr) { - this->headers.erase(attr); -} +void HttpClient::RemoveHeader(const std::string &attr) { this->headers.erase(attr); } diff --git a/src/jsonrpccpp/client/connectors/httpclient.h b/src/jsonrpccpp/client/connectors/httpclient.h index a1d5562e..d813e5af 100644 --- a/src/jsonrpccpp/client/connectors/httpclient.h +++ b/src/jsonrpccpp/client/connectors/httpclient.h @@ -16,28 +16,28 @@ #include namespace jsonrpc { -class HttpClient : public IClientConnector { -public: - HttpClient(const std::string &url); - virtual ~HttpClient(); - virtual void SendRPCMessage(const std::string &message, std::string &result); - - void SetUrl(const std::string &url); - void SetTimeout(long timeout); - - void AddHeader(const std::string &attr, const std::string &val); - void RemoveHeader(const std::string &attr); - -protected: - std::map headers; - std::string url; - - /** - * @brief timeout for http request in milliseconds - */ - long timeout; - CURL *curl; -}; + class HttpClient : public IClientConnector { + public: + HttpClient(const std::string &url); + virtual ~HttpClient(); + virtual void SendRPCMessage(const std::string &message, std::string &result); + + void SetUrl(const std::string &url); + void SetTimeout(long timeout); + + void AddHeader(const std::string &attr, const std::string &val); + void RemoveHeader(const std::string &attr); + + protected: + std::map headers; + std::string url; + + /** + * @brief timeout for http request in milliseconds + */ + long timeout; + CURL *curl; + }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_HTTPCLIENT_H_ */ diff --git a/src/jsonrpccpp/client/connectors/linuxserialportclient.cpp b/src/jsonrpccpp/client/connectors/linuxserialportclient.cpp index 2d09babe..4b9d7b93 100644 --- a/src/jsonrpccpp/client/connectors/linuxserialportclient.cpp +++ b/src/jsonrpccpp/client/connectors/linuxserialportclient.cpp @@ -23,26 +23,22 @@ using namespace jsonrpc; using namespace std; -LinuxSerialPortClient::LinuxSerialPortClient(const std::string &deviceName) - : deviceName(deviceName) {} +LinuxSerialPortClient::LinuxSerialPortClient(const std::string &deviceName) : deviceName(deviceName) {} LinuxSerialPortClient::~LinuxSerialPortClient() {} -void LinuxSerialPortClient::SendRPCMessage(const std::string &message, - std::string &result) { +void LinuxSerialPortClient::SendRPCMessage(const std::string &message, std::string &result) { int serial_fd = this->Connect(); StreamWriter writer; string toSend = message + DEFAULT_DELIMITER_CHAR; if (!writer.Write(toSend, serial_fd)) { - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "Could not write request"); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Could not write request"); } StreamReader reader(DEFAULT_BUFFER_SIZE); if (!reader.Read(result, serial_fd, DEFAULT_DELIMITER_CHAR)) { - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "Could not read response"); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Could not read response"); } close(serial_fd); } diff --git a/src/jsonrpccpp/client/connectors/linuxserialportclient.h b/src/jsonrpccpp/client/connectors/linuxserialportclient.h index cd5c3b71..c75287ed 100644 --- a/src/jsonrpccpp/client/connectors/linuxserialportclient.h +++ b/src/jsonrpccpp/client/connectors/linuxserialportclient.h @@ -14,49 +14,47 @@ #include #include -namespace jsonrpc -{ +namespace jsonrpc { + /** + * This class is the Linux/Unix implementation of LinuxSerialPortClient. + * It uses the POSIX socket API to performs its job. + */ + class LinuxSerialPortClient : public IClientConnector { + public: /** - * This class is the Linux/Unix implementation of LinuxSerialPortClient. - * It uses the POSIX socket API to performs its job. + * @brief LinuxSerialPortClient, constructor of the Linux/UNIX implementation of class TcpSocketClient + * @param deviceName The device name on which the client should try to connect */ - class LinuxSerialPortClient : public IClientConnector - { - public: - /** - * @brief LinuxSerialPortClient, constructor of the Linux/UNIX implementation of class TcpSocketClient - * @param deviceName The device name on which the client should try to connect - */ - LinuxSerialPortClient(const std::string& deviceName); - /** - * @brief ~LinuxSerialPortClient, the destructor of LinuxSerialPortClient - */ - virtual ~LinuxSerialPortClient(); - /** - * @brief The real implementation of TcpSocketClient::SendRPCMessage method. - * @param message The message to send - * @param result The result of the call returned by the server - * @throw JsonRpcException Thrown when an issue is encountered with socket manipulation (see message of exception for more information about what happened). - */ - virtual void SendRPCMessage(const std::string& message, std::string& result) ; + LinuxSerialPortClient(const std::string &deviceName); + /** + * @brief ~LinuxSerialPortClient, the destructor of LinuxSerialPortClient + */ + virtual ~LinuxSerialPortClient(); + /** + * @brief The real implementation of TcpSocketClient::SendRPCMessage method. + * @param message The message to send + * @param result The result of the call returned by the server + * @throw JsonRpcException Thrown when an issue is encountered with socket manipulation (see message of exception for more information about what happened). + */ + virtual void SendRPCMessage(const std::string &message, std::string &result); - protected: - int fd; - std::string deviceName; /*!< The serial port device name on which the client should try to connect*/ - /** - * @brief Connects to the serial port provided by constructor parameters. - * - * @returns A file descriptor to the successfully connected socket - * @throw JsonRpcException Thrown when an issue is encountered while trying to connect (see message of exception for more information about what happened). - */ - int Connect() ; - /** - * @param deviceName The device name to connect to - * @returns A file descriptor to the successfully connected socket - * @throw JsonRpcException Thrown when an issue is encountered while trying to connect (see message of exception for more information about what happened). - */ - int Connect(const std::string& deviceName) ; - }; + protected: + int fd; + std::string deviceName; /*!< The serial port device name on which the client should try to connect*/ + /** + * @brief Connects to the serial port provided by constructor parameters. + * + * @returns A file descriptor to the successfully connected socket + * @throw JsonRpcException Thrown when an issue is encountered while trying to connect (see message of exception for more information about what happened). + */ + int Connect(); + /** + * @param deviceName The device name to connect to + * @returns A file descriptor to the successfully connected socket + * @throw JsonRpcException Thrown when an issue is encountered while trying to connect (see message of exception for more information about what happened). + */ + int Connect(const std::string &deviceName); + }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_LINUXSERIALPORTCLIENT_H_ */ diff --git a/src/jsonrpccpp/client/connectors/linuxtcpsocketclient.cpp b/src/jsonrpccpp/client/connectors/linuxtcpsocketclient.cpp index 1d59ca59..32fd7b3c 100644 --- a/src/jsonrpccpp/client/connectors/linuxtcpsocketclient.cpp +++ b/src/jsonrpccpp/client/connectors/linuxtcpsocketclient.cpp @@ -26,27 +26,22 @@ using namespace jsonrpc; using namespace std; -LinuxTcpSocketClient::LinuxTcpSocketClient(const std::string &hostToConnect, - const unsigned int &port) - : hostToConnect(hostToConnect), port(port) {} +LinuxTcpSocketClient::LinuxTcpSocketClient(const std::string &hostToConnect, const unsigned int &port) : hostToConnect(hostToConnect), port(port) {} LinuxTcpSocketClient::~LinuxTcpSocketClient() {} -void LinuxTcpSocketClient::SendRPCMessage(const std::string &message, - std::string &result) { +void LinuxTcpSocketClient::SendRPCMessage(const std::string &message, std::string &result) { int socket_fd = this->Connect(); StreamWriter writer; string toSend = message + DEFAULT_DELIMITER_CHAR; if (!writer.Write(toSend, socket_fd)) { - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "Could not write request"); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Could not write request"); } StreamReader reader(DEFAULT_BUFFER_SIZE); if (!reader.Read(result, socket_fd, DEFAULT_DELIMITER_CHAR)) { - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "Could not read response"); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Could not read response"); } close(socket_fd); } @@ -64,20 +59,16 @@ int LinuxTcpSocketClient::Connect() { hints.ai_protocol = IPPROTO_TCP; char port[6]; snprintf(port, 6, "%d", this->port); - int retval = - getaddrinfo(this->hostToConnect.c_str(), port, &hints, &result); + int retval = getaddrinfo(this->hostToConnect.c_str(), port, &hints, &result); if (retval != 0) - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "Could not resolve hostname."); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Could not resolve hostname."); bool foundValidIp = false; int socket_fd; - for (struct addrinfo *temp = result; (temp != NULL) && !foundValidIp; - temp = temp->ai_next) { + for (struct addrinfo *temp = result; (temp != NULL) && !foundValidIp; temp = temp->ai_next) { if (temp->ai_family == AF_INET) { try { sockaddr_in *sock = reinterpret_cast(temp->ai_addr); - socket_fd = - this->Connect(inet_ntoa(sock->sin_addr), ntohs(sock->sin_port)); + socket_fd = this->Connect(inet_ntoa(sock->sin_addr), ntohs(sock->sin_port)); foundValidIp = true; } catch (const JsonRpcException &e) { foundValidIp = false; @@ -90,9 +81,7 @@ int LinuxTcpSocketClient::Connect() { } if (!foundValidIp) - throw JsonRpcException( - Errors::ERROR_CLIENT_CONNECTOR, - "Hostname resolved but connection was refused on the given port."); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Hostname resolved but connection was refused on the given port."); return socket_fd; } @@ -124,8 +113,7 @@ int LinuxTcpSocketClient::Connect(const string &ip, const int &port) { inet_aton(ip.c_str(), &(address.sin_addr)); address.sin_port = htons(port); - if (connect(socket_fd, (struct sockaddr *)&address, sizeof(sockaddr_in)) != - 0) { + if (connect(socket_fd, (struct sockaddr *)&address, sizeof(sockaddr_in)) != 0) { string message = "connect() failed"; int err = errno; switch (err) { diff --git a/src/jsonrpccpp/client/connectors/linuxtcpsocketclient.h b/src/jsonrpccpp/client/connectors/linuxtcpsocketclient.h index 8df9eeba..c8d0d4d9 100644 --- a/src/jsonrpccpp/client/connectors/linuxtcpsocketclient.h +++ b/src/jsonrpccpp/client/connectors/linuxtcpsocketclient.h @@ -12,66 +12,64 @@ #include -namespace jsonrpc -{ +namespace jsonrpc { + /** + * This class is the Linux/UNIX implementation of TCPSocketClient. + * It uses the POSIX socket API to performs its job. + */ + class LinuxTcpSocketClient : public IClientConnector { + public: /** - * This class is the Linux/UNIX implementation of TCPSocketClient. - * It uses the POSIX socket API to performs its job. + * @brief LinuxTcpSocketClient, constructor of the Linux/UNIX implementation of class TcpSocketClient + * @param hostToConnect The hostname or the ipv4 address on which the client should try to connect + * @param port The port on which the client should try to connect */ - class LinuxTcpSocketClient : public IClientConnector - { - public: - /** - * @brief LinuxTcpSocketClient, constructor of the Linux/UNIX implementation of class TcpSocketClient - * @param hostToConnect The hostname or the ipv4 address on which the client should try to connect - * @param port The port on which the client should try to connect - */ - LinuxTcpSocketClient(const std::string& hostToConnect, const unsigned int &port); - /** - * @brief ~LinuxTcpSocketClient, the destructor of LinuxTcpSocketClient - */ - virtual ~LinuxTcpSocketClient(); - /** - * @brief The real implementation of TcpSocketClient::SendRPCMessage method. - * @param message The message to send - * @param result The result of the call returned by the server - * @throw JsonRpcException Thrown when an issue is encountered with socket manipulation (see message of exception for more information about what happened). - */ - virtual void SendRPCMessage(const std::string& message, std::string& result) ; + LinuxTcpSocketClient(const std::string &hostToConnect, const unsigned int &port); + /** + * @brief ~LinuxTcpSocketClient, the destructor of LinuxTcpSocketClient + */ + virtual ~LinuxTcpSocketClient(); + /** + * @brief The real implementation of TcpSocketClient::SendRPCMessage method. + * @param message The message to send + * @param result The result of the call returned by the server + * @throw JsonRpcException Thrown when an issue is encountered with socket manipulation (see message of exception for more information about what happened). + */ + virtual void SendRPCMessage(const std::string &message, std::string &result); - protected: - std::string hostToConnect; /*!< The hostname or the ipv4 address on which the client should try to connect*/ - unsigned int port; /*!< The port on which the client should try to connect*/ - /** - * @brief Connects to the host and port provided by constructor parameters. - * - * This method detects if the hostToConnect attribute is either an IPv4 or a hostname. - * On first case it tries to connect to the ip. - * On second case it tries to resolve hostname to an ip and tries to connect to it if resolve was successful. - * - * @returns A file descriptor to the successfully connected socket - * @throw JsonRpcException Thrown when an issue is encountered while trying to connect (see message of exception for more information about what happened). - */ - int Connect() ; - /** - * @brief Connects to provided ip and port. - * - * This method tries to connect to the provided ip and port. - * - * @param ip The ipv4 address to connect to - * @param port The port to connect to - * @returns A file descriptor to the successfully connected socket - * @throw JsonRpcException Thrown when an issue is encountered while trying to connect (see message of exception for more information about what happened). - */ - int Connect(const std::string& ip, const int& port) ; - /** - * @brief Check if provided ip is an ipv4 address. - * - * @param ip The ipv4 address to check - * @returns A boolean indicating if the provided ip is or is not an ipv4 address - */ - bool IsIpv4Address(const std::string& ip); - }; + protected: + std::string hostToConnect; /*!< The hostname or the ipv4 address on which the client should try to connect*/ + unsigned int port; /*!< The port on which the client should try to connect*/ + /** + * @brief Connects to the host and port provided by constructor parameters. + * + * This method detects if the hostToConnect attribute is either an IPv4 or a hostname. + * On first case it tries to connect to the ip. + * On second case it tries to resolve hostname to an ip and tries to connect to it if resolve was successful. + * + * @returns A file descriptor to the successfully connected socket + * @throw JsonRpcException Thrown when an issue is encountered while trying to connect (see message of exception for more information about what happened). + */ + int Connect(); + /** + * @brief Connects to provided ip and port. + * + * This method tries to connect to the provided ip and port. + * + * @param ip The ipv4 address to connect to + * @param port The port to connect to + * @returns A file descriptor to the successfully connected socket + * @throw JsonRpcException Thrown when an issue is encountered while trying to connect (see message of exception for more information about what happened). + */ + int Connect(const std::string &ip, const int &port); + /** + * @brief Check if provided ip is an ipv4 address. + * + * @param ip The ipv4 address to check + * @returns A boolean indicating if the provided ip is or is not an ipv4 address + */ + bool IsIpv4Address(const std::string &ip); + }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_LINUXTCPSOCKETCLIENT_H_ */ diff --git a/src/jsonrpccpp/client/connectors/redisclient.cpp b/src/jsonrpccpp/client/connectors/redisclient.cpp index 3745f7ea..f97a2218 100644 --- a/src/jsonrpccpp/client/connectors/redisclient.cpp +++ b/src/jsonrpccpp/client/connectors/redisclient.cpp @@ -50,8 +50,7 @@ void ProcessReply(redisReply *reply, std::string &result) { } if (reply->elements != 2) { - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "Item needs two elements"); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Item needs two elements"); } // It's the second element that we care about @@ -72,25 +71,21 @@ void ProcessReply(redisReply *reply, std::string &result) { * @param prefix Prefix for the queue name. * @param ret_queue The name is returned here. */ -void jsonrpc::GetReturnQueue(redisContext *con, const std::string &prefix, - std::string &ret_queue) { +void jsonrpc::GetReturnQueue(redisContext *con, const std::string &prefix, std::string &ret_queue) { char id[17]; std::stringstream str; genRandom(id, 16); str << prefix << "_" << id; ret_queue = str.str(); - redisReply *reply = - (redisReply *)redisCommand(con, "EXISTS %s", ret_queue.c_str()); + redisReply *reply = (redisReply *)redisCommand(con, "EXISTS %s", ret_queue.c_str()); if (reply == NULL) { - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "redis error: Failed to run queue check"); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "redis error: Failed to run queue check"); } if (reply->type != REDIS_REPLY_INTEGER) { freeReplyObject(reply); - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "redis error: Failed to run queue check"); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "redis error: Failed to run queue check"); } if (reply->integer != 0) { @@ -102,15 +97,12 @@ void jsonrpc::GetReturnQueue(redisContext *con, const std::string &prefix, freeReplyObject(reply); } -RedisClient::RedisClient(const std::string &host, int port, - const std::string &queue) - : queue(queue), con(NULL) { +RedisClient::RedisClient(const std::string &host, int port, const std::string &queue) : queue(queue), con(NULL) { this->timeout = 10; con = redisConnect(host.c_str(), port); if (con == NULL) { - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "redis error: Failed to connect"); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "redis error: Failed to connect"); } if (con->err) { @@ -132,39 +124,32 @@ RedisClient::~RedisClient() { } } -void RedisClient::SendRPCMessage(const std::string &message, - std::string &result) { +void RedisClient::SendRPCMessage(const std::string &message, std::string &result) { std::string ret_queue; GetReturnQueue(con, queue, ret_queue); redisReply *ret; std::string data = ret_queue + "!" + message; - ret = (redisReply *)redisCommand(con, "LPUSH %s %s", queue.c_str(), - data.c_str()); + ret = (redisReply *)redisCommand(con, "LPUSH %s %s", queue.c_str(), data.c_str()); if (ret == NULL) { - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "Unknown error while sending request"); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Unknown error while sending request"); } if (ret->type != REDIS_REPLY_INTEGER || ret->integer <= 0) { freeReplyObject(ret); - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "Error while sending request, queue not updated"); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Error while sending request, queue not updated"); } freeReplyObject(ret); redisReply *reply = NULL; - reply = (redisReply *)redisCommand(con, "BRPOP %s %d", ret_queue.c_str(), - this->timeout); + reply = (redisReply *)redisCommand(con, "BRPOP %s %d", ret_queue.c_str(), this->timeout); if (reply == NULL) { - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "Unknown error while getting response"); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Unknown error while getting response"); } if (reply->type == REDIS_REPLY_NIL) { freeReplyObject(reply); - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "Operation timed out"); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Operation timed out"); } ProcessReply(reply, result); diff --git a/src/jsonrpccpp/client/connectors/redisclient.h b/src/jsonrpccpp/client/connectors/redisclient.h index 00b9fa0c..6ab3fc2f 100644 --- a/src/jsonrpccpp/client/connectors/redisclient.h +++ b/src/jsonrpccpp/client/connectors/redisclient.h @@ -11,82 +11,75 @@ #define JSONRPC_CPP_REDISCLIENT_H_ #include "../iclientconnector.h" -#include #include +#include -namespace jsonrpc -{ +namespace jsonrpc { + /** + * This class is the redis implementation of an AbstractClientConnector. + * It uses hiredis to connect to a designated redis server. + * + * The RedisClient sends the json string to the RedisServer by pushing + * it to the RedisServer's queue using LPUSH. The RedisServer will pop + * the item off the queue, handle it, then send its response back via + * another queue using LPUSH. The client will wait for this response for + * `timeout` seconds using BRPOP. + * + * The queue used to handle the responses must be unique, therefore the + * RedisClient generates a random queue name with the prefix of the + * RedisServer's queue, and ensures that it is unique using EXISTS. + * It then prepends the response/return queue name to the json string + * with an exlimation mark used as a seperator. + */ + class RedisClient : public IClientConnector { + public: /** - * This class is the redis implementation of an AbstractClientConnector. - * It uses hiredis to connect to a designated redis server. - * - * The RedisClient sends the json string to the RedisServer by pushing - * it to the RedisServer's queue using LPUSH. The RedisServer will pop - * the item off the queue, handle it, then send its response back via - * another queue using LPUSH. The client will wait for this response for - * `timeout` seconds using BRPOP. - * - * The queue used to handle the responses must be unique, therefore the - * RedisClient generates a random queue name with the prefix of the - * RedisServer's queue, and ensures that it is unique using EXISTS. - * It then prepends the response/return queue name to the json string - * with an exlimation mark used as a seperator. + * RedisClient + * @param host The ip address of the redis server. + * @param port The port of the redis server. + * @param queue The queue to send to. */ - class RedisClient : public IClientConnector - { - public: - - /** - * RedisClient - * @param host The ip address of the redis server. - * @param port The port of the redis server. - * @param queue The queue to send to. - */ - RedisClient(const std::string& host, int port, const std::string& queue); - virtual ~RedisClient(); - - - /** - * This method will send an rpc message to the RedisServer and return the result. - * @param message The message to send. - * @param result The returned message from the server. - */ - virtual void SendRPCMessage(const std::string& message, std::string& result); - - - /** - * Set the queue that we are messaging with. - * @param queue The queue to send to. - */ - void SetQueue(const std::string& queue); + RedisClient(const std::string &host, int port, const std::string &queue); + virtual ~RedisClient(); + /** + * This method will send an rpc message to the RedisServer and return the result. + * @param message The message to send. + * @param result The returned message from the server. + */ + virtual void SendRPCMessage(const std::string &message, std::string &result); - /** - * Set how long we should wait for a response. - * @param timeout The length of time to wait in seconds - */ - void SetTimeout(long timeout); + /** + * Set the queue that we are messaging with. + * @param queue The queue to send to. + */ + void SetQueue(const std::string &queue); - protected: + /** + * Set how long we should wait for a response. + * @param timeout The length of time to wait in seconds + */ + void SetTimeout(long timeout); - /** - * @brief Queue that we are messaging - */ - std::string queue; + protected: + /** + * @brief Queue that we are messaging + */ + std::string queue; - /** - * @brief Timeout for http request in milliseconds - */ - long timeout; + /** + * @brief Timeout for http request in milliseconds + */ + long timeout; - /** - * @brief Our connection to the redis server - */ - redisContext * con; - }; + /** + * @brief Our connection to the redis server + */ + redisContext *con; + }; - // Exported here for unit testing purposes. - void GetReturnQueue(redisContext * con, const std::string& prefix, std::string& ret_queue); + // Exported here for unit testing purposes. + void GetReturnQueue(redisContext *con, const std::string &prefix, std::string &ret_queue); } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_REDISCLIENT_H_ */ diff --git a/src/jsonrpccpp/client/connectors/streamreader.h b/src/jsonrpccpp/client/connectors/streamreader.h index f4d631be..836b9621 100644 --- a/src/jsonrpccpp/client/connectors/streamreader.h +++ b/src/jsonrpccpp/client/connectors/streamreader.h @@ -1,11 +1,9 @@ #ifndef STREAMREADER_H #define STREAMREADER_H - -class StreamReader -{ +class StreamReader { public: - StreamReader(); + StreamReader(); }; #endif // STREAMREADER_H \ No newline at end of file diff --git a/src/jsonrpccpp/client/connectors/tcpsocketclient.cpp b/src/jsonrpccpp/client/connectors/tcpsocketclient.cpp index 13ecabde..6acbcb89 100644 --- a/src/jsonrpccpp/client/connectors/tcpsocketclient.cpp +++ b/src/jsonrpccpp/client/connectors/tcpsocketclient.cpp @@ -18,8 +18,7 @@ using namespace jsonrpc; using namespace std; -TcpSocketClient::TcpSocketClient(const std::string &ipToConnect, - const unsigned int &port) { +TcpSocketClient::TcpSocketClient(const std::string &ipToConnect, const unsigned int &port) { #ifdef _WIN32 this->realSocket = new WindowsTcpSocketClient(ipToConnect, port); #else @@ -29,8 +28,7 @@ TcpSocketClient::TcpSocketClient(const std::string &ipToConnect, TcpSocketClient::~TcpSocketClient() { delete this->realSocket; } -void TcpSocketClient::SendRPCMessage(const std::string &message, - std::string &result) { +void TcpSocketClient::SendRPCMessage(const std::string &message, std::string &result) { if (this->realSocket != NULL) { this->realSocket->SendRPCMessage(message, result); } diff --git a/src/jsonrpccpp/client/connectors/tcpsocketclient.h b/src/jsonrpccpp/client/connectors/tcpsocketclient.h index 8388d332..cb000cb3 100644 --- a/src/jsonrpccpp/client/connectors/tcpsocketclient.h +++ b/src/jsonrpccpp/client/connectors/tcpsocketclient.h @@ -14,42 +14,40 @@ #include #include -namespace jsonrpc -{ - /** - * This class provides an embedded TCP Socket Client that sends Requests over a tcp socket and read result from same socket. - * It uses the delimiter character to distinct a full RPC Message over the tcp flow. This character is parametered on - * compilation time in implementation files. The default value for this delimiter is 0x0A a.k.a. "new line". - * This class hides OS specific features in real implementation of this client. Currently it has implementation for - * both Linux and Windows. - */ - class TcpSocketClient : public IClientConnector - { - public: - /** - * @brief TcpSocketClient, constructor for the included TcpSocketClient - * - * Instanciates the real implementation of TcpSocketClientPrivate depending on running OS. - * - * @param ipToConnect The ipv4 address on which the client should try to connect - * @param port The port on which the client should try to connect - */ - TcpSocketClient(const std::string& ipToConnect, const unsigned int &port); - /** - * @brief ~TcpSocketClient, the destructor of TcpSocketClient - */ - virtual ~TcpSocketClient(); - /** - * @brief The IClientConnector::SendRPCMessage method overload. - * @param message The message to send - * @param result The result of the call returned by the servsr - * @throw JsonRpcException Thrown when an issue is encounter with socket manipulation (see message of exception for more information about what happened). - */ - virtual void SendRPCMessage(const std::string& message, std::string& result) ; +namespace jsonrpc { + /** + * This class provides an embedded TCP Socket Client that sends Requests over a tcp socket and read result from same socket. + * It uses the delimiter character to distinct a full RPC Message over the tcp flow. This character is parametered on + * compilation time in implementation files. The default value for this delimiter is 0x0A a.k.a. "new line". + * This class hides OS specific features in real implementation of this client. Currently it has implementation for + * both Linux and Windows. + */ + class TcpSocketClient : public IClientConnector { + public: + /** + * @brief TcpSocketClient, constructor for the included TcpSocketClient + * + * Instanciates the real implementation of TcpSocketClientPrivate depending on running OS. + * + * @param ipToConnect The ipv4 address on which the client should try to connect + * @param port The port on which the client should try to connect + */ + TcpSocketClient(const std::string &ipToConnect, const unsigned int &port); + /** + * @brief ~TcpSocketClient, the destructor of TcpSocketClient + */ + virtual ~TcpSocketClient(); + /** + * @brief The IClientConnector::SendRPCMessage method overload. + * @param message The message to send + * @param result The result of the call returned by the servsr + * @throw JsonRpcException Thrown when an issue is encounter with socket manipulation (see message of exception for more information about what happened). + */ + virtual void SendRPCMessage(const std::string &message, std::string &result); - protected: - IClientConnector *realSocket; /*!< A pointer to the real implementation of this class depending of running OS*/ - }; + protected: + IClientConnector *realSocket; /*!< A pointer to the real implementation of this class depending of running OS*/ + }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_TCPSOCKETCLIENT_H_ */ diff --git a/src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp b/src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp index 9a50062f..5e975755 100644 --- a/src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp +++ b/src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp @@ -23,45 +23,38 @@ using namespace jsonrpc; using namespace std; -UnixDomainSocketClient::UnixDomainSocketClient(const std::string &path) - : path(path) {} +UnixDomainSocketClient::UnixDomainSocketClient(const std::string &path) : path(path) {} UnixDomainSocketClient::~UnixDomainSocketClient() {} -void UnixDomainSocketClient::SendRPCMessage(const std::string &message, - std::string &result) { +void UnixDomainSocketClient::SendRPCMessage(const std::string &message, std::string &result) { sockaddr_un address; int socket_fd; socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); if (socket_fd < 0) { - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "Could not create unix domain socket"); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Could not create unix domain socket"); } memset(&address, 0, sizeof(sockaddr_un)); address.sun_family = AF_UNIX; strncpy(address.sun_path, this->path.c_str(), 107); - if (connect(socket_fd, (struct sockaddr *)&address, sizeof(sockaddr_un)) != - 0) { + if (connect(socket_fd, (struct sockaddr *)&address, sizeof(sockaddr_un)) != 0) { close(socket_fd); - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "Could not connect to: " + this->path); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Could not connect to: " + this->path); } StreamWriter writer; string toSend = message + DEFAULT_DELIMITER_CHAR; if (!writer.Write(toSend, socket_fd)) { close(socket_fd); - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "Could not write request"); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Could not write request"); } StreamReader reader(DEFAULT_BUFFER_SIZE); if (!reader.Read(result, socket_fd, DEFAULT_DELIMITER_CHAR)) { close(socket_fd); - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "Could not read response"); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Could not read response"); } close(socket_fd); } diff --git a/src/jsonrpccpp/client/connectors/unixdomainsocketclient.h b/src/jsonrpccpp/client/connectors/unixdomainsocketclient.h index 055c9df1..a1f02f24 100644 --- a/src/jsonrpccpp/client/connectors/unixdomainsocketclient.h +++ b/src/jsonrpccpp/client/connectors/unixdomainsocketclient.h @@ -13,18 +13,16 @@ #include "../iclientconnector.h" #include -namespace jsonrpc -{ - class UnixDomainSocketClient : public IClientConnector - { - public: - UnixDomainSocketClient(const std::string& path); - virtual ~UnixDomainSocketClient(); - virtual void SendRPCMessage(const std::string& message, std::string& result) ; +namespace jsonrpc { + class UnixDomainSocketClient : public IClientConnector { + public: + UnixDomainSocketClient(const std::string &path); + virtual ~UnixDomainSocketClient(); + virtual void SendRPCMessage(const std::string &message, std::string &result); - protected: - std::string path; - }; + protected: + std::string path; + }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_UNIXDOMAINSOCKETCLIENT_H_ */ diff --git a/src/jsonrpccpp/client/connectors/windowstcpsocketclient.cpp b/src/jsonrpccpp/client/connectors/windowstcpsocketclient.cpp index 3b66ca5c..868668b7 100644 --- a/src/jsonrpccpp/client/connectors/windowstcpsocketclient.cpp +++ b/src/jsonrpccpp/client/connectors/windowstcpsocketclient.cpp @@ -23,14 +23,11 @@ using namespace jsonrpc; using namespace std; -WindowsTcpSocketClient::WindowsTcpSocketClient(const std::string &hostToConnect, - const unsigned int &port) - : hostToConnect(hostToConnect), port(port) {} +WindowsTcpSocketClient::WindowsTcpSocketClient(const std::string &hostToConnect, const unsigned int &port) : hostToConnect(hostToConnect), port(port) {} WindowsTcpSocketClient::~WindowsTcpSocketClient() {} -void WindowsTcpSocketClient::SendRPCMessage( - const std::string &message, std::string &result) throw(JsonRpcException) { +void WindowsTcpSocketClient::SendRPCMessage(const std::string &message, std::string &result) throw(JsonRpcException) { SOCKET socket_fd = this->Connect(); char buffer[BUFFER_SIZE]; bool fullyWritten = false; @@ -113,9 +110,7 @@ void WindowsTcpSocketClient::SendRPCMessage( string WindowsTcpSocketClient::GetErrorMessage(const int &e) { LPVOID lpMsgBuf; lpMsgBuf = (LPVOID) "Unknown error"; - FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, e, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, e, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL); string message(static_cast(lpMsgBuf)); LocalFree(lpMsgBuf); @@ -135,21 +130,17 @@ SOCKET WindowsTcpSocketClient::Connect() throw(JsonRpcException) { hints.ai_protocol = IPPROTO_TCP; char port[6]; itoa(this->port, port, 10); - DWORD retval = - getaddrinfo(this->hostToConnect.c_str(), port, &hints, &result); + DWORD retval = getaddrinfo(this->hostToConnect.c_str(), port, &hints, &result); if (retval != 0) - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "Could not resolve hostname."); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Could not resolve hostname."); bool foundValidIp = false; SOCKET socket_fd = INVALID_SOCKET; - for (struct addrinfo *temp = result; (temp != NULL) && !foundValidIp; - temp = temp->ai_next) { + for (struct addrinfo *temp = result; (temp != NULL) && !foundValidIp; temp = temp->ai_next) { if (temp->ai_family == AF_INET) { try { SOCKADDR_IN *sock = reinterpret_cast(temp->ai_addr); - socket_fd = - this->Connect(inet_ntoa(sock->sin_addr), ntohs(sock->sin_port)); + socket_fd = this->Connect(inet_ntoa(sock->sin_addr), ntohs(sock->sin_port)); foundValidIp = true; } catch (const JsonRpcException &e) { foundValidIp = false; @@ -163,18 +154,15 @@ SOCKET WindowsTcpSocketClient::Connect() throw(JsonRpcException) { if (!foundValidIp) { closesocket(socket_fd); - throw JsonRpcException( - Errors::ERROR_CLIENT_CONNECTOR, - "Hostname resolved but connection was refused on the given port."); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Hostname resolved but connection was refused on the given port."); } - + return socket_fd; } } SOCKET -WindowsTcpSocketClient::Connect(const string &ip, - const int &port) throw(JsonRpcException) { +WindowsTcpSocketClient::Connect(const string &ip, const int &port) throw(JsonRpcException) { SOCKADDR_IN address; SOCKET socket_fd = socket(AF_INET, SOCK_STREAM, 0); if (socket_fd == INVALID_SOCKET) { @@ -205,8 +193,7 @@ WindowsTcpSocketClient::Connect(const string &ip, address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr(ip.c_str()); address.sin_port = htons(port); - if (connect(socket_fd, reinterpret_cast(&address), - sizeof(SOCKADDR_IN)) != 0) { + if (connect(socket_fd, reinterpret_cast(&address), sizeof(SOCKADDR_IN)) != 0) { string message = "connect() failed"; int err = WSAGetLastError(); switch (err) { @@ -238,9 +225,7 @@ WindowsTcpSocketClient::Connect(const string &ip, return socket_fd; } -bool WindowsTcpSocketClient::IsIpv4Address(const std::string &ip) { - return (inet_addr(ip.c_str()) != INADDR_NONE); -} +bool WindowsTcpSocketClient::IsIpv4Address(const std::string &ip) { return (inet_addr(ip.c_str()) != INADDR_NONE); } // This is inspired from SFML to manage Winsock initialization. Thanks to them! // ( http://www.sfml-dev.org/ ). @@ -250,8 +235,7 @@ struct ClientSocketInitializer { { WSADATA init; if (WSAStartup(MAKEWORD(2, 2), &init) != 0) { - throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "An issue occurred while WSAStartup executed."); + throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "An issue occurred while WSAStartup executed."); } } diff --git a/src/jsonrpccpp/client/connectors/windowstcpsocketclient.h b/src/jsonrpccpp/client/connectors/windowstcpsocketclient.h index c4f0288a..657b484d 100644 --- a/src/jsonrpccpp/client/connectors/windowstcpsocketclient.h +++ b/src/jsonrpccpp/client/connectors/windowstcpsocketclient.h @@ -10,77 +10,75 @@ #ifndef JSONRPC_CPP_WINDOWSTCPSOCKETCLIENT_H_ #define JSONRPC_CPP_WINDOWSTCPSOCKETCLIENT_H_ +#include #include #include -#include #include -namespace jsonrpc -{ +namespace jsonrpc { + /** + * This class is the windows implementation of TCPSocketClient. + * It uses the Winsock2 API to performs its job. + */ + class WindowsTcpSocketClient : public IClientConnector { + public: + /** + * @brief WindowsTcpSocketClient, constructor of the Windows implementation of class TcpSocketClient + * @param hostToConnect The hostname or the ipv4 address on which the client should try to connect + * @param port The port on which the client should try to connect + */ + WindowsTcpSocketClient(const std::string &hostToConnect, const unsigned int &port); /** - * This class is the windows implementation of TCPSocketClient. - * It uses the Winsock2 API to performs its job. + * @brief ~WindowsTcpSocketClient, the destructor of WindowsTcpSocketClient */ - class WindowsTcpSocketClient : public IClientConnector - { - public: - /** - * @brief WindowsTcpSocketClient, constructor of the Windows implementation of class TcpSocketClient - * @param hostToConnect The hostname or the ipv4 address on which the client should try to connect - * @param port The port on which the client should try to connect - */ - WindowsTcpSocketClient(const std::string& hostToConnect, const unsigned int &port); - /** - * @brief ~WindowsTcpSocketClient, the destructor of WindowsTcpSocketClient - */ - virtual ~WindowsTcpSocketClient(); - /** - * @brief The real implementation of TcpSocketClient::SendRPCMessage method. - * @param message The message to send - * @param result The result of the call returned by the server - * @throw JsonRpcException Thrown when an issue is encounter with socket manipulation (see message of exception for more information about what happened). - */ - virtual void SendRPCMessage(const std::string& message, std::string& result) ; + virtual ~WindowsTcpSocketClient(); + /** + * @brief The real implementation of TcpSocketClient::SendRPCMessage method. + * @param message The message to send + * @param result The result of the call returned by the server + * @throw JsonRpcException Thrown when an issue is encounter with socket manipulation (see message of exception for more information about what happened). + */ + virtual void SendRPCMessage(const std::string &message, std::string &result); - protected: - std::string hostToConnect; /*!< The hostname or the ipv4 address on which the client should try to connect*/ - unsigned int port; /*!< The port on which the client should try to connect*/ - /** - * @brief A method to produce human readable messages from Winsock2 error values. - * @param e A Winsock2 error value - * @return The message matching the error value - */ - static std::string GetErrorMessage(const int &e); - /** - * @brief Connects to the host and port provided by constructor parameters. - * - * This method detects if the hostToConnect attribute is either an IPv4 or a hostname. - * On first case it tries to connect to the ip. - * On second case it tries to resolve hostname to an ip and tries to connect to it if resolve was successful. - * - * @returns A file descriptor to the successfully connected socket - * @throw JsonRpcException Thrown when an issue is encountered while trying to connect (see message of exception for more information about what happened). - */ - SOCKET Connect() ; - /** - * @brief Connects to provided ip and port. - * - * This method tries to connect to the provided ip and port. - * - * @param ip The ipv4 address to connect to - * @param port The port to connect to - * @returns A file descriptor to the successfully connected socket - * @throw JsonRpcException Thrown when an issue is encountered while trying to connect (see message of exception for more information about what happened). - */ - SOCKET Connect(const std::string& ip, const int& port) ; - /** - * @brief Check if provided ip is an ipv4 address. - * - * @param ip The ipv4 address to check - * @returns A boolean indicating if the provided ip is or is not an ipv4 address - */ - bool IsIpv4Address(const std::string& ip); - }; + protected: + std::string hostToConnect; /*!< The hostname or the ipv4 address on which the client should try to connect*/ + unsigned int port; /*!< The port on which the client should try to connect*/ + /** + * @brief A method to produce human readable messages from Winsock2 error values. + * @param e A Winsock2 error value + * @return The message matching the error value + */ + static std::string GetErrorMessage(const int &e); + /** + * @brief Connects to the host and port provided by constructor parameters. + * + * This method detects if the hostToConnect attribute is either an IPv4 or a hostname. + * On first case it tries to connect to the ip. + * On second case it tries to resolve hostname to an ip and tries to connect to it if resolve was successful. + * + * @returns A file descriptor to the successfully connected socket + * @throw JsonRpcException Thrown when an issue is encountered while trying to connect (see message of exception for more information about what happened). + */ + SOCKET Connect(); + /** + * @brief Connects to provided ip and port. + * + * This method tries to connect to the provided ip and port. + * + * @param ip The ipv4 address to connect to + * @param port The port to connect to + * @returns A file descriptor to the successfully connected socket + * @throw JsonRpcException Thrown when an issue is encountered while trying to connect (see message of exception for more information about what happened). + */ + SOCKET Connect(const std::string &ip, const int &port); + /** + * @brief Check if provided ip is an ipv4 address. + * + * @param ip The ipv4 address to check + * @returns A boolean indicating if the provided ip is or is not an ipv4 address + */ + bool IsIpv4Address(const std::string &ip); + }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_WINDOWSTCPSOCKETCLIENT_H_ */ diff --git a/src/jsonrpccpp/client/iclientconnector.h b/src/jsonrpccpp/client/iclientconnector.h index a95696ae..cbdf286b 100644 --- a/src/jsonrpccpp/client/iclientconnector.h +++ b/src/jsonrpccpp/client/iclientconnector.h @@ -10,17 +10,15 @@ #ifndef JSONRPC_CPP_CLIENTCONNECTOR_H_ #define JSONRPC_CPP_CLIENTCONNECTOR_H_ -#include #include +#include -namespace jsonrpc -{ - class IClientConnector - { - public: - virtual ~IClientConnector(){} +namespace jsonrpc { + class IClientConnector { + public: + virtual ~IClientConnector() {} - virtual void SendRPCMessage(const std::string& message, std::string& result) = 0; - }; + virtual void SendRPCMessage(const std::string &message, std::string &result) = 0; + }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_CLIENTCONNECTOR_H_ */ diff --git a/src/jsonrpccpp/client/rpcprotocolclient.cpp b/src/jsonrpccpp/client/rpcprotocolclient.cpp index cb7ff0f0..8d85d226 100644 --- a/src/jsonrpccpp/client/rpcprotocolclient.cpp +++ b/src/jsonrpccpp/client/rpcprotocolclient.cpp @@ -23,13 +23,9 @@ const std::string RpcProtocolClient::KEY_ERROR_CODE = "code"; const std::string RpcProtocolClient::KEY_ERROR_MESSAGE = "message"; const std::string RpcProtocolClient::KEY_ERROR_DATA = "data"; -RpcProtocolClient::RpcProtocolClient(clientVersion_t version, - bool omitEndingLineFeed) - : version(version), omitEndingLineFeed(omitEndingLineFeed) {} +RpcProtocolClient::RpcProtocolClient(clientVersion_t version, bool omitEndingLineFeed) : version(version), omitEndingLineFeed(omitEndingLineFeed) {} -void RpcProtocolClient::BuildRequest(const std::string &method, - const Json::Value ¶meter, - std::string &result, bool isNotification) { +void RpcProtocolClient::BuildRequest(const std::string &method, const Json::Value ¶meter, std::string &result, bool isNotification) { Json::Value request; Json::StreamWriterBuilder wbuilder; wbuilder["indentation"] = ""; @@ -38,8 +34,7 @@ void RpcProtocolClient::BuildRequest(const std::string &method, result = Json::writeString(wbuilder, request); } -void RpcProtocolClient::HandleResponse(const std::string &response, - Json::Value &result) { +void RpcProtocolClient::HandleResponse(const std::string &response, Json::Value &result) { Json::Reader reader; Json::Value value; @@ -47,16 +42,14 @@ void RpcProtocolClient::HandleResponse(const std::string &response, if (reader.parse(response, value)) { this->HandleResponse(value, result); } else { - throw JsonRpcException(Errors::ERROR_RPC_JSON_PARSE_ERROR, - " " + response); + throw JsonRpcException(Errors::ERROR_RPC_JSON_PARSE_ERROR, " " + response); } } catch (Json::Exception &e) { throw JsonRpcException(Errors::ERROR_RPC_JSON_PARSE_ERROR, " " + response); } } -Json::Value RpcProtocolClient::HandleResponse(const Json::Value &value, - Json::Value &result) { +Json::Value RpcProtocolClient::HandleResponse(const Json::Value &value, Json::Value &result) { if (this->ValidateResponse(value)) { if (this->HasError(value)) { this->throwErrorException(value); @@ -64,15 +57,12 @@ Json::Value RpcProtocolClient::HandleResponse(const Json::Value &value, result = value[KEY_RESULT]; } } else { - throw JsonRpcException(Errors::ERROR_CLIENT_INVALID_RESPONSE, - " " + value.toStyledString()); + throw JsonRpcException(Errors::ERROR_CLIENT_INVALID_RESPONSE, " " + value.toStyledString()); } return value[KEY_ID]; } -void RpcProtocolClient::BuildRequest(int id, const std::string &method, - const Json::Value ¶meter, - Json::Value &result, bool isNotification) { +void RpcProtocolClient::BuildRequest(int id, const std::string &method, const Json::Value ¶meter, Json::Value &result, bool isNotification) { if (this->version == JSONRPC_CLIENT_V2) result[KEY_PROTOCOL_VERSION] = "2.0"; result[KEY_PROCEDURE_NAME] = method; @@ -85,15 +75,12 @@ void RpcProtocolClient::BuildRequest(int id, const std::string &method, } void RpcProtocolClient::throwErrorException(const Json::Value &response) { - if (response[KEY_ERROR].isMember(KEY_ERROR_MESSAGE) && - response[KEY_ERROR][KEY_ERROR_MESSAGE].isString()) { + if (response[KEY_ERROR].isMember(KEY_ERROR_MESSAGE) && response[KEY_ERROR][KEY_ERROR_MESSAGE].isString()) { if (response[KEY_ERROR].isMember(KEY_ERROR_DATA)) { - throw JsonRpcException(response[KEY_ERROR][KEY_ERROR_CODE].asInt(), - response[KEY_ERROR][KEY_ERROR_MESSAGE].asString(), + throw JsonRpcException(response[KEY_ERROR][KEY_ERROR_CODE].asInt(), response[KEY_ERROR][KEY_ERROR_MESSAGE].asString(), response[KEY_ERROR][KEY_ERROR_DATA]); } else { - throw JsonRpcException(response[KEY_ERROR][KEY_ERROR_CODE].asInt(), - response[KEY_ERROR][KEY_ERROR_MESSAGE].asString()); + throw JsonRpcException(response[KEY_ERROR][KEY_ERROR_CODE].asInt(), response[KEY_ERROR][KEY_ERROR_MESSAGE].asString()); } } else { throw JsonRpcException(response[KEY_ERROR][KEY_ERROR_CODE].asInt()); @@ -110,22 +97,17 @@ bool RpcProtocolClient::ValidateResponse(const Json::Value &response) { if (!response[KEY_RESULT].isNull() && !response[KEY_ERROR].isNull()) return false; if (!response[KEY_ERROR].isNull() && - !(response[KEY_ERROR].isObject() && - response[KEY_ERROR].isMember(KEY_ERROR_CODE) && - response[KEY_ERROR][KEY_ERROR_CODE].isIntegral())) + !(response[KEY_ERROR].isObject() && response[KEY_ERROR].isMember(KEY_ERROR_CODE) && response[KEY_ERROR][KEY_ERROR_CODE].isIntegral())) return false; } else if (this->version == JSONRPC_CLIENT_V2) { - if (!response.isMember(KEY_PROTOCOL_VERSION) || - response[KEY_PROTOCOL_VERSION] != "2.0") + if (!response.isMember(KEY_PROTOCOL_VERSION) || response[KEY_PROTOCOL_VERSION] != "2.0") return false; if (response.isMember(KEY_RESULT) && response.isMember(KEY_ERROR)) return false; if (!response.isMember(KEY_RESULT) && !response.isMember(KEY_ERROR)) return false; if (response.isMember(KEY_ERROR) && - !(response[KEY_ERROR].isObject() && - response[KEY_ERROR].isMember(KEY_ERROR_CODE) && - response[KEY_ERROR][KEY_ERROR_CODE].isIntegral())) + !(response[KEY_ERROR].isObject() && response[KEY_ERROR].isMember(KEY_ERROR_CODE) && response[KEY_ERROR][KEY_ERROR_CODE].isIntegral())) return false; } diff --git a/src/jsonrpccpp/client/rpcprotocolclient.h b/src/jsonrpccpp/client/rpcprotocolclient.h index 6cc4ceca..20cbfafe 100644 --- a/src/jsonrpccpp/client/rpcprotocolclient.h +++ b/src/jsonrpccpp/client/rpcprotocolclient.h @@ -10,75 +10,72 @@ #ifndef RESPONSEHANDLER_H #define RESPONSEHANDLER_H +#include "client.h" #include #include #include -#include "client.h" namespace jsonrpc { + /** + * @brief The RpcProtocolClient class handles the json-rpc 2.0 protocol for the client side. + */ + class RpcProtocolClient { + public: + RpcProtocolClient(clientVersion_t version = JSONRPC_CLIENT_V2, bool omitEndingLineFeed = false); /** - * @brief The RpcProtocolClient class handles the json-rpc 2.0 protocol for the client side. + * @brief This method builds a valid json-rpc 2.0 request object based on passed parameters. + * The id starts at 1 and is incremented for each request. To reset this value to one, call + * the jsonrpc::RpcProRpcProtocolClient::resetId() method. + * @param method - name of method or notification to be called + * @param parameter - parameters represented as json objects + * @return the string representation of the request to be built. */ - class RpcProtocolClient - { - public: - RpcProtocolClient(clientVersion_t version = JSONRPC_CLIENT_V2, bool omitEndingLineFeed = false); - - /** - * @brief This method builds a valid json-rpc 2.0 request object based on passed parameters. - * The id starts at 1 and is incremented for each request. To reset this value to one, call - * the jsonrpc::RpcProRpcProtocolClient::resetId() method. - * @param method - name of method or notification to be called - * @param parameter - parameters represented as json objects - * @return the string representation of the request to be built. - */ - std::string BuildRequest(const std::string& method, const Json::Value& parameter, bool isNotification); - - /** - * @brief BuildRequest does the same as std::string jsonrpc::RpcProRpcProtocolClient::BuildRequest(const std::string& method, const Json::Value& parameter); - * The only difference here is that the result is returend by value, using the result parameter. - * @param method - name of method or notification to be called - * @param parameter - parameters represented as json objects - * @param result - the string representation will be hold within this reference. - */ - void BuildRequest(const std::string& method, const Json::Value& parameter, std::string& result, bool isNotification); + std::string BuildRequest(const std::string &method, const Json::Value ¶meter, bool isNotification); + /** + * @brief BuildRequest does the same as std::string jsonrpc::RpcProRpcProtocolClient::BuildRequest(const std::string& method, const Json::Value& parameter); + * The only difference here is that the result is returend by value, using the result parameter. + * @param method - name of method or notification to be called + * @param parameter - parameters represented as json objects + * @param result - the string representation will be hold within this reference. + */ + void BuildRequest(const std::string &method, const Json::Value ¶meter, std::string &result, bool isNotification); - /** - * @brief Does the same as Json::Value RpcProtocolClient::HandleResponse(const std::string& response) throw(Exception) - * but returns result as reference for performance speed up. - */ - void HandleResponse(const std::string &response, Json::Value &result) ; + /** + * @brief Does the same as Json::Value RpcProtocolClient::HandleResponse(const std::string& response) throw(Exception) + * but returns result as reference for performance speed up. + */ + void HandleResponse(const std::string &response, Json::Value &result); - /** - * @brief HandleResponse - * @param response - * @param result - * @return response id - */ - Json::Value HandleResponse(const Json::Value &response, Json::Value &result) ; + /** + * @brief HandleResponse + * @param response + * @param result + * @return response id + */ + Json::Value HandleResponse(const Json::Value &response, Json::Value &result); - static const std::string KEY_PROTOCOL_VERSION; - static const std::string KEY_PROCEDURE_NAME; - static const std::string KEY_ID; - static const std::string KEY_PARAMETER; - static const std::string KEY_AUTH; - static const std::string KEY_RESULT; - static const std::string KEY_ERROR; - static const std::string KEY_ERROR_CODE; - static const std::string KEY_ERROR_MESSAGE; - static const std::string KEY_ERROR_DATA; + static const std::string KEY_PROTOCOL_VERSION; + static const std::string KEY_PROCEDURE_NAME; + static const std::string KEY_ID; + static const std::string KEY_PARAMETER; + static const std::string KEY_AUTH; + static const std::string KEY_RESULT; + static const std::string KEY_ERROR; + static const std::string KEY_ERROR_CODE; + static const std::string KEY_ERROR_MESSAGE; + static const std::string KEY_ERROR_DATA; - private: - clientVersion_t version; - bool omitEndingLineFeed; + private: + clientVersion_t version; + bool omitEndingLineFeed; - void BuildRequest(int id, const std::string& method, const Json::Value& parameter, Json::Value& result, bool isNotification); - bool ValidateResponse(const Json::Value &response); - bool HasError(const Json::Value &response); - void throwErrorException(const Json::Value &response); - }; -} + void BuildRequest(int id, const std::string &method, const Json::Value ¶meter, Json::Value &result, bool isNotification); + bool ValidateResponse(const Json::Value &response); + bool HasError(const Json::Value &response); + void throwErrorException(const Json::Value &response); + }; +} // namespace jsonrpc #endif // RESPONSEHANDLER_H diff --git a/src/jsonrpccpp/common/errors.cpp b/src/jsonrpccpp/common/errors.cpp index 550f00ab..1072ce25 100644 --- a/src/jsonrpccpp/common/errors.cpp +++ b/src/jsonrpccpp/common/errors.cpp @@ -42,22 +42,16 @@ Errors::_init::_init() { possibleErrors[ERROR_RPC_INVALID_PARAMS] = "INVALID_PARAMS: Invalid method " "parameters (invalid name and/or " "type) recognised"; - possibleErrors[ERROR_RPC_JSON_PARSE_ERROR] = - "JSON_PARSE_ERROR: The JSON-Object is not JSON-Valid"; + possibleErrors[ERROR_RPC_JSON_PARSE_ERROR] = "JSON_PARSE_ERROR: The JSON-Object is not JSON-Valid"; possibleErrors[ERROR_RPC_INTERNAL_ERROR] = "INTERNAL_ERROR: "; - possibleErrors[ERROR_SERVER_PROCEDURE_IS_METHOD] = - "PROCEDURE_IS_METHOD: The requested notification is declared as a method"; - possibleErrors[ERROR_SERVER_PROCEDURE_IS_NOTIFICATION] = - "PROCEDURE_IS_NOTIFICATION: The requested method is declared as " - "notification"; - possibleErrors[ERROR_SERVER_PROCEDURE_POINTER_IS_NULL] = - "PROCEDURE_POINTER_IS_NULL: Server has no function Reference registered"; - possibleErrors[ERROR_SERVER_PROCEDURE_SPECIFICATION_NOT_FOUND] = - "Configuration file was not found"; + possibleErrors[ERROR_SERVER_PROCEDURE_IS_METHOD] = "PROCEDURE_IS_METHOD: The requested notification is declared as a method"; + possibleErrors[ERROR_SERVER_PROCEDURE_IS_NOTIFICATION] = "PROCEDURE_IS_NOTIFICATION: The requested method is declared as " + "notification"; + possibleErrors[ERROR_SERVER_PROCEDURE_POINTER_IS_NULL] = "PROCEDURE_POINTER_IS_NULL: Server has no function Reference registered"; + possibleErrors[ERROR_SERVER_PROCEDURE_SPECIFICATION_NOT_FOUND] = "Configuration file was not found"; - possibleErrors[ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX] = - "Procedure specification mallformed"; + possibleErrors[ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX] = "Procedure specification mallformed"; possibleErrors[ERROR_CLIENT_INVALID_RESPONSE] = "The response is invalid"; possibleErrors[ERROR_CLIENT_CONNECTOR] = "Client connector error"; diff --git a/src/jsonrpccpp/common/errors.h b/src/jsonrpccpp/common/errors.h index d6c4879e..9f8caebc 100644 --- a/src/jsonrpccpp/common/errors.h +++ b/src/jsonrpccpp/common/errors.h @@ -15,50 +15,48 @@ #include "jsonparser.h" -namespace jsonrpc -{ - class JsonRpcException; - - class Errors - { - public: - /** - * @return error message to corresponding error code. - */ - static std::string GetErrorMessage(int errorCode); - - static class _init - { - public: - _init(); - } _initializer; - - /** - * Official JSON-RPC 2.0 Errors - */ - static const int ERROR_RPC_JSON_PARSE_ERROR; - static const int ERROR_RPC_METHOD_NOT_FOUND; - static const int ERROR_RPC_INVALID_REQUEST; - static const int ERROR_RPC_INVALID_PARAMS; - static const int ERROR_RPC_INTERNAL_ERROR; - - /** - * Server Library Errors - */ - static const int ERROR_SERVER_PROCEDURE_IS_METHOD; - static const int ERROR_SERVER_PROCEDURE_IS_NOTIFICATION; - static const int ERROR_SERVER_PROCEDURE_POINTER_IS_NULL; - static const int ERROR_SERVER_PROCEDURE_SPECIFICATION_NOT_FOUND; - static const int ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX; - static const int ERROR_SERVER_CONNECTOR; - - /** - * Client Library Errors - */ - static const int ERROR_CLIENT_CONNECTOR; - static const int ERROR_CLIENT_INVALID_RESPONSE; - private: - static std::map possibleErrors; - }; +namespace jsonrpc { + class JsonRpcException; + + class Errors { + public: + /** + * @return error message to corresponding error code. + */ + static std::string GetErrorMessage(int errorCode); + + static class _init { + public: + _init(); + } _initializer; + + /** + * Official JSON-RPC 2.0 Errors + */ + static const int ERROR_RPC_JSON_PARSE_ERROR; + static const int ERROR_RPC_METHOD_NOT_FOUND; + static const int ERROR_RPC_INVALID_REQUEST; + static const int ERROR_RPC_INVALID_PARAMS; + static const int ERROR_RPC_INTERNAL_ERROR; + + /** + * Server Library Errors + */ + static const int ERROR_SERVER_PROCEDURE_IS_METHOD; + static const int ERROR_SERVER_PROCEDURE_IS_NOTIFICATION; + static const int ERROR_SERVER_PROCEDURE_POINTER_IS_NULL; + static const int ERROR_SERVER_PROCEDURE_SPECIFICATION_NOT_FOUND; + static const int ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX; + static const int ERROR_SERVER_CONNECTOR; + + /** + * Client Library Errors + */ + static const int ERROR_CLIENT_CONNECTOR; + static const int ERROR_CLIENT_INVALID_RESPONSE; + + private: + static std::map possibleErrors; + }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_ERRORS_H_ */ diff --git a/src/jsonrpccpp/common/exception.cpp b/src/jsonrpccpp/common/exception.cpp index 787672b9..a4201650 100644 --- a/src/jsonrpccpp/common/exception.cpp +++ b/src/jsonrpccpp/common/exception.cpp @@ -11,21 +11,16 @@ using namespace jsonrpc; -JsonRpcException::JsonRpcException(int code) - : code(code), message(Errors::GetErrorMessage(code)) { - this->setWhatMessage(); -} +JsonRpcException::JsonRpcException(int code) : code(code), message(Errors::GetErrorMessage(code)) { this->setWhatMessage(); } -JsonRpcException::JsonRpcException(int code, const std::string &message) - : code(code), message(Errors::GetErrorMessage(code)) { +JsonRpcException::JsonRpcException(int code, const std::string &message) : code(code), message(Errors::GetErrorMessage(code)) { if (!this->message.empty()) this->message = this->message + ": "; this->message = this->message + message; this->setWhatMessage(); } -JsonRpcException::JsonRpcException(int code, const std::string &message, - const Json::Value &data) +JsonRpcException::JsonRpcException(int code, const std::string &message, const Json::Value &data) : code(code), message(Errors::GetErrorMessage(code)), data(data) { if (!this->message.empty()) this->message = this->message + ": "; @@ -33,10 +28,7 @@ JsonRpcException::JsonRpcException(int code, const std::string &message, this->setWhatMessage(); } -JsonRpcException::JsonRpcException(const std::string &message) - : code(0), message(message) { - this->setWhatMessage(); -} +JsonRpcException::JsonRpcException(const std::string &message) : code(0), message(message) { this->setWhatMessage(); } JsonRpcException::~JsonRpcException() throw() {} @@ -46,9 +38,7 @@ const std::string &JsonRpcException::GetMessage() const { return message; } const Json::Value &JsonRpcException::GetData() const { return data; } -const char *JsonRpcException::what() const throw() { - return this->whatString.c_str(); -} +const char *JsonRpcException::what() const throw() { return this->whatString.c_str(); } void JsonRpcException::setWhatMessage() { if (this->code != 0) { diff --git a/src/jsonrpccpp/common/exception.h b/src/jsonrpccpp/common/exception.h index 847d1f64..b9abba8e 100644 --- a/src/jsonrpccpp/common/exception.h +++ b/src/jsonrpccpp/common/exception.h @@ -10,37 +10,35 @@ #ifndef JSONRPC_CPP_EXCEPTION_H_ #define JSONRPC_CPP_EXCEPTION_H_ -#include -#include #include +#include +#include #include "errors.h" -namespace jsonrpc -{ - class JsonRpcException: public std::exception - { - public: - JsonRpcException(int code); - JsonRpcException(int code, const std::string& message); - JsonRpcException(int code, const std::string& message, const Json::Value &data); - JsonRpcException(const std::string& message); - - virtual ~JsonRpcException() throw (); - - int GetCode() const; - const std::string& GetMessage() const; - const Json::Value& GetData() const; - - virtual const char* what() const throw (); - - private: - int code; - std::string message; - std::string whatString; - Json::Value data; - void setWhatMessage(); - }; +namespace jsonrpc { + class JsonRpcException : public std::exception { + public: + JsonRpcException(int code); + JsonRpcException(int code, const std::string &message); + JsonRpcException(int code, const std::string &message, const Json::Value &data); + JsonRpcException(const std::string &message); + + virtual ~JsonRpcException() throw(); + + int GetCode() const; + const std::string &GetMessage() const; + const Json::Value &GetData() const; + + virtual const char *what() const throw(); + + private: + int code; + std::string message; + std::string whatString; + Json::Value data; + void setWhatMessage(); + }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_EXCEPTION_H_ */ diff --git a/src/jsonrpccpp/common/procedure.cpp b/src/jsonrpccpp/common/procedure.cpp index c46f26af..02069853 100644 --- a/src/jsonrpccpp/common/procedure.cpp +++ b/src/jsonrpccpp/common/procedure.cpp @@ -16,12 +16,9 @@ using namespace std; using namespace jsonrpc; -Procedure::Procedure() - : procedureName(""), procedureType(RPC_METHOD), returntype(JSON_BOOLEAN), - paramDeclaration(PARAMS_BY_NAME) {} +Procedure::Procedure() : procedureName(""), procedureType(RPC_METHOD), returntype(JSON_BOOLEAN), paramDeclaration(PARAMS_BY_NAME) {} -Procedure::Procedure(const string &name, parameterDeclaration_t paramType, - jsontype_t returntype, ...) { +Procedure::Procedure(const string &name, parameterDeclaration_t paramType, jsontype_t returntype, ...) { va_list parameters; va_start(parameters, returntype); const char *paramname = va_arg(parameters, const char *); @@ -37,8 +34,7 @@ Procedure::Procedure(const string &name, parameterDeclaration_t paramType, this->procedureType = RPC_METHOD; this->paramDeclaration = paramType; } -Procedure::Procedure(const string &name, parameterDeclaration_t paramType, - ...) { +Procedure::Procedure(const string &name, parameterDeclaration_t paramType, ...) { va_list parameters; va_start(parameters, paramType); const char *paramname = va_arg(parameters, const char *); @@ -61,35 +57,22 @@ bool Procedure::ValdiateParameters(const Json::Value ¶meters) const { } if (parameters.isArray() && this->paramDeclaration == PARAMS_BY_POSITION) { return this->ValidatePositionalParameters(parameters); - } else if (parameters.isObject() && - this->paramDeclaration == PARAMS_BY_NAME) { + } else if (parameters.isObject() && this->paramDeclaration == PARAMS_BY_NAME) { return this->ValidateNamedParameters(parameters); } else { return false; } } -const parameterNameList_t &Procedure::GetParameters() const { - return this->parametersName; -} +const parameterNameList_t &Procedure::GetParameters() const { return this->parametersName; } procedure_t Procedure::GetProcedureType() const { return this->procedureType; } -const std::string &Procedure::GetProcedureName() const { - return this->procedureName; -} -parameterDeclaration_t Procedure::GetParameterDeclarationType() const { - return this->paramDeclaration; -} +const std::string &Procedure::GetProcedureName() const { return this->procedureName; } +parameterDeclaration_t Procedure::GetParameterDeclarationType() const { return this->paramDeclaration; } jsontype_t Procedure::GetReturnType() const { return this->returntype; } -void Procedure::SetProcedureName(const string &name) { - this->procedureName = name; -} -void Procedure::SetProcedureType(procedure_t type) { - this->procedureType = type; -} +void Procedure::SetProcedureName(const string &name) { this->procedureName = name; } +void Procedure::SetProcedureType(procedure_t type) { this->procedureType = type; } void Procedure::SetReturnType(jsontype_t type) { this->returntype = type; } -void Procedure::SetParameterDeclarationType(parameterDeclaration_t type) { - this->paramDeclaration = type; -} +void Procedure::SetParameterDeclarationType(parameterDeclaration_t type) { this->paramDeclaration = type; } void Procedure::AddParameter(const string &name, jsontype_t type) { this->parametersName[name] = type; @@ -97,9 +80,7 @@ void Procedure::AddParameter(const string &name, jsontype_t type) { } bool Procedure::ValidateNamedParameters(const Json::Value ¶meters) const { bool ok = parameters.isObject() || parameters.isNull(); - for (map::const_iterator it = - this->parametersName.begin(); - ok == true && it != this->parametersName.end(); ++it) { + for (map::const_iterator it = this->parametersName.begin(); ok == true && it != this->parametersName.end(); ++it) { if (!parameters.isMember(it->first)) { ok = false; } else { @@ -108,8 +89,7 @@ bool Procedure::ValidateNamedParameters(const Json::Value ¶meters) const { } return ok; } -bool Procedure::ValidatePositionalParameters( - const Json::Value ¶meters) const { +bool Procedure::ValidatePositionalParameters(const Json::Value ¶meters) const { bool ok = true; if (parameters.size() != this->parametersPosition.size()) { @@ -117,13 +97,11 @@ bool Procedure::ValidatePositionalParameters( } for (unsigned int i = 0; ok && i < this->parametersPosition.size(); i++) { - ok = this->ValidateSingleParameter(this->parametersPosition.at(i), - parameters[i]); + ok = this->ValidateSingleParameter(this->parametersPosition.at(i), parameters[i]); } return ok; } -bool Procedure::ValidateSingleParameter(jsontype_t expectedType, - const Json::Value &value) const { +bool Procedure::ValidateSingleParameter(jsontype_t expectedType, const Json::Value &value) const { bool ok = true; switch (expectedType) { case JSON_STRING: diff --git a/src/jsonrpccpp/common/procedure.h b/src/jsonrpccpp/common/procedure.h index ba4f09cd..079c7bd5 100644 --- a/src/jsonrpccpp/common/procedure.h +++ b/src/jsonrpccpp/common/procedure.h @@ -10,110 +10,103 @@ #ifndef JSONRPC_CPP_PROCEDURE_H_ #define JSONRPC_CPP_PROCEDURE_H_ -#include #include +#include #include "jsonparser.h" #include "specification.h" -namespace jsonrpc -{ - typedef std::map parameterNameList_t; - typedef std::vector parameterPositionList_t; - - typedef enum {PARAMS_BY_NAME, PARAMS_BY_POSITION} parameterDeclaration_t; - - class Procedure - { - public: - - Procedure(); - - /** - * @brief Constructor for notificaiton with parameters as va_list. The last parameter must be NULL. - * If no parameters are passed, parameters either do not exist, or cannot be checked for type compliance by the library. - * @param name - */ - Procedure(const std::string& name, parameterDeclaration_t paramType, ...); - - /** - * @brief Constructor for method with parameters as va_list. The last parameter must be NULL. - * If no parameters are passed, parameters either do not exist, or cannot be checked for type compliance by the library. - * @param name - * @param returntype - */ - Procedure(const std::string& name, parameterDeclaration_t paramType, jsontype_t returntype, ...); - - - /** - * This method is validating the incoming parameters for each procedure. - * @param parameters - should contain the parameter-object of an valid json-rpc 2.0 request - * @see http://groups.google.com/group/json-rpc/web/json-rpc-2-0 - * @return true on successful validation false otherwise. - * - * If the valid parameters are of Type JSON_ARRAY or JSON_OBJECT, they can only be checked for name and not for their structure. - */ - bool ValdiateParameters(const Json::Value ¶meters) const; - - - //Various get methods. - const parameterNameList_t& GetParameters () const; - procedure_t GetProcedureType () const; - const std::string& GetProcedureName () const; - jsontype_t GetReturnType () const; - parameterDeclaration_t GetParameterDeclarationType () const; - - //Various set methods. - void SetProcedureName (const std::string &name); - void SetProcedureType (procedure_t type); - void SetReturnType (jsontype_t type); - void SetParameterDeclarationType (parameterDeclaration_t type); - - - /** - * @brief AddParameter - * @param name describes the name of the parameter. In case of an positional parameters, this value can be anything. - * @param type describes the defined type for this parameter. - */ - void AddParameter(const std::string& name, jsontype_t type); - - bool ValidateNamedParameters (const Json::Value ¶meters) const; - bool ValidatePositionalParameters (const Json::Value ¶meters) const; - - private: - - /** - * Each Procedure should have a name. - */ - std::string procedureName; - - /** - * This map represents all necessary Parameters of each Procedure. - * The string represents the name of each parameter and JsonType the type it should have. - */ - parameterNameList_t parametersName; - - /** - * This vector holds all parametertypes by position. - */ - parameterPositionList_t parametersPosition; - - /** - * @brief defines whether the procedure is a method or a notification - */ - procedure_t procedureType; - - /** - * @brief this field is only valid if procedure is of type method (not notification). - */ - jsontype_t returntype; - - /** - * @brief paramDeclaration this field defines if procedure uses named or positional parameters. - */ - parameterDeclaration_t paramDeclaration; - - bool ValidateSingleParameter (jsontype_t expectedType, const Json::Value &value) const; - }; +namespace jsonrpc { + typedef std::map parameterNameList_t; + typedef std::vector parameterPositionList_t; + + typedef enum { PARAMS_BY_NAME, PARAMS_BY_POSITION } parameterDeclaration_t; + + class Procedure { + public: + Procedure(); + + /** + * @brief Constructor for notificaiton with parameters as va_list. The last parameter must be NULL. + * If no parameters are passed, parameters either do not exist, or cannot be checked for type compliance by the library. + * @param name + */ + Procedure(const std::string &name, parameterDeclaration_t paramType, ...); + + /** + * @brief Constructor for method with parameters as va_list. The last parameter must be NULL. + * If no parameters are passed, parameters either do not exist, or cannot be checked for type compliance by the library. + * @param name + * @param returntype + */ + Procedure(const std::string &name, parameterDeclaration_t paramType, jsontype_t returntype, ...); + + /** + * This method is validating the incoming parameters for each procedure. + * @param parameters - should contain the parameter-object of an valid json-rpc 2.0 request + * @see http://groups.google.com/group/json-rpc/web/json-rpc-2-0 + * @return true on successful validation false otherwise. + * + * If the valid parameters are of Type JSON_ARRAY or JSON_OBJECT, they can only be checked for name and not for their structure. + */ + bool ValdiateParameters(const Json::Value ¶meters) const; + + // Various get methods. + const parameterNameList_t &GetParameters() const; + procedure_t GetProcedureType() const; + const std::string &GetProcedureName() const; + jsontype_t GetReturnType() const; + parameterDeclaration_t GetParameterDeclarationType() const; + + // Various set methods. + void SetProcedureName(const std::string &name); + void SetProcedureType(procedure_t type); + void SetReturnType(jsontype_t type); + void SetParameterDeclarationType(parameterDeclaration_t type); + + /** + * @brief AddParameter + * @param name describes the name of the parameter. In case of an positional parameters, this value can be anything. + * @param type describes the defined type for this parameter. + */ + void AddParameter(const std::string &name, jsontype_t type); + + bool ValidateNamedParameters(const Json::Value ¶meters) const; + bool ValidatePositionalParameters(const Json::Value ¶meters) const; + + private: + /** + * Each Procedure should have a name. + */ + std::string procedureName; + + /** + * This map represents all necessary Parameters of each Procedure. + * The string represents the name of each parameter and JsonType the type it should have. + */ + parameterNameList_t parametersName; + + /** + * This vector holds all parametertypes by position. + */ + parameterPositionList_t parametersPosition; + + /** + * @brief defines whether the procedure is a method or a notification + */ + procedure_t procedureType; + + /** + * @brief this field is only valid if procedure is of type method (not notification). + */ + jsontype_t returntype; + + /** + * @brief paramDeclaration this field defines if procedure uses named or positional parameters. + */ + parameterDeclaration_t paramDeclaration; + + bool ValidateSingleParameter(jsontype_t expectedType, const Json::Value &value) const; + }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_PROCEDURE_H_ */ diff --git a/src/jsonrpccpp/common/sharedconstants.h b/src/jsonrpccpp/common/sharedconstants.h index 1cfca7cc..686d3f3e 100644 --- a/src/jsonrpccpp/common/sharedconstants.h +++ b/src/jsonrpccpp/common/sharedconstants.h @@ -2,16 +2,14 @@ #define SHAREDCONSTANTS_H #ifdef __APPLE__ - #include +#include #endif #ifdef __linux__ - #include +#include #endif - #define DEFAULT_DELIMITER_CHAR char(0x0A) #define DEFAULT_BUFFER_SIZE 1024 - #endif // SHAREDCONSTANTS_H diff --git a/src/jsonrpccpp/common/specification.h b/src/jsonrpccpp/common/specification.h index 299913cb..46e70bec 100644 --- a/src/jsonrpccpp/common/specification.h +++ b/src/jsonrpccpp/common/specification.h @@ -10,36 +10,23 @@ #ifndef JSONRPC_CPP_SPECIFICATION_H #define JSONRPC_CPP_SPECIFICATION_H -#define KEY_SPEC_PROCEDURE_NAME "name" -#define KEY_SPEC_PROCEDURE_METHOD "method" //legacy format -> use name now -#define KEY_SPEC_PROCEDURE_NOTIFICATION "notification" //legacy format -> use name now -#define KEY_SPEC_PROCEDURE_PARAMETERS "params" -#define KEY_SPEC_RETURN_TYPE "returns" +#define KEY_SPEC_PROCEDURE_NAME "name" +#define KEY_SPEC_PROCEDURE_METHOD "method" // legacy format -> use name now +#define KEY_SPEC_PROCEDURE_NOTIFICATION "notification" // legacy format -> use name now +#define KEY_SPEC_PROCEDURE_PARAMETERS "params" +#define KEY_SPEC_RETURN_TYPE "returns" -namespace jsonrpc -{ - /** - * This enum describes whether a Procdeure is a notification procdeure or a method procdeure - * @see http://groups.google.com/group/json-rpc/web/json-rpc-2-0 - */ - typedef enum - { - RPC_METHOD, RPC_NOTIFICATION - } procedure_t; +namespace jsonrpc { + /** + * This enum describes whether a Procdeure is a notification procdeure or a method procdeure + * @see http://groups.google.com/group/json-rpc/web/json-rpc-2-0 + */ + typedef enum { RPC_METHOD, RPC_NOTIFICATION } procedure_t; - /** - * This enum represents all processable json Types of this framework. - */ - enum jsontype_t - { - JSON_STRING = 1, - JSON_BOOLEAN = 2, - JSON_INTEGER = 3, - JSON_REAL = 4, - JSON_OBJECT = 5, - JSON_ARRAY = 6, - JSON_NUMERIC = 7 - } ; -} + /** + * This enum represents all processable json Types of this framework. + */ + enum jsontype_t { JSON_STRING = 1, JSON_BOOLEAN = 2, JSON_INTEGER = 3, JSON_REAL = 4, JSON_OBJECT = 5, JSON_ARRAY = 6, JSON_NUMERIC = 7 }; +} // namespace jsonrpc #endif // JSONRPC_CPP_SPECIFICATION_H diff --git a/src/jsonrpccpp/common/specificationparser.cpp b/src/jsonrpccpp/common/specificationparser.cpp index ca6a3282..b7ba640f 100644 --- a/src/jsonrpccpp/common/specificationparser.cpp +++ b/src/jsonrpccpp/common/specificationparser.cpp @@ -15,25 +15,21 @@ using namespace std; using namespace jsonrpc; -vector -SpecificationParser::GetProceduresFromFile(const string &filename) { +vector SpecificationParser::GetProceduresFromFile(const string &filename) { string content; GetFileContent(filename, content); return GetProceduresFromString(content); } -vector -SpecificationParser::GetProceduresFromString(const string &content) { +vector SpecificationParser::GetProceduresFromString(const string &content) { Json::Reader reader; Json::Value val; if (!reader.parse(content, val)) { - throw JsonRpcException(Errors::ERROR_RPC_JSON_PARSE_ERROR, - " specification file contains syntax errors"); + throw JsonRpcException(Errors::ERROR_RPC_JSON_PARSE_ERROR, " specification file contains syntax errors"); } if (!val.isArray()) { - throw JsonRpcException(Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX, - " top level json value is not an array"); + throw JsonRpcException(Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX, " top level json value is not an array"); } vector result; @@ -42,17 +38,14 @@ SpecificationParser::GetProceduresFromString(const string &content) { Procedure proc; GetProcedure(val[i], proc); if (procnames.find(proc.GetProcedureName()) != procnames.end()) { - throw JsonRpcException( - Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX, - "Procedurename not unique: " + proc.GetProcedureName()); + throw JsonRpcException(Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX, "Procedurename not unique: " + proc.GetProcedureName()); } procnames[proc.GetProcedureName()] = proc; result.push_back(proc); } return result; } -void SpecificationParser::GetProcedure(Json::Value &signature, - Procedure &result) { +void SpecificationParser::GetProcedure(Json::Value &signature, Procedure &result) { if (signature.isObject() && !GetProcedureName(signature).empty()) { result.SetProcedureName(GetProcedureName(signature)); if (signature.isMember(KEY_SPEC_RETURN_TYPE)) { @@ -62,8 +55,7 @@ void SpecificationParser::GetProcedure(Json::Value &signature, result.SetProcedureType(RPC_NOTIFICATION); } if (signature.isMember(KEY_SPEC_PROCEDURE_PARAMETERS)) { - if (signature[KEY_SPEC_PROCEDURE_PARAMETERS].isObject() || - signature[KEY_SPEC_PROCEDURE_PARAMETERS].isArray()) { + if (signature[KEY_SPEC_PROCEDURE_PARAMETERS].isObject() || signature[KEY_SPEC_PROCEDURE_PARAMETERS].isArray()) { if (signature[KEY_SPEC_PROCEDURE_PARAMETERS].isArray()) { result.SetParameterDeclarationType(PARAMS_BY_POSITION); GetPositionalParameters(signature, result); @@ -72,29 +64,22 @@ void SpecificationParser::GetProcedure(Json::Value &signature, GetNamedParameters(signature, result); } } else { - throw JsonRpcException( - Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX, - "Invalid signature types in fileds: " + signature.toStyledString()); + throw JsonRpcException(Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX, "Invalid signature types in fileds: " + signature.toStyledString()); } } } else { - throw JsonRpcException( - Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX, - "procedure declaration does not contain name or parameters: " + - signature.toStyledString()); + throw JsonRpcException(Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX, + "procedure declaration does not contain name or parameters: " + signature.toStyledString()); } } -void SpecificationParser::GetFileContent(const std::string &filename, - std::string &target) { +void SpecificationParser::GetFileContent(const std::string &filename, std::string &target) { ifstream config(filename.c_str()); if (config) { config.open(filename.c_str(), ios::in); - target.assign((std::istreambuf_iterator(config)), - (std::istreambuf_iterator())); + target.assign((std::istreambuf_iterator(config)), (std::istreambuf_iterator())); } else { - throw JsonRpcException( - Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_NOT_FOUND, filename); + throw JsonRpcException(Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_NOT_FOUND, filename); } } jsontype_t SpecificationParser::toJsonType(Json::Value &val) { @@ -120,29 +105,22 @@ jsontype_t SpecificationParser::toJsonType(Json::Value &val) { result = JSON_OBJECT; break; default: - throw JsonRpcException(Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX, - "Unknown parameter type: " + val.toStyledString()); + throw JsonRpcException(Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX, "Unknown parameter type: " + val.toStyledString()); } return result; } -void SpecificationParser::GetPositionalParameters(Json::Value &val, - Procedure &result) { +void SpecificationParser::GetPositionalParameters(Json::Value &val, Procedure &result) { // Positional parameters for (unsigned int i = 0; i < val[KEY_SPEC_PROCEDURE_PARAMETERS].size(); i++) { stringstream paramname; paramname << "param" << std::setfill('0') << std::setw(2) << (i + 1); - result.AddParameter(paramname.str(), - toJsonType(val[KEY_SPEC_PROCEDURE_PARAMETERS][i])); + result.AddParameter(paramname.str(), toJsonType(val[KEY_SPEC_PROCEDURE_PARAMETERS][i])); } } -void SpecificationParser::GetNamedParameters(Json::Value &val, - Procedure &result) { - vector parameters = - val[KEY_SPEC_PROCEDURE_PARAMETERS].getMemberNames(); +void SpecificationParser::GetNamedParameters(Json::Value &val, Procedure &result) { + vector parameters = val[KEY_SPEC_PROCEDURE_PARAMETERS].getMemberNames(); for (unsigned int i = 0; i < parameters.size(); ++i) { - result.AddParameter( - parameters.at(i), - toJsonType(val[KEY_SPEC_PROCEDURE_PARAMETERS][parameters.at(i)])); + result.AddParameter(parameters.at(i), toJsonType(val[KEY_SPEC_PROCEDURE_PARAMETERS][parameters.at(i)])); } } diff --git a/src/jsonrpccpp/common/specificationparser.h b/src/jsonrpccpp/common/specificationparser.h index 92df0142..fab24a03 100644 --- a/src/jsonrpccpp/common/specificationparser.h +++ b/src/jsonrpccpp/common/specificationparser.h @@ -10,29 +10,27 @@ #ifndef JSONRPC_CPP_SPECIFICATIONPARSER_H #define JSONRPC_CPP_SPECIFICATIONPARSER_H -#include "procedure.h" #include "exception.h" +#include "procedure.h" namespace jsonrpc { - class SpecificationParser - { - public: - static std::vector GetProceduresFromFile(const std::string& filename) ; - static std::vector GetProceduresFromString(const std::string& spec) ; - - static void GetFileContent (const std::string& filename, std::string& target); + class SpecificationParser { + public: + static std::vector GetProceduresFromFile(const std::string &filename); + static std::vector GetProceduresFromString(const std::string &spec); - private: - static void GetProcedure (Json::Value& val, Procedure &target); - static void GetMethod (Json::Value& val, Procedure &target); - static void GetNotification (Json::Value& val, Procedure &target); - static jsontype_t toJsonType (Json::Value& val); + static void GetFileContent(const std::string &filename, std::string &target); - static void GetPositionalParameters (Json::Value &val, Procedure &target); - static void GetNamedParameters (Json::Value &val, Procedure &target); - static std::string GetProcedureName (Json::Value &signature); + private: + static void GetProcedure(Json::Value &val, Procedure &target); + static void GetMethod(Json::Value &val, Procedure &target); + static void GetNotification(Json::Value &val, Procedure &target); + static jsontype_t toJsonType(Json::Value &val); - }; -} + static void GetPositionalParameters(Json::Value &val, Procedure &target); + static void GetNamedParameters(Json::Value &val, Procedure &target); + static std::string GetProcedureName(Json::Value &signature); + }; +} // namespace jsonrpc #endif // JSONRPC_CPP_SPECIFICATIONPARSER_H diff --git a/src/jsonrpccpp/common/specificationwriter.cpp b/src/jsonrpccpp/common/specificationwriter.cpp index 83c0e94d..0be28ad7 100644 --- a/src/jsonrpccpp/common/specificationwriter.cpp +++ b/src/jsonrpccpp/common/specificationwriter.cpp @@ -16,8 +16,7 @@ using namespace std; using namespace jsonrpc; -Json::Value -SpecificationWriter::toJsonValue(const vector &procedures) { +Json::Value SpecificationWriter::toJsonValue(const vector &procedures) { Json::Value result; Json::Value row; for (unsigned int i = 0; i < procedures.size(); i++) { @@ -32,8 +31,7 @@ std::string SpecificationWriter::toString(const vector &procedures) { wb["indentation"] = " "; return Json::writeString(wb, toJsonValue(procedures)); } -bool SpecificationWriter::toFile(const std::string &filename, - const vector &procedures) { +bool SpecificationWriter::toFile(const std::string &filename, const vector &procedures) { ofstream file; file.open(filename.c_str(), ios_base::out); if (!file.is_open()) @@ -69,18 +67,14 @@ Json::Value SpecificationWriter::toJsonLiteral(jsontype_t type) { } return literal; } -void SpecificationWriter::procedureToJsonValue(const Procedure &procedure, - Json::Value &target) { +void SpecificationWriter::procedureToJsonValue(const Procedure &procedure, Json::Value &target) { target[KEY_SPEC_PROCEDURE_NAME] = procedure.GetProcedureName(); if (procedure.GetProcedureType() == RPC_METHOD) { target[KEY_SPEC_RETURN_TYPE] = toJsonLiteral(procedure.GetReturnType()); } - for (parameterNameList_t::const_iterator it = - procedure.GetParameters().begin(); - it != procedure.GetParameters().end(); ++it) { + for (parameterNameList_t::const_iterator it = procedure.GetParameters().begin(); it != procedure.GetParameters().end(); ++it) { if (procedure.GetParameterDeclarationType() == PARAMS_BY_NAME) { - target[KEY_SPEC_PROCEDURE_PARAMETERS][it->first] = - toJsonLiteral(it->second); + target[KEY_SPEC_PROCEDURE_PARAMETERS][it->first] = toJsonLiteral(it->second); } else { target[KEY_SPEC_PROCEDURE_PARAMETERS].append(toJsonLiteral(it->second)); } diff --git a/src/jsonrpccpp/common/specificationwriter.h b/src/jsonrpccpp/common/specificationwriter.h index 00531c12..d34d8913 100644 --- a/src/jsonrpccpp/common/specificationwriter.h +++ b/src/jsonrpccpp/common/specificationwriter.h @@ -14,17 +14,16 @@ #include "specification.h" namespace jsonrpc { - class SpecificationWriter - { - public: - static Json::Value toJsonValue (const std::vector& procedures); - static std::string toString (const std::vector& procedures); - static bool toFile (const std::string& filename, const std::vector& procedures); + class SpecificationWriter { + public: + static Json::Value toJsonValue(const std::vector &procedures); + static std::string toString(const std::vector &procedures); + static bool toFile(const std::string &filename, const std::vector &procedures); - private: - static Json::Value toJsonLiteral (jsontype_t type); - static void procedureToJsonValue (const Procedure& procedure, Json::Value& target); - }; -} + private: + static Json::Value toJsonLiteral(jsontype_t type); + static void procedureToJsonValue(const Procedure &procedure, Json::Value &target); + }; +} // namespace jsonrpc #endif // JSONRPC_CPP_SPECIFICATIONWRITER_H diff --git a/src/jsonrpccpp/common/streamreader.cpp b/src/jsonrpccpp/common/streamreader.cpp index e94012e5..340b3cff 100644 --- a/src/jsonrpccpp/common/streamreader.cpp +++ b/src/jsonrpccpp/common/streamreader.cpp @@ -6,8 +6,7 @@ using namespace jsonrpc; using namespace std; -StreamReader::StreamReader(size_t buffersize) - : buffersize(buffersize), buffer(static_cast(malloc(buffersize))) {} +StreamReader::StreamReader(size_t buffersize) : buffersize(buffersize), buffer(static_cast(malloc(buffersize))) {} StreamReader::~StreamReader() { free(buffer); } @@ -20,8 +19,7 @@ bool StreamReader::Read(std::string &target, int fd, char delimiter) { } else { target.append(buffer, static_cast(bytesRead)); } - } while (memchr(buffer, delimiter, bytesRead) == - NULL); //(target.find(delimiter) == string::npos && bytesRead > 0); + } while (memchr(buffer, delimiter, bytesRead) == NULL); //(target.find(delimiter) == string::npos && bytesRead > 0); target.pop_back(); return true; diff --git a/src/jsonrpccpp/common/streamreader.h b/src/jsonrpccpp/common/streamreader.h index e971a7e9..ffb4fedb 100644 --- a/src/jsonrpccpp/common/streamreader.h +++ b/src/jsonrpccpp/common/streamreader.h @@ -1,21 +1,20 @@ #ifndef STREAMREADER_H #define STREAMREADER_H -#include #include +#include namespace jsonrpc { -class StreamReader -{ -public: + class StreamReader { + public: StreamReader(size_t buffersize); virtual ~StreamReader(); bool Read(std::string &target, int fd, char delimiter); -private: + private: size_t buffersize; - char* buffer; -}; -} + char *buffer; + }; +} // namespace jsonrpc #endif // STREAMREADER_H diff --git a/src/jsonrpccpp/common/streamwriter.cpp b/src/jsonrpccpp/common/streamwriter.cpp index 5f71cfb1..386ee9e7 100644 --- a/src/jsonrpccpp/common/streamwriter.cpp +++ b/src/jsonrpccpp/common/streamwriter.cpp @@ -10,8 +10,7 @@ bool StreamWriter::Write(const string &source, int fd) { size_t remainingSize = totalSize; do { - bytesWritten = - write(fd, source.c_str() + (totalSize - remainingSize), remainingSize); + bytesWritten = write(fd, source.c_str() + (totalSize - remainingSize), remainingSize); if (bytesWritten < 0) { return false; } else { diff --git a/src/jsonrpccpp/common/streamwriter.h b/src/jsonrpccpp/common/streamwriter.h index bdb50cd5..e25c3764 100644 --- a/src/jsonrpccpp/common/streamwriter.h +++ b/src/jsonrpccpp/common/streamwriter.h @@ -1,17 +1,15 @@ #ifndef STREAMWRITER_H #define STREAMWRITER_H -#include #include +#include namespace jsonrpc { -class StreamWriter -{ -public: + class StreamWriter { + public: bool Write(const std::string &source, int fd); -}; - -} + }; +} // namespace jsonrpc #endif // STREAMWRITER_H diff --git a/src/jsonrpccpp/server.h b/src/jsonrpccpp/server.h index 876e6a9b..71d51b9e 100644 --- a/src/jsonrpccpp/server.h +++ b/src/jsonrpccpp/server.h @@ -10,8 +10,7 @@ #ifndef JSONRPCCPP_SERVER_H_ #define JSONRPCCPP_SERVER_H_ -#include #include - +#include #endif /* JSONRPCCPP_SERVER_H_ */ diff --git a/src/jsonrpccpp/server/abstractprotocolhandler.cpp b/src/jsonrpccpp/server/abstractprotocolhandler.cpp index 0d7971c1..25e4f693 100644 --- a/src/jsonrpccpp/server/abstractprotocolhandler.cpp +++ b/src/jsonrpccpp/server/abstractprotocolhandler.cpp @@ -16,18 +16,13 @@ using namespace jsonrpc; using namespace std; -AbstractProtocolHandler::AbstractProtocolHandler( - IProcedureInvokationHandler &handler) - : handler(handler) {} +AbstractProtocolHandler::AbstractProtocolHandler(IProcedureInvokationHandler &handler) : handler(handler) {} AbstractProtocolHandler::~AbstractProtocolHandler() {} -void AbstractProtocolHandler::AddProcedure(const Procedure &procedure) { - this->procedures[procedure.GetProcedureName()] = procedure; -} +void AbstractProtocolHandler::AddProcedure(const Procedure &procedure) { this->procedures[procedure.GetProcedureName()] = procedure; } -void AbstractProtocolHandler::HandleRequest(const std::string &request, - std::string &retValue) { +void AbstractProtocolHandler::HandleRequest(const std::string &request, std::string &retValue) { Json::Reader reader; Json::Value req; Json::Value resp; @@ -38,24 +33,18 @@ void AbstractProtocolHandler::HandleRequest(const std::string &request, if (reader.parse(request, req, false)) { this->HandleJsonRequest(req, resp); } else { - this->WrapError( - Json::nullValue, Errors::ERROR_RPC_JSON_PARSE_ERROR, - Errors::GetErrorMessage(Errors::ERROR_RPC_JSON_PARSE_ERROR), resp); + this->WrapError(Json::nullValue, Errors::ERROR_RPC_JSON_PARSE_ERROR, Errors::GetErrorMessage(Errors::ERROR_RPC_JSON_PARSE_ERROR), resp); } } catch (const Json::Exception &e) { - this->WrapError(Json::nullValue, Errors::ERROR_RPC_JSON_PARSE_ERROR, - Errors::GetErrorMessage(Errors::ERROR_RPC_JSON_PARSE_ERROR), - resp); + this->WrapError(Json::nullValue, Errors::ERROR_RPC_JSON_PARSE_ERROR, Errors::GetErrorMessage(Errors::ERROR_RPC_JSON_PARSE_ERROR), resp); } if (resp != Json::nullValue) retValue = Json::writeString(wbuilder, resp); } -void AbstractProtocolHandler::ProcessRequest(const Json::Value &request, - Json::Value &response) { - Procedure &method = - this->procedures[request[KEY_REQUEST_METHODNAME].asString()]; +void AbstractProtocolHandler::ProcessRequest(const Json::Value &request, Json::Value &response) { + Procedure &method = this->procedures[request[KEY_REQUEST_METHODNAME].asString()]; Json::Value result; if (method.GetProcedureType() == RPC_METHOD) { @@ -73,15 +62,12 @@ int AbstractProtocolHandler::ValidateRequest(const Json::Value &request) { if (!this->ValidateRequestFields(request)) { error = Errors::ERROR_RPC_INVALID_REQUEST; } else { - map::iterator it = - this->procedures.find(request[KEY_REQUEST_METHODNAME].asString()); + map::iterator it = this->procedures.find(request[KEY_REQUEST_METHODNAME].asString()); if (it != this->procedures.end()) { proc = it->second; - if (this->GetRequestType(request) == RPC_METHOD && - proc.GetProcedureType() == RPC_NOTIFICATION) { + if (this->GetRequestType(request) == RPC_METHOD && proc.GetProcedureType() == RPC_NOTIFICATION) { error = Errors::ERROR_SERVER_PROCEDURE_IS_NOTIFICATION; - } else if (this->GetRequestType(request) == RPC_NOTIFICATION && - proc.GetProcedureType() == RPC_METHOD) { + } else if (this->GetRequestType(request) == RPC_NOTIFICATION && proc.GetProcedureType() == RPC_METHOD) { error = Errors::ERROR_SERVER_PROCEDURE_IS_METHOD; } else if (!proc.ValdiateParameters(request[KEY_REQUEST_PARAMETERS])) { error = Errors::ERROR_RPC_INVALID_PARAMS; diff --git a/src/jsonrpccpp/server/abstractprotocolhandler.h b/src/jsonrpccpp/server/abstractprotocolhandler.h index 5b74cd20..35efc2cd 100644 --- a/src/jsonrpccpp/server/abstractprotocolhandler.h +++ b/src/jsonrpccpp/server/abstractprotocolhandler.h @@ -10,44 +10,42 @@ #ifndef JSONRPC_CPP_ABSTRACTPROTOCOLHANDLER_H #define JSONRPC_CPP_ABSTRACTPROTOCOLHANDLER_H -#include "iprocedureinvokationhandler.h" #include "iclientconnectionhandler.h" +#include "iprocedureinvokationhandler.h" +#include #include #include -#include -#define KEY_REQUEST_METHODNAME "method" -#define KEY_REQUEST_ID "id" -#define KEY_REQUEST_PARAMETERS "params" -#define KEY_RESPONSE_ERROR "error" -#define KEY_RESPONSE_RESULT "result" +#define KEY_REQUEST_METHODNAME "method" +#define KEY_REQUEST_ID "id" +#define KEY_REQUEST_PARAMETERS "params" +#define KEY_RESPONSE_ERROR "error" +#define KEY_RESPONSE_RESULT "result" namespace jsonrpc { - class AbstractProtocolHandler : public IProtocolHandler - { - public: - AbstractProtocolHandler(IProcedureInvokationHandler &handler); - virtual ~AbstractProtocolHandler(); - - void HandleRequest(const std::string& request, std::string& retValue); + class AbstractProtocolHandler : public IProtocolHandler { + public: + AbstractProtocolHandler(IProcedureInvokationHandler &handler); + virtual ~AbstractProtocolHandler(); - virtual void AddProcedure(const Procedure& procedure); + void HandleRequest(const std::string &request, std::string &retValue); - virtual void HandleJsonRequest(const Json::Value& request, Json::Value& response) = 0; - virtual bool ValidateRequestFields(const Json::Value &val) = 0; - virtual void WrapResult(const Json::Value& request, Json::Value& response, Json::Value& retValue) = 0; - virtual void WrapError(const Json::Value& request, int code, const std::string &message, Json::Value& result) = 0; - virtual procedure_t GetRequestType(const Json::Value& request) = 0; + virtual void AddProcedure(const Procedure &procedure); - protected: - IProcedureInvokationHandler &handler; - std::map procedures; + virtual void HandleJsonRequest(const Json::Value &request, Json::Value &response) = 0; + virtual bool ValidateRequestFields(const Json::Value &val) = 0; + virtual void WrapResult(const Json::Value &request, Json::Value &response, Json::Value &retValue) = 0; + virtual void WrapError(const Json::Value &request, int code, const std::string &message, Json::Value &result) = 0; + virtual procedure_t GetRequestType(const Json::Value &request) = 0; - void ProcessRequest(const Json::Value &request, Json::Value &retValue); - int ValidateRequest(const Json::Value &val); + protected: + IProcedureInvokationHandler &handler; + std::map procedures; - }; + void ProcessRequest(const Json::Value &request, Json::Value &retValue); + int ValidateRequest(const Json::Value &val); + }; } // namespace jsonrpc diff --git a/src/jsonrpccpp/server/abstractserver.h b/src/jsonrpccpp/server/abstractserver.h index 3d048153..54ee5ad3 100644 --- a/src/jsonrpccpp/server/abstractserver.h +++ b/src/jsonrpccpp/server/abstractserver.h @@ -10,97 +10,77 @@ #ifndef JSONRPC_CPP_ABSTRACTSERVER_H_ #define JSONRPC_CPP_ABSTRACTSERVER_H_ -#include -#include -#include -#include #include "abstractserverconnector.h" -#include "iprocedureinvokationhandler.h" #include "iclientconnectionhandler.h" +#include "iprocedureinvokationhandler.h" #include "requesthandlerfactory.h" +#include +#include +#include +#include -namespace jsonrpc -{ +namespace jsonrpc { - template - class AbstractServer : public IProcedureInvokationHandler - { - public: - typedef void(S::*methodPointer_t) (const Json::Value ¶meter, Json::Value &result); - typedef void(S::*notificationPointer_t) (const Json::Value ¶meter); + template + class AbstractServer : public IProcedureInvokationHandler { + public: + typedef void (S::*methodPointer_t)(const Json::Value ¶meter, Json::Value &result); + typedef void (S::*notificationPointer_t)(const Json::Value ¶meter); - AbstractServer(AbstractServerConnector &connector, serverVersion_t type = JSONRPC_SERVER_V2) : - connection(connector) - { - this->handler = RequestHandlerFactory::createProtocolHandler(type, *this); - connector.SetHandler(this->handler); - } + AbstractServer(AbstractServerConnector &connector, serverVersion_t type = JSONRPC_SERVER_V2) : connection(connector) { + this->handler = RequestHandlerFactory::createProtocolHandler(type, *this); + connector.SetHandler(this->handler); + } - virtual ~AbstractServer() - { - delete this->handler; - } + virtual ~AbstractServer() { delete this->handler; } - bool StartListening() - { - return connection.StartListening(); - } + bool StartListening() { return connection.StartListening(); } - bool StopListening() - { - return connection.StopListening(); - } + bool StopListening() { return connection.StopListening(); } - virtual void HandleMethodCall(Procedure &proc, const Json::Value& input, Json::Value& output) - { - S* instance = dynamic_cast(this); - (instance->*methods[proc.GetProcedureName()])(input, output); - } + virtual void HandleMethodCall(Procedure &proc, const Json::Value &input, Json::Value &output) { + S *instance = dynamic_cast(this); + (instance->*methods[proc.GetProcedureName()])(input, output); + } - virtual void HandleNotificationCall(Procedure &proc, const Json::Value& input) - { - S* instance = dynamic_cast(this); - (instance->*notifications[proc.GetProcedureName()])(input); - } + virtual void HandleNotificationCall(Procedure &proc, const Json::Value &input) { + S *instance = dynamic_cast(this); + (instance->*notifications[proc.GetProcedureName()])(input); + } - protected: - bool bindAndAddMethod(const Procedure& proc, methodPointer_t pointer) - { - if(proc.GetProcedureType() == RPC_METHOD && !this->symbolExists(proc.GetProcedureName())) - { - this->handler->AddProcedure(proc); - this->methods[proc.GetProcedureName()] = pointer; - return true; - } - return false; - } + protected: + bool bindAndAddMethod(const Procedure &proc, methodPointer_t pointer) { + if (proc.GetProcedureType() == RPC_METHOD && !this->symbolExists(proc.GetProcedureName())) { + this->handler->AddProcedure(proc); + this->methods[proc.GetProcedureName()] = pointer; + return true; + } + return false; + } - bool bindAndAddNotification(const Procedure& proc, notificationPointer_t pointer) - { - if(proc.GetProcedureType() == RPC_NOTIFICATION && !this->symbolExists(proc.GetProcedureName())) - { - this->handler->AddProcedure(proc); - this->notifications[proc.GetProcedureName()] = pointer; - return true; - } - return false; - } + bool bindAndAddNotification(const Procedure &proc, notificationPointer_t pointer) { + if (proc.GetProcedureType() == RPC_NOTIFICATION && !this->symbolExists(proc.GetProcedureName())) { + this->handler->AddProcedure(proc); + this->notifications[proc.GetProcedureName()] = pointer; + return true; + } + return false; + } - private: - AbstractServerConnector &connection; - IProtocolHandler *handler; - std::map methods; - std::map notifications; + private: + AbstractServerConnector &connection; + IProtocolHandler *handler; + std::map methods; + std::map notifications; - bool symbolExists(const std::string &name) - { - if (methods.find(name) != methods.end()) - return true; - if (notifications.find(name) != notifications.end()) - return true; - return false; - } - }; + bool symbolExists(const std::string &name) { + if (methods.find(name) != methods.end()) + return true; + if (notifications.find(name) != notifications.end()) + return true; + return false; + } + }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_ABSTRACTSERVER_H_ */ diff --git a/src/jsonrpccpp/server/abstractserverconnector.cpp b/src/jsonrpccpp/server/abstractserverconnector.cpp index b8d37ae4..ba0d1fa8 100644 --- a/src/jsonrpccpp/server/abstractserverconnector.cpp +++ b/src/jsonrpccpp/server/abstractserverconnector.cpp @@ -18,17 +18,12 @@ AbstractServerConnector::AbstractServerConnector() { this->handler = NULL; } AbstractServerConnector::~AbstractServerConnector() {} -void AbstractServerConnector::ProcessRequest(const string &request, - string &response) { +void AbstractServerConnector::ProcessRequest(const string &request, string &response) { if (this->handler != NULL) { this->handler->HandleRequest(request, response); } } -void AbstractServerConnector::SetHandler(IClientConnectionHandler *handler) { - this->handler = handler; -} +void AbstractServerConnector::SetHandler(IClientConnectionHandler *handler) { this->handler = handler; } -IClientConnectionHandler *AbstractServerConnector::GetHandler() { - return this->handler; -} +IClientConnectionHandler *AbstractServerConnector::GetHandler() { return this->handler; } diff --git a/src/jsonrpccpp/server/abstractserverconnector.h b/src/jsonrpccpp/server/abstractserverconnector.h index 58507829..2b83a6e5 100644 --- a/src/jsonrpccpp/server/abstractserverconnector.h +++ b/src/jsonrpccpp/server/abstractserverconnector.h @@ -15,32 +15,32 @@ namespace jsonrpc { -class AbstractServerConnector { -public: - AbstractServerConnector(); - virtual ~AbstractServerConnector(); - - /** - * This method should signal the Connector to start waiting for requests, in - * any way that is appropriate for the derived connector class. - * If something went wrong, this method should return false, otherwise true. - */ - virtual bool StartListening() = 0; - /** - * This method should signal the Connector to stop waiting for requests, in - * any way that is appropriate for the derived connector class. - * If something went wrong, this method should return false, otherwise true. - */ - virtual bool StopListening() = 0; - - void ProcessRequest(const std::string &request, std::string &response); - - void SetHandler(IClientConnectionHandler *handler); - IClientConnectionHandler *GetHandler(); - -private: - IClientConnectionHandler *handler; -}; + class AbstractServerConnector { + public: + AbstractServerConnector(); + virtual ~AbstractServerConnector(); + + /** + * This method should signal the Connector to start waiting for requests, in + * any way that is appropriate for the derived connector class. + * If something went wrong, this method should return false, otherwise true. + */ + virtual bool StartListening() = 0; + /** + * This method should signal the Connector to stop waiting for requests, in + * any way that is appropriate for the derived connector class. + * If something went wrong, this method should return false, otherwise true. + */ + virtual bool StopListening() = 0; + + void ProcessRequest(const std::string &request, std::string &response); + + void SetHandler(IClientConnectionHandler *handler); + IClientConnectionHandler *GetHandler(); + + private: + IClientConnectionHandler *handler; + }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_ERVERCONNECTOR_H_ */ diff --git a/src/jsonrpccpp/server/abstractthreadedserver.cpp b/src/jsonrpccpp/server/abstractthreadedserver.cpp index 693bc811..bb4aea54 100644 --- a/src/jsonrpccpp/server/abstractthreadedserver.cpp +++ b/src/jsonrpccpp/server/abstractthreadedserver.cpp @@ -3,8 +3,7 @@ using namespace jsonrpc; using namespace std; -AbstractThreadedServer::AbstractThreadedServer(size_t threads) - : running(false), threadPool(threads), threads(threads) {} +AbstractThreadedServer::AbstractThreadedServer(size_t threads) : running(false), threadPool(threads), threads(threads) {} AbstractThreadedServer::~AbstractThreadedServer() { this->StopListening(); } @@ -17,8 +16,7 @@ bool AbstractThreadedServer::StartListening() { this->running = true; - this->listenerThread = - unique_ptr(new thread(&AbstractThreadedServer::ListenLoop, this)); + this->listenerThread = unique_ptr(new thread(&AbstractThreadedServer::ListenLoop, this)); return true; } @@ -39,8 +37,7 @@ void AbstractThreadedServer::ListenLoop() { if (conn > 0) { if (this->threads > 0) { - this->threadPool.enqueue(&AbstractThreadedServer::HandleConnection, - this, conn); + this->threadPool.enqueue(&AbstractThreadedServer::HandleConnection, this, conn); } else { this->HandleConnection(conn); } diff --git a/src/jsonrpccpp/server/abstractthreadedserver.h b/src/jsonrpccpp/server/abstractthreadedserver.h index 4fa3f3c7..9543a8ea 100644 --- a/src/jsonrpccpp/server/abstractthreadedserver.h +++ b/src/jsonrpccpp/server/abstractthreadedserver.h @@ -7,43 +7,43 @@ #include namespace jsonrpc { -class AbstractThreadedServer : public AbstractServerConnector { -public: - AbstractThreadedServer(size_t threads); - virtual ~AbstractThreadedServer(); - - virtual bool StartListening(); - virtual bool StopListening(); - -protected: - /** - * @brief InitializeListener should initialize sockets, file descriptors etc. - * @return - */ - virtual bool InitializeListener() = 0; - - /** - * @brief CheckForConnection should poll for a new connection. This must be - * a non-blocking call. - * @return a handle which is passed on to HandleConnection() - */ - virtual int CheckForConnection() = 0; - - /** - * @brief HandleConnection must handle connection information for a given - * handle that has been returned by CheckForConnection() - * @param connection - */ - virtual void HandleConnection(int connection) = 0; - -private: - bool running; - std::unique_ptr listenerThread; - ThreadPool threadPool; - size_t threads; - - void ListenLoop(); -}; -} + class AbstractThreadedServer : public AbstractServerConnector { + public: + AbstractThreadedServer(size_t threads); + virtual ~AbstractThreadedServer(); + + virtual bool StartListening(); + virtual bool StopListening(); + + protected: + /** + * @brief InitializeListener should initialize sockets, file descriptors etc. + * @return + */ + virtual bool InitializeListener() = 0; + + /** + * @brief CheckForConnection should poll for a new connection. This must be + * a non-blocking call. + * @return a handle which is passed on to HandleConnection() + */ + virtual int CheckForConnection() = 0; + + /** + * @brief HandleConnection must handle connection information for a given + * handle that has been returned by CheckForConnection() + * @param connection + */ + virtual void HandleConnection(int connection) = 0; + + private: + bool running; + std::unique_ptr listenerThread; + ThreadPool threadPool; + size_t threads; + + void ListenLoop(); + }; +} // namespace jsonrpc #endif // ABSTRACTTHREADEDSERVER_H diff --git a/src/jsonrpccpp/server/connectors/filedescriptorserver.cpp b/src/jsonrpccpp/server/connectors/filedescriptorserver.cpp index 6eb51b4d..f446d18f 100644 --- a/src/jsonrpccpp/server/connectors/filedescriptorserver.cpp +++ b/src/jsonrpccpp/server/connectors/filedescriptorserver.cpp @@ -27,8 +27,7 @@ using namespace std; #define READ_TIMEOUT 0.001 // Set timeout in seconds FileDescriptorServer::FileDescriptorServer(int inputfd, int outputfd) - : AbstractThreadedServer(0), inputfd(inputfd), outputfd(outputfd), - reader(DEFAULT_BUFFER_SIZE) {} + : AbstractThreadedServer(0), inputfd(inputfd), outputfd(outputfd), reader(DEFAULT_BUFFER_SIZE) {} bool FileDescriptorServer::InitializeListener() { if (!IsReadable(inputfd) || !IsWritable(outputfd)) @@ -61,8 +60,7 @@ bool FileDescriptorServer::IsReadable(int fd) { int ret = fcntl(fd, F_GETFL, &o_accmode); if (ret == -1) return false; - return ((o_accmode & O_ACCMODE) == O_RDONLY || - (o_accmode & O_ACCMODE) == O_RDWR); + return ((o_accmode & O_ACCMODE) == O_RDONLY || (o_accmode & O_ACCMODE) == O_RDWR); } bool FileDescriptorServer::IsWritable(int fd) { diff --git a/src/jsonrpccpp/server/connectors/filedescriptorserver.h b/src/jsonrpccpp/server/connectors/filedescriptorserver.h index e9dbbbfb..7da48611 100644 --- a/src/jsonrpccpp/server/connectors/filedescriptorserver.h +++ b/src/jsonrpccpp/server/connectors/filedescriptorserver.h @@ -19,40 +19,40 @@ #include namespace jsonrpc { -/** - * This class is the file descriptor implementation of an - * AbstractServerConnector. - * It uses the POSIX file API and POSIX thread API to performs its job. - * Each client request is handled in a new thread. - */ -class FileDescriptorServer : public AbstractThreadedServer { -public: /** - * AbstractServerConnector - * @param inputfd The file descriptor already open for us to read - * @param outputfd The file descriptor already open for us to write + * This class is the file descriptor implementation of an + * AbstractServerConnector. + * It uses the POSIX file API and POSIX thread API to performs its job. + * Each client request is handled in a new thread. */ - FileDescriptorServer(int inputfd, int outputfd); - - virtual bool InitializeListener(); - virtual int CheckForConnection(); - virtual void HandleConnection(int connection); - -protected: - int inputfd; - int outputfd; - StreamReader reader; - StreamWriter writer; - - bool IsReadable(int fd); - bool IsWritable(int fd); - - // For select operation - fd_set read_fds; - fd_set write_fds; - fd_set except_fds; - struct timeval timeout; -}; -} + class FileDescriptorServer : public AbstractThreadedServer { + public: + /** + * AbstractServerConnector + * @param inputfd The file descriptor already open for us to read + * @param outputfd The file descriptor already open for us to write + */ + FileDescriptorServer(int inputfd, int outputfd); + + virtual bool InitializeListener(); + virtual int CheckForConnection(); + virtual void HandleConnection(int connection); + + protected: + int inputfd; + int outputfd; + StreamReader reader; + StreamWriter writer; + + bool IsReadable(int fd); + bool IsWritable(int fd); + + // For select operation + fd_set read_fds; + fd_set write_fds; + fd_set except_fds; + struct timeval timeout; + }; +} // namespace jsonrpc #endif /* JSONRPC_CPP_FILEDESCRIPTORSERVERCONNECTOR_H_ */ diff --git a/src/jsonrpccpp/server/connectors/httpserver.cpp b/src/jsonrpccpp/server/connectors/httpserver.cpp index d3cb08bf..605f6294 100644 --- a/src/jsonrpccpp/server/connectors/httpserver.cpp +++ b/src/jsonrpccpp/server/connectors/httpserver.cpp @@ -27,19 +27,15 @@ struct mhd_coninfo { int code; }; -HttpServer::HttpServer(int port, const std::string &sslcert, - const std::string &sslkey, int threads) - : AbstractServerConnector(), port(port), threads(threads), running(false), - path_sslcert(sslcert), path_sslkey(sslkey), daemon(NULL), - bindlocalhost(false) {} +HttpServer::HttpServer(int port, const std::string &sslcert, const std::string &sslkey, int threads) + : AbstractServerConnector(), port(port), threads(threads), running(false), path_sslcert(sslcert), path_sslkey(sslkey), daemon(NULL), bindlocalhost(false) {} HttpServer::~HttpServer() {} IClientConnectionHandler *HttpServer::GetHandler(const std::string &url) { if (AbstractServerConnector::GetHandler() != NULL) return AbstractServerConnector::GetHandler(); - map::iterator it = - this->urlhandler.find(url); + map::iterator it = this->urlhandler.find(url); if (it != this->urlhandler.end()) return it->second; return NULL; @@ -52,10 +48,8 @@ HttpServer &HttpServer::BindLocalhost() { bool HttpServer::StartListening() { if (!this->running) { - const bool has_epoll = - (MHD_is_feature_supported(MHD_FEATURE_EPOLL) == MHD_YES); - const bool has_poll = - (MHD_is_feature_supported(MHD_FEATURE_POLL) == MHD_YES); + const bool has_epoll = (MHD_is_feature_supported(MHD_FEATURE_EPOLL) == MHD_YES); + const bool has_poll = (MHD_is_feature_supported(MHD_FEATURE_POLL) == MHD_YES); unsigned int mhd_flags = MHD_USE_DUAL_STACK; if (has_epoll) @@ -76,29 +70,23 @@ bool HttpServer::StartListening() { loopback_addr.sin_port = htons(this->port); loopback_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); - this->daemon = MHD_start_daemon( - mhd_flags, this->port, NULL, NULL, HttpServer::callback, this, - MHD_OPTION_THREAD_POOL_SIZE, this->threads, MHD_OPTION_SOCK_ADDR, - (struct sockaddr *)(&(this->loopback_addr)), MHD_OPTION_END); + this->daemon = MHD_start_daemon(mhd_flags, this->port, NULL, NULL, HttpServer::callback, this, MHD_OPTION_THREAD_POOL_SIZE, this->threads, + MHD_OPTION_SOCK_ADDR, (struct sockaddr *)(&(this->loopback_addr)), MHD_OPTION_END); } else if (!this->path_sslcert.empty() && !this->path_sslkey.empty()) { try { SpecificationParser::GetFileContent(this->path_sslcert, this->sslcert); SpecificationParser::GetFileContent(this->path_sslkey, this->sslkey); - this->daemon = MHD_start_daemon( - MHD_USE_SSL | mhd_flags, this->port, NULL, NULL, - HttpServer::callback, this, MHD_OPTION_HTTPS_MEM_KEY, - this->sslkey.c_str(), MHD_OPTION_HTTPS_MEM_CERT, - this->sslcert.c_str(), MHD_OPTION_THREAD_POOL_SIZE, this->threads, - MHD_OPTION_END); + this->daemon = + MHD_start_daemon(MHD_USE_SSL | mhd_flags, this->port, NULL, NULL, HttpServer::callback, this, MHD_OPTION_HTTPS_MEM_KEY, this->sslkey.c_str(), + MHD_OPTION_HTTPS_MEM_CERT, this->sslcert.c_str(), MHD_OPTION_THREAD_POOL_SIZE, this->threads, MHD_OPTION_END); } catch (JsonRpcException &ex) { return false; } } else { - this->daemon = MHD_start_daemon( - mhd_flags, this->port, NULL, NULL, HttpServer::callback, this, - MHD_OPTION_THREAD_POOL_SIZE, this->threads, MHD_OPTION_END); + this->daemon = + MHD_start_daemon(mhd_flags, this->port, NULL, NULL, HttpServer::callback, this, MHD_OPTION_THREAD_POOL_SIZE, this->threads, MHD_OPTION_END); } if (this->daemon != NULL) this->running = true; @@ -115,49 +103,38 @@ bool HttpServer::StopListening() { } bool HttpServer::SendResponse(const string &response, void *addInfo) { - struct mhd_coninfo *client_connection = - static_cast(addInfo); - struct MHD_Response *result = MHD_create_response_from_buffer( - response.size(), (void *)response.c_str(), MHD_RESPMEM_MUST_COPY); + struct mhd_coninfo *client_connection = static_cast(addInfo); + struct MHD_Response *result = MHD_create_response_from_buffer(response.size(), (void *)response.c_str(), MHD_RESPMEM_MUST_COPY); MHD_add_response_header(result, "Content-Type", "application/json"); MHD_add_response_header(result, "Access-Control-Allow-Origin", "*"); - int ret = MHD_queue_response(client_connection->connection, - client_connection->code, result); + int ret = MHD_queue_response(client_connection->connection, client_connection->code, result); MHD_destroy_response(result); return ret == MHD_YES; } bool HttpServer::SendOptionsResponse(void *addInfo) { - struct mhd_coninfo *client_connection = - static_cast(addInfo); - struct MHD_Response *result = - MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_MUST_COPY); + struct mhd_coninfo *client_connection = static_cast(addInfo); + struct MHD_Response *result = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_MUST_COPY); MHD_add_response_header(result, "Allow", "POST, OPTIONS"); MHD_add_response_header(result, "Access-Control-Allow-Origin", "*"); - MHD_add_response_header(result, "Access-Control-Allow-Headers", - "origin, content-type, accept"); + MHD_add_response_header(result, "Access-Control-Allow-Headers", "origin, content-type, accept"); MHD_add_response_header(result, "DAV", "1"); - int ret = MHD_queue_response(client_connection->connection, - client_connection->code, result); + int ret = MHD_queue_response(client_connection->connection, client_connection->code, result); MHD_destroy_response(result); return ret == MHD_YES; } -void HttpServer::SetUrlHandler(const string &url, - IClientConnectionHandler *handler) { +void HttpServer::SetUrlHandler(const string &url, IClientConnectionHandler *handler) { this->urlhandler[url] = handler; this->SetHandler(NULL); } -HttpServer::MicroHttpdResult HttpServer::callback( - void *cls, MHD_Connection *connection, const char *url, - const char *method, const char *version, - const char *upload_data, size_t *upload_data_size, - void **con_cls) { +HttpServer::MicroHttpdResult HttpServer::callback(void *cls, MHD_Connection *connection, const char *url, const char *method, const char *version, + const char *upload_data, size_t *upload_data_size, void **con_cls) { (void)version; if (*con_cls == NULL) { struct mhd_coninfo *client_connection = new mhd_coninfo; @@ -166,8 +143,7 @@ HttpServer::MicroHttpdResult HttpServer::callback( *con_cls = client_connection; return MHD_YES; } - struct mhd_coninfo *client_connection = - static_cast(*con_cls); + struct mhd_coninfo *client_connection = static_cast(*con_cls); if (string("POST") == method) { if (*upload_data_size != 0) { @@ -176,12 +152,10 @@ HttpServer::MicroHttpdResult HttpServer::callback( return MHD_YES; } else { string response; - IClientConnectionHandler *handler = - client_connection->server->GetHandler(string(url)); + IClientConnectionHandler *handler = client_connection->server->GetHandler(string(url)); if (handler == NULL) { client_connection->code = MHD_HTTP_INTERNAL_SERVER_ERROR; - client_connection->server->SendResponse( - "No client connection handler found", client_connection); + client_connection->server->SendResponse("No client connection handler found", client_connection); } else { client_connection->code = MHD_HTTP_OK; handler->HandleRequest(client_connection->request.str(), response); @@ -193,8 +167,7 @@ HttpServer::MicroHttpdResult HttpServer::callback( client_connection->server->SendOptionsResponse(client_connection); } else { client_connection->code = MHD_HTTP_METHOD_NOT_ALLOWED; - client_connection->server->SendResponse("Not allowed HTTP Method", - client_connection); + client_connection->server->SendResponse("Not allowed HTTP Method", client_connection); } if (client_connection != nullptr) { diff --git a/src/jsonrpccpp/server/connectors/httpserver.h b/src/jsonrpccpp/server/connectors/httpserver.h index 6798be9c..f56ff673 100644 --- a/src/jsonrpccpp/server/connectors/httpserver.h +++ b/src/jsonrpccpp/server/connectors/httpserver.h @@ -33,67 +33,62 @@ typedef intptr_t ssize_t; #include namespace jsonrpc { -/** - * This class provides an embedded HTTP Server, based on libmicrohttpd, to - * handle incoming Requests and send HTTP 1.1 valid responses. Note that this - * class will always send HTTP-Status 200, even though an JSON-RPC Error might - * have occurred. Please always check for the JSON-RPC Error Header. - */ -class HttpServer : public AbstractServerConnector { -public: /** - * @brief HttpServer, constructor for the included HttpServer - * @param port on which the server is listening - * @param enableSpecification - defines if the specification is returned in - * case of a GET request - * @param sslcert - defines the path to a SSL certificate, if this path is != - * "", then SSL/HTTPS is used with the given certificate. + * This class provides an embedded HTTP Server, based on libmicrohttpd, to + * handle incoming Requests and send HTTP 1.1 valid responses. Note that this + * class will always send HTTP-Status 200, even though an JSON-RPC Error might + * have occurred. Please always check for the JSON-RPC Error Header. */ - HttpServer(int port, const std::string &sslcert = "", - const std::string &sslkey = "", int threads = 50); + class HttpServer : public AbstractServerConnector { + public: + /** + * @brief HttpServer, constructor for the included HttpServer + * @param port on which the server is listening + * @param enableSpecification - defines if the specification is returned in + * case of a GET request + * @param sslcert - defines the path to a SSL certificate, if this path is != + * "", then SSL/HTTPS is used with the given certificate. + */ + HttpServer(int port, const std::string &sslcert = "", const std::string &sslkey = "", int threads = 50); - ~HttpServer(); + ~HttpServer(); - //Bind to localhost only, deactivates TLS settings - HttpServer& BindLocalhost(); + // Bind to localhost only, deactivates TLS settings + HttpServer &BindLocalhost(); - virtual bool StartListening(); - virtual bool StopListening(); + virtual bool StartListening(); + virtual bool StopListening(); - bool virtual SendResponse(const std::string &response, void *addInfo = NULL); - bool virtual SendOptionsResponse(void *addInfo); + bool virtual SendResponse(const std::string &response, void *addInfo = NULL); + bool virtual SendOptionsResponse(void *addInfo); - void SetUrlHandler(const std::string &url, IClientConnectionHandler *handler); + void SetUrlHandler(const std::string &url, IClientConnectionHandler *handler); -private: + private: #if MHD_VERSION >= 0x00097002 - typedef MHD_Result MicroHttpdResult; + typedef MHD_Result MicroHttpdResult; #else - typedef int MicroHttpdResult; + typedef int MicroHttpdResult; #endif - int port; - int threads; - bool running; - std::string path_sslcert; - std::string path_sslkey; - std::string sslcert; - std::string sslkey; + int port; + int threads; + bool running; + std::string path_sslcert; + std::string path_sslkey; + std::string sslcert; + std::string sslkey; - struct MHD_Daemon *daemon; - bool bindlocalhost; - std::map urlhandler; - struct sockaddr_in loopback_addr; + struct MHD_Daemon *daemon; + bool bindlocalhost; + std::map urlhandler; + struct sockaddr_in loopback_addr; - static MicroHttpdResult callback(void *cls, struct MHD_Connection *connection, - const char *url, const char *method, - const char *version, - const char *upload_data, - size_t *upload_data_size, - void **con_cls); + static MicroHttpdResult callback(void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, + const char *upload_data, size_t *upload_data_size, void **con_cls); - IClientConnectionHandler *GetHandler(const std::string &url); -}; + IClientConnectionHandler *GetHandler(const std::string &url); + }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_HTTPSERVERCONNECTOR_H_ */ diff --git a/src/jsonrpccpp/server/connectors/linuxserialportserver.cpp b/src/jsonrpccpp/server/connectors/linuxserialportserver.cpp index e69b7209..970112b1 100644 --- a/src/jsonrpccpp/server/connectors/linuxserialportserver.cpp +++ b/src/jsonrpccpp/server/connectors/linuxserialportserver.cpp @@ -33,10 +33,8 @@ using namespace std; #define READ_TIMEOUT 0.001 // Set timeout in seconds -LinuxSerialPortServer::LinuxSerialPortServer(const std::string &deviceName, - size_t threads) - : AbstractThreadedServer(threads), deviceName(deviceName), - reader(DEFAULT_BUFFER_SIZE) {} +LinuxSerialPortServer::LinuxSerialPortServer(const std::string &deviceName, size_t threads) + : AbstractThreadedServer(threads), deviceName(deviceName), reader(DEFAULT_BUFFER_SIZE) {} LinuxSerialPortServer::~LinuxSerialPortServer() { close(this->serial_fd); } diff --git a/src/jsonrpccpp/server/connectors/linuxserialportserver.h b/src/jsonrpccpp/server/connectors/linuxserialportserver.h index 6ddd3421..c50764d6 100644 --- a/src/jsonrpccpp/server/connectors/linuxserialportserver.h +++ b/src/jsonrpccpp/server/connectors/linuxserialportserver.h @@ -24,39 +24,37 @@ #include "../abstractthreadedserver.h" namespace jsonrpc { -/** - * This class is the Linux/UNIX implementation of TCPSocketServer. - * It uses the POSIX socket API and POSIX thread API to performs its job. - * Each client request is handled in a new thread. - */ -class LinuxSerialPortServer : public AbstractThreadedServer { -public: /** - * @brief LinuxSerialPortServer, constructor of the Linux/UNIX - * implementation of class TcpSocketServer - * @param deviceName The ipv4 address on which the server should + * This class is the Linux/UNIX implementation of TCPSocketServer. + * It uses the POSIX socket API and POSIX thread API to performs its job. + * Each client request is handled in a new thread. */ - LinuxSerialPortServer(const std::string &deviceName, - size_t threads = 1); - - virtual ~LinuxSerialPortServer(); - - virtual bool InitializeListener(); - virtual int CheckForConnection(); - virtual void HandleConnection(int connection); - -protected: - std::string deviceName; - int serial_fd; - - StreamReader reader; - StreamWriter writer; - - // For select operation - fd_set read_fds; - struct timeval timeout; - -}; + class LinuxSerialPortServer : public AbstractThreadedServer { + public: + /** + * @brief LinuxSerialPortServer, constructor of the Linux/UNIX + * implementation of class TcpSocketServer + * @param deviceName The ipv4 address on which the server should + */ + LinuxSerialPortServer(const std::string &deviceName, size_t threads = 1); + + virtual ~LinuxSerialPortServer(); + + virtual bool InitializeListener(); + virtual int CheckForConnection(); + virtual void HandleConnection(int connection); + + protected: + std::string deviceName; + int serial_fd; + + StreamReader reader; + StreamWriter writer; + + // For select operation + fd_set read_fds; + struct timeval timeout; + }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_LINUXSERIALPORTSERVERCONNECTOR_H_ */ diff --git a/src/jsonrpccpp/server/connectors/linuxtcpsocketserver.cpp b/src/jsonrpccpp/server/connectors/linuxtcpsocketserver.cpp index a82ad84f..d18db6ac 100644 --- a/src/jsonrpccpp/server/connectors/linuxtcpsocketserver.cpp +++ b/src/jsonrpccpp/server/connectors/linuxtcpsocketserver.cpp @@ -26,9 +26,7 @@ using namespace jsonrpc; using namespace std; -LinuxTcpSocketServer::LinuxTcpSocketServer(const std::string &ipToBind, - const unsigned int &port, - size_t threads) +LinuxTcpSocketServer::LinuxTcpSocketServer(const std::string &ipToBind, const unsigned int &port, size_t threads) : AbstractThreadedServer(threads), ipToBind(ipToBind), port(port) {} LinuxTcpSocketServer::~LinuxTcpSocketServer() { @@ -44,8 +42,7 @@ bool LinuxTcpSocketServer::InitializeListener() { fcntl(this->socket_fd, F_SETFL, FNDELAY); int reuseaddr = 1; - setsockopt(this->socket_fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, - sizeof(reuseaddr)); + setsockopt(this->socket_fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr)); /* start with a clean address structure */ memset(&(this->address), 0, sizeof(struct sockaddr_in)); @@ -54,9 +51,7 @@ bool LinuxTcpSocketServer::InitializeListener() { inet_aton(this->ipToBind.c_str(), &(this->address.sin_addr)); this->address.sin_port = htons(this->port); - if (::bind(this->socket_fd, - reinterpret_cast(&(this->address)), - sizeof(struct sockaddr_in)) != 0) { + if (::bind(this->socket_fd, reinterpret_cast(&(this->address)), sizeof(struct sockaddr_in)) != 0) { return false; } @@ -70,9 +65,7 @@ int LinuxTcpSocketServer::CheckForConnection() { struct sockaddr_in connection_address; memset(&connection_address, 0, sizeof(struct sockaddr_in)); socklen_t address_length = sizeof(connection_address); - return accept(this->socket_fd, - reinterpret_cast(&(connection_address)), - &address_length); + return accept(this->socket_fd, reinterpret_cast(&(connection_address)), &address_length); } void LinuxTcpSocketServer::HandleConnection(int connection) { @@ -106,8 +99,7 @@ int LinuxTcpSocketServer::CloseByReset(const int &fd) { so_linger.l_onoff = 1; so_linger.l_linger = 0; - int ret = - setsockopt(fd, SOL_SOCKET, SO_LINGER, &so_linger, sizeof(so_linger)); + int ret = setsockopt(fd, SOL_SOCKET, SO_LINGER, &so_linger, sizeof(so_linger)); if (ret != 0) return ret; diff --git a/src/jsonrpccpp/server/connectors/linuxtcpsocketserver.h b/src/jsonrpccpp/server/connectors/linuxtcpsocketserver.h index 05202cd4..9af97368 100644 --- a/src/jsonrpccpp/server/connectors/linuxtcpsocketserver.h +++ b/src/jsonrpccpp/server/connectors/linuxtcpsocketserver.h @@ -23,71 +23,70 @@ #include "../abstractthreadedserver.h" namespace jsonrpc { -/** - * This class is the Linux/UNIX implementation of TCPSocketServer. - * It uses the POSIX socket API and POSIX thread API to performs its job. - * Each client request is handled in a new thread. - */ -class LinuxTcpSocketServer : public AbstractThreadedServer { -public: /** - * @brief LinuxTcpSocketServer, constructor of the Linux/UNIX - * implementation of class TcpSocketServer - * @param ipToBind The ipv4 address on which the server should - * bind and listen - * @param port The port on which the server should bind and listen + * This class is the Linux/UNIX implementation of TCPSocketServer. + * It uses the POSIX socket API and POSIX thread API to performs its job. + * Each client request is handled in a new thread. */ - LinuxTcpSocketServer(const std::string &ipToBind, const unsigned int &port, - size_t threads = 1); + class LinuxTcpSocketServer : public AbstractThreadedServer { + public: + /** + * @brief LinuxTcpSocketServer, constructor of the Linux/UNIX + * implementation of class TcpSocketServer + * @param ipToBind The ipv4 address on which the server should + * bind and listen + * @param port The port on which the server should bind and listen + */ + LinuxTcpSocketServer(const std::string &ipToBind, const unsigned int &port, size_t threads = 1); - virtual ~LinuxTcpSocketServer(); + virtual ~LinuxTcpSocketServer(); - virtual bool InitializeListener(); - virtual int CheckForConnection(); - virtual void HandleConnection(int connection); + virtual bool InitializeListener(); + virtual int CheckForConnection(); + virtual void HandleConnection(int connection); -protected: - std::string ipToBind; - unsigned int port; - int socket_fd; - struct sockaddr_in address; + protected: + std::string ipToBind; + unsigned int port; + int socket_fd; + struct sockaddr_in address; - /** - * @brief A method that wait for the client to close the tcp session - * - * This method wait for the client to close the tcp session in order to avoid - * the server to enter in TIME_WAIT status. - * Entering in TIME_WAIT status with too many clients may occur in a DOS - * attack - * since server will not be able to use a new socket when a new client - * connects. - * @param fd The file descriptor of the socket that should be closed by the - * client - * @param timeout The maximum time the server will wait for the client to - * close the tcp session in microseconds. - * @returns A boolean indicating the success or the failure of the operation - */ - bool WaitClientClose(const int &fd, const int &timeout = 100000); - /** - * @brief A method that close a socket by reseting it - * - * This method reset the tcp session in order to avoid enter in TIME_WAIT - * state. - * @param fd The file descriptor of the socket that should be reset - * @returns The return value of POSIX close() method - */ - int CloseByReset(const int &fd); - /** - * @brief A method that cleanly close a socket by avoid TIME_WAIT state - * - * This method uses WaitClientClose and ClodeByReset to clenly close a tcp - * session with a client - * (avoiding TIME_WAIT to avoid DOS attacks). - * @param fd The file descriptor of the socket that should be cleanly closed - * @returns The return value of POSIX close() method - */ - int CleanClose(const int &fd); -}; + /** + * @brief A method that wait for the client to close the tcp session + * + * This method wait for the client to close the tcp session in order to avoid + * the server to enter in TIME_WAIT status. + * Entering in TIME_WAIT status with too many clients may occur in a DOS + * attack + * since server will not be able to use a new socket when a new client + * connects. + * @param fd The file descriptor of the socket that should be closed by the + * client + * @param timeout The maximum time the server will wait for the client to + * close the tcp session in microseconds. + * @returns A boolean indicating the success or the failure of the operation + */ + bool WaitClientClose(const int &fd, const int &timeout = 100000); + /** + * @brief A method that close a socket by reseting it + * + * This method reset the tcp session in order to avoid enter in TIME_WAIT + * state. + * @param fd The file descriptor of the socket that should be reset + * @returns The return value of POSIX close() method + */ + int CloseByReset(const int &fd); + /** + * @brief A method that cleanly close a socket by avoid TIME_WAIT state + * + * This method uses WaitClientClose and ClodeByReset to clenly close a tcp + * session with a client + * (avoiding TIME_WAIT to avoid DOS attacks). + * @param fd The file descriptor of the socket that should be cleanly closed + * @returns The return value of POSIX close() method + */ + int CleanClose(const int &fd); + }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_LINUXTCPSOCKETSERVERCONNECTOR_H_ */ diff --git a/src/jsonrpccpp/server/connectors/redisserver.cpp b/src/jsonrpccpp/server/connectors/redisserver.cpp index 9ebed215..6d0f2533 100644 --- a/src/jsonrpccpp/server/connectors/redisserver.cpp +++ b/src/jsonrpccpp/server/connectors/redisserver.cpp @@ -20,8 +20,7 @@ using namespace jsonrpc; * @param request The request is returned here. * @return Returns true on success, false otherwise. */ -bool ProcessRedisReply(redisReply *req, std::string &ret_queue, - std::string &request) { +bool ProcessRedisReply(redisReply *req, std::string &ret_queue, std::string &request) { // The return from hiredis is strange in that it's always an array of // length 2, with the first element the name of the key as a string, @@ -55,8 +54,7 @@ bool ProcessRedisReply(redisReply *req, std::string &ret_queue, return true; } -RedisServer::RedisServer(std::string host, int port, std::string queue) - : running(false), host(host), port(port), queue(queue), con(NULL) {} +RedisServer::RedisServer(std::string host, int port, std::string queue) : running(false), host(host), port(port), queue(queue), con(NULL) {} bool RedisServer::StartListening() { if (this->running) { @@ -74,8 +72,7 @@ bool RedisServer::StartListening() { } this->running = true; - int ret = pthread_create(&(this->listenning_thread), NULL, - RedisServer::LaunchLoop, this); + int ret = pthread_create(&(this->listenning_thread), NULL, RedisServer::LaunchLoop, this); this->running = static_cast(ret == 0); return this->running; @@ -93,11 +90,9 @@ bool RedisServer::StopListening() { return !(this->running); } -bool RedisServer::SendResponse(const std::string &response, - const std::string &ret_queue) { +bool RedisServer::SendResponse(const std::string &response, const std::string &ret_queue) { redisReply *ret; - ret = (redisReply *)redisCommand(con, "LPUSH %s %s", ret_queue.c_str(), - response.c_str()); + ret = (redisReply *)redisCommand(con, "LPUSH %s %s", ret_queue.c_str(), response.c_str()); if (ret == NULL) { return false; diff --git a/src/jsonrpccpp/server/connectors/redisserver.h b/src/jsonrpccpp/server/connectors/redisserver.h index bdc8627a..1340ad74 100644 --- a/src/jsonrpccpp/server/connectors/redisserver.h +++ b/src/jsonrpccpp/server/connectors/redisserver.h @@ -11,13 +11,12 @@ #define JSONRPC_CPP_REDISSERVERCONNECTOR_H_ #include -#include #include +#include #include "../abstractserverconnector.h" -namespace jsonrpc -{ +namespace jsonrpc { /** * This class is the redis implementation of an AbstractServerConnector. * It uses hiredis to connect to a designated redis server. @@ -27,91 +26,82 @@ namespace jsonrpc * response/return queue name, processes the request and then uses LPUSH to * send the result back to the client. */ - class RedisServer: public AbstractServerConnector - { - public: - /** - * RedisServer - * @param host The ip address of the redis server. - * @param port The port of the redis server. - * @param queue The queue to listen on. - */ - RedisServer(std::string host, int port, std::string queue); - - - /** - * This method launches the listening loop that will handle client connections. - * @return true for success, false otherwise. - */ - bool StartListening(); - - - /** - * This method stops the listening loop that will handle client connections. - * @return True if successful, false otherwise or if not listening. - */ - bool StopListening(); - - - /** - * This method sends the result of the RPC Call back to the client - * @param response The response to send to the client. - * @param ret_queue The queue to send the response to. - * @return A boolean that indicates the success or the failure of the operation. - */ - bool SendResponse(const std::string& response, const std::string& ret_queue); - - protected: - - /** - * Callback for listening thread to start ListenLoop. - * @param p_data A pointer to this object. - * @return Nothing. - */ - static void* LaunchLoop(void *p_data); - - - /** - * Main loop listening for connections. The loop pops requests off the - * servers' queue and processes them. It then calls this class's - * OnRequest method which handles the request and sends the response - * using this classes' SendResponse method. - */ - void ListenLoop(); - - - - /** - * @brief Keeps track of whether the server is running. - */ - bool running; - - /** - * @brief Our listening thread - */ - pthread_t listenning_thread; - - /** - * @brief Ip address of the redis server - */ - std::string host; - - /** - * @brief port of the redis server - */ - int port; - - /** - * @brief Queue that we are messaging. - */ - std::string queue; - - /** - * @brief Our connection to the redis server - */ - redisContext * con; - + class RedisServer : public AbstractServerConnector { + public: + /** + * RedisServer + * @param host The ip address of the redis server. + * @param port The port of the redis server. + * @param queue The queue to listen on. + */ + RedisServer(std::string host, int port, std::string queue); + + /** + * This method launches the listening loop that will handle client connections. + * @return true for success, false otherwise. + */ + bool StartListening(); + + /** + * This method stops the listening loop that will handle client connections. + * @return True if successful, false otherwise or if not listening. + */ + bool StopListening(); + + /** + * This method sends the result of the RPC Call back to the client + * @param response The response to send to the client. + * @param ret_queue The queue to send the response to. + * @return A boolean that indicates the success or the failure of the operation. + */ + bool SendResponse(const std::string &response, const std::string &ret_queue); + + protected: + /** + * Callback for listening thread to start ListenLoop. + * @param p_data A pointer to this object. + * @return Nothing. + */ + static void *LaunchLoop(void *p_data); + + /** + * Main loop listening for connections. The loop pops requests off the + * servers' queue and processes them. It then calls this class's + * OnRequest method which handles the request and sends the response + * using this classes' SendResponse method. + */ + void ListenLoop(); + + /** + * @brief Keeps track of whether the server is running. + */ + bool running; + + /** + * @brief Our listening thread + */ + pthread_t listenning_thread; + + /** + * @brief Ip address of the redis server + */ + std::string host; + + /** + * @brief port of the redis server + */ + int port; + + /** + * @brief Queue that we are messaging. + */ + std::string queue; + + /** + * @brief Our connection to the redis server + */ + redisContext *con; }; -} +} // namespace jsonrpc #endif /* JSONRPC_CPP_REDISSERVERCONNECTOR_H_ */ diff --git a/src/jsonrpccpp/server/connectors/tcpsocketserver.cpp b/src/jsonrpccpp/server/connectors/tcpsocketserver.cpp index 0efe9b06..2d628c21 100644 --- a/src/jsonrpccpp/server/connectors/tcpsocketserver.cpp +++ b/src/jsonrpccpp/server/connectors/tcpsocketserver.cpp @@ -18,9 +18,7 @@ using namespace jsonrpc; using namespace std; -TcpSocketServer::TcpSocketServer(const std::string &ipToBind, - const unsigned int &port) - : AbstractServerConnector() { +TcpSocketServer::TcpSocketServer(const std::string &ipToBind, const unsigned int &port) : AbstractServerConnector() { #ifdef _WIN32 this->realSocket = new WindowsTcpSocketServer(ipToBind, port); #else diff --git a/src/jsonrpccpp/server/connectors/tcpsocketserver.h b/src/jsonrpccpp/server/connectors/tcpsocketserver.h index d3b89067..1d97e619 100644 --- a/src/jsonrpccpp/server/connectors/tcpsocketserver.h +++ b/src/jsonrpccpp/server/connectors/tcpsocketserver.h @@ -13,63 +13,63 @@ #include "../abstractserverconnector.h" namespace jsonrpc { -/** - * This class provides an embedded TCP Socket Server that handle incoming - * Requests and send result over same socket. - * It uses the delimiter character to distinct a full RPC Message over the - * tcp flow. This character is parametered on - * compilation time in implementation files. The default value for this - * delimiter is 0x0A a.k.a. "new line". - * This class hides OS specific features in real implementation of this - * server. Currently it has implementation for - * both Linux and Windows. - */ -class TcpSocketServer : public AbstractServerConnector { -public: - /** - * @brief TcpSocketServer, constructor for the included - * TcpSocketServer - * - * Instanciates the real implementation of TcpSocketServerPrivate - * depending on running OS. - * - * @param ipToBind The ipv4 address on which the server should - * bind and listen - * @param port The port on which the server should bind and listen - */ - TcpSocketServer(const std::string &ipToBind, const unsigned int &port); - - ~TcpSocketServer(); - /** - * @brief The AbstractServerConnector::StartListening method overload. - * - * This method launches the listening loop that will handle client - * connections. - * The return value depends on the current listening states : - * - not listening and no error come up while bind and listen returns true - * - not listening but error happen on bind or listen returns false - * - is called while listening returns false - * - * @return A boolean that indicates the success or the failure of the - * operation. - */ - bool StartListening(); /** - * @brief The AbstractServerConnector::StopListening method overload. - * - * This method stops the listening loop that will handle client connections. - * The return value depends on the current listening states : - * - listening and successfully stops the listen loop returns true - * - is called while not listening returns false - * - * @return A boolean that indicates the success or the failure of the - * operation. + * This class provides an embedded TCP Socket Server that handle incoming + * Requests and send result over same socket. + * It uses the delimiter character to distinct a full RPC Message over the + * tcp flow. This character is parametered on + * compilation time in implementation files. The default value for this + * delimiter is 0x0A a.k.a. "new line". + * This class hides OS specific features in real implementation of this + * server. Currently it has implementation for + * both Linux and Windows. */ - bool StopListening(); + class TcpSocketServer : public AbstractServerConnector { + public: + /** + * @brief TcpSocketServer, constructor for the included + * TcpSocketServer + * + * Instanciates the real implementation of TcpSocketServerPrivate + * depending on running OS. + * + * @param ipToBind The ipv4 address on which the server should + * bind and listen + * @param port The port on which the server should bind and listen + */ + TcpSocketServer(const std::string &ipToBind, const unsigned int &port); + + ~TcpSocketServer(); + /** + * @brief The AbstractServerConnector::StartListening method overload. + * + * This method launches the listening loop that will handle client + * connections. + * The return value depends on the current listening states : + * - not listening and no error come up while bind and listen returns true + * - not listening but error happen on bind or listen returns false + * - is called while listening returns false + * + * @return A boolean that indicates the success or the failure of the + * operation. + */ + bool StartListening(); + /** + * @brief The AbstractServerConnector::StopListening method overload. + * + * This method stops the listening loop that will handle client connections. + * The return value depends on the current listening states : + * - listening and successfully stops the listen loop returns true + * - is called while not listening returns false + * + * @return A boolean that indicates the success or the failure of the + * operation. + */ + bool StopListening(); -protected: - AbstractServerConnector *realSocket; -}; + protected: + AbstractServerConnector *realSocket; + }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_TCPSOCKETSERVERCONNECTOR_H_ */ diff --git a/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp index dcbf34bf..9dc28f8f 100644 --- a/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp +++ b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp @@ -22,10 +22,8 @@ using namespace jsonrpc; using namespace std; -UnixDomainSocketServer::UnixDomainSocketServer(const string &socket_path, - size_t threads) - : AbstractThreadedServer(threads), socket_path(socket_path), socket_fd(-1) { -} +UnixDomainSocketServer::UnixDomainSocketServer(const string &socket_path, size_t threads) + : AbstractThreadedServer(threads), socket_path(socket_path), socket_fd(-1) {} UnixDomainSocketServer::~UnixDomainSocketServer() { if (this->socket_fd != -1) @@ -50,9 +48,7 @@ bool UnixDomainSocketServer::InitializeListener() { this->address.sun_family = AF_UNIX; strncpy(this->address.sun_path, this->socket_path.c_str(), 107); - if (::bind(this->socket_fd, - reinterpret_cast(&(this->address)), - sizeof(struct sockaddr_un)) != 0) { + if (::bind(this->socket_fd, reinterpret_cast(&(this->address)), sizeof(struct sockaddr_un)) != 0) { return false; } @@ -66,9 +62,7 @@ int UnixDomainSocketServer::CheckForConnection() { socklen_t address_length = sizeof(this->address); int fd; - fd = accept(this->socket_fd, - reinterpret_cast(&(this->address)), - &address_length); + fd = accept(this->socket_fd, reinterpret_cast(&(this->address)), &address_length); return fd; } diff --git a/src/jsonrpccpp/server/connectors/unixdomainsocketserver.h b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.h index 8a5c3287..1819bd59 100644 --- a/src/jsonrpccpp/server/connectors/unixdomainsocketserver.h +++ b/src/jsonrpccpp/server/connectors/unixdomainsocketserver.h @@ -24,29 +24,29 @@ #include "../abstractthreadedserver.h" namespace jsonrpc { -/** - * This class provides an embedded Unix Domain Socket Server,to handle incoming - * Requests. - */ -class UnixDomainSocketServer : public AbstractThreadedServer { -public: /** - * @brief UnixDomainSocketServer, constructor for the included - * UnixDomainSocketServer - * @param socket_path, a string containing the path to the unix socket + * This class provides an embedded Unix Domain Socket Server,to handle incoming + * Requests. */ - UnixDomainSocketServer(const std::string &socket_path, size_t threads = 1); - virtual ~UnixDomainSocketServer(); + class UnixDomainSocketServer : public AbstractThreadedServer { + public: + /** + * @brief UnixDomainSocketServer, constructor for the included + * UnixDomainSocketServer + * @param socket_path, a string containing the path to the unix socket + */ + UnixDomainSocketServer(const std::string &socket_path, size_t threads = 1); + virtual ~UnixDomainSocketServer(); - virtual bool InitializeListener(); - virtual int CheckForConnection(); - virtual void HandleConnection(int connection); + virtual bool InitializeListener(); + virtual int CheckForConnection(); + virtual void HandleConnection(int connection); -protected: - std::string socket_path; - int socket_fd; - struct sockaddr_un address; -}; + protected: + std::string socket_path; + int socket_fd; + struct sockaddr_un address; + }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_HTTPSERVERCONNECTOR_H_ */ diff --git a/src/jsonrpccpp/server/connectors/windowstcpsocketserver.cpp b/src/jsonrpccpp/server/connectors/windowstcpsocketserver.cpp index 42331c1e..dee3b8f6 100644 --- a/src/jsonrpccpp/server/connectors/windowstcpsocketserver.cpp +++ b/src/jsonrpccpp/server/connectors/windowstcpsocketserver.cpp @@ -28,10 +28,8 @@ using namespace std; #define DELIMITER_CHAR char(0x0A) #endif // DELIMITER_CHAR -WindowsTcpSocketServer::WindowsTcpSocketServer(const std::string &ipToBind, - const unsigned int &port) - : AbstractServerConnector(), ipToBind(ipToBind), port(port), - running(false) {} +WindowsTcpSocketServer::WindowsTcpSocketServer(const std::string &ipToBind, const unsigned int &port) + : AbstractServerConnector(), ipToBind(ipToBind), port(port), running(false) {} WindowsTcpSocketServer::~WindowsTcpSocketServer() {} @@ -46,8 +44,7 @@ bool WindowsTcpSocketServer::StartListening() { unsigned long nonBlocking = 1; ioctlsocket(this->socket_fd, FIONBIO, &nonBlocking); // Set non blocking int reuseaddr = 1; - setsockopt(this->socket_fd, SOL_SOCKET, SO_REUSEADDR, - reinterpret_cast(&reuseaddr), sizeof(reuseaddr)); + setsockopt(this->socket_fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&reuseaddr), sizeof(reuseaddr)); /* start with a clean address structure */ memset(&(this->address), 0, sizeof(SOCKADDR_IN)); @@ -56,8 +53,7 @@ bool WindowsTcpSocketServer::StartListening() { this->address.sin_addr.s_addr = inet_addr(this->ipToBind.c_str()); this->address.sin_port = htons(this->port); - if (::bind(this->socket_fd, reinterpret_cast(&(this->address)), - sizeof(SOCKADDR_IN)) != 0) { + if (::bind(this->socket_fd, reinterpret_cast(&(this->address)), sizeof(SOCKADDR_IN)) != 0) { return false; } @@ -66,10 +62,7 @@ bool WindowsTcpSocketServer::StartListening() { } // Launch listening loop there this->running = true; - HANDLE ret = CreateThread(NULL, 0, - reinterpret_cast( - &(WindowsTcpSocketServer::LaunchLoop)), - reinterpret_cast(this), 0, + HANDLE ret = CreateThread(NULL, 0, reinterpret_cast(&(WindowsTcpSocketServer::LaunchLoop)), reinterpret_cast(this), 0, &(this->listenning_thread)); if (ret == NULL) { ExitProcess(3); @@ -86,9 +79,7 @@ bool WindowsTcpSocketServer::StartListening() { bool WindowsTcpSocketServer::StopListening() { if (this->running) { this->running = false; - WaitForSingleObject( - OpenThread(THREAD_ALL_ACCESS, FALSE, this->listenning_thread), - INFINITE); + WaitForSingleObject(OpenThread(THREAD_ALL_ACCESS, FALSE, this->listenning_thread), INFINITE); closesocket(this->socket_fd); return !(this->running); } else { @@ -96,8 +87,7 @@ bool WindowsTcpSocketServer::StopListening() { } } -bool WindowsTcpSocketServer::SendResponse(const string &response, - void *addInfo) { +bool WindowsTcpSocketServer::SendResponse(const string &response, void *addInfo) { bool result = false; int connection_fd = reinterpret_cast(addInfo); @@ -118,8 +108,7 @@ bool WindowsTcpSocketServer::SendResponse(const string &response, } DWORD WINAPI WindowsTcpSocketServer::LaunchLoop(LPVOID lp_data) { - WindowsTcpSocketServer *instance = - reinterpret_cast(lp_data); + WindowsTcpSocketServer *instance = reinterpret_cast(lp_data); ; instance->ListenLoop(); CloseHandle(GetCurrentThread()); @@ -134,21 +123,15 @@ void WindowsTcpSocketServer::ListenLoop() { SOCKADDR_IN connection_address; memset(&connection_address, 0, sizeof(SOCKADDR_IN)); int address_length = sizeof(connection_address); - if ((connection_fd = accept( - this->socket_fd, reinterpret_cast(&connection_address), - &address_length)) != INVALID_SOCKET) { + if ((connection_fd = accept(this->socket_fd, reinterpret_cast(&connection_address), &address_length)) != INVALID_SOCKET) { unsigned long nonBlocking = 0; ioctlsocket(connection_fd, FIONBIO, &nonBlocking); // Set blocking DWORD client_thread; - struct GenerateResponseParameters *params = - new struct GenerateResponseParameters(); + struct GenerateResponseParameters *params = new struct GenerateResponseParameters(); params->instance = this; params->connection_fd = connection_fd; - HANDLE ret = - CreateThread(NULL, 0, - reinterpret_cast( - &(WindowsTcpSocketServer::GenerateResponse)), - reinterpret_cast(params), 0, &client_thread); + HANDLE ret = CreateThread(NULL, 0, reinterpret_cast(&(WindowsTcpSocketServer::GenerateResponse)), + reinterpret_cast(params), 0, &client_thread); if (ret == NULL) { delete params; params = NULL; @@ -163,8 +146,7 @@ void WindowsTcpSocketServer::ListenLoop() { } DWORD WINAPI WindowsTcpSocketServer::GenerateResponse(LPVOID lp_data) { - struct GenerateResponseParameters *params = - reinterpret_cast(lp_data); + struct GenerateResponseParameters *params = reinterpret_cast(lp_data); WindowsTcpSocketServer *instance = params->instance; int connection_fd = params->connection_fd; delete params; @@ -190,8 +172,7 @@ DWORD WINAPI WindowsTcpSocketServer::GenerateResponse(LPVOID lp_data) { // a memory leak. } -bool WindowsTcpSocketServer::WriteToSocket(const SOCKET &fd, - const string &toWrite) { +bool WindowsTcpSocketServer::WriteToSocket(const SOCKET &fd, const string &toWrite) { bool fullyWritten = false; bool errorOccured = false; string toSend = toWrite; @@ -209,8 +190,7 @@ bool WindowsTcpSocketServer::WriteToSocket(const SOCKET &fd, return fullyWritten && !errorOccured; } -bool WindowsTcpSocketServer::WaitClientClose(const SOCKET &fd, - const int &timeout) { +bool WindowsTcpSocketServer::WaitClientClose(const SOCKET &fd, const int &timeout) { bool ret = false; int i = 0; while ((recv(fd, NULL, 0, 0) != 0) && i < timeout) { @@ -227,8 +207,7 @@ int WindowsTcpSocketServer::CloseByReset(const SOCKET &fd) { so_linger.l_onoff = 1; so_linger.l_linger = 0; - int ret = setsockopt(fd, SOL_SOCKET, SO_LINGER, - reinterpret_cast(&so_linger), sizeof(so_linger)); + int ret = setsockopt(fd, SOL_SOCKET, SO_LINGER, reinterpret_cast(&so_linger), sizeof(so_linger)); if (ret != 0) return ret; @@ -249,8 +228,7 @@ struct ServerSocketInitializer { ServerSocketInitializer() { WSADATA init; if (WSAStartup(MAKEWORD(2, 2), &init) != 0) { - JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, - "An issue occurred while WSAStartup executed."); + JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "An issue occurred while WSAStartup executed."); } } diff --git a/src/jsonrpccpp/server/connectors/windowstcpsocketserver.h b/src/jsonrpccpp/server/connectors/windowstcpsocketserver.h index 1940e65a..9d5ca41e 100644 --- a/src/jsonrpccpp/server/connectors/windowstcpsocketserver.h +++ b/src/jsonrpccpp/server/connectors/windowstcpsocketserver.h @@ -16,126 +16,123 @@ #include "../abstractserverconnector.h" -namespace jsonrpc -{ +namespace jsonrpc { + /** + * This class is the Windows implementation of TCPSocketServer. + * It uses the Winsock2 socket API and Windows thread API to performs its job. + * Each client request is handled in a new thread. + */ + class WindowsTcpSocketServer : public AbstractServerConnector { + public: /** - * This class is the Windows implementation of TCPSocketServer. - * It uses the Winsock2 socket API and Windows thread API to performs its job. - * Each client request is handled in a new thread. - */ - class WindowsTcpSocketServer: public AbstractServerConnector - { - public: - /** - * @brief WindowsTcpSocketServer, constructor of the Windows implementation of class TcpSocketServer - * @param ipToBind The ipv4 address on which the server should bind and listen - * @param port The port on which the server should bind and listen - */ - WindowsTcpSocketServer(const std::string& ipToBind, const unsigned int &port); - /** - * @brief ~WindowsTcpSocketServer, the destructor of WindowsTcpSocketServer - */ - ~WindowsTcpSocketServer(); - /** - * @brief The real implementation TcpSocketServer::StartListening method. - * - * This method launches the listening loop that will handle client connections. - * The return value depends on the current listening states : - * - not listening and no error come up while bind and listen returns true - * - not listening but error happen on bind or listen returns false - * - is called while listening returns false - * - * @return A boolean that indicates the success or the failure of the operation. - */ - bool StartListening(); - /** - * @brief The real implementation TcpSocketServer::StopListening method. - * - * This method stops the listening loop that will handle client connections. - * The return value depends on the current listening states : - * - listening and successfully stops the listen loop returns true - * - is called while not listening returns false - * - * @return A boolean that indicates the success or the failure of the operation. - */ - bool StopListening(); + * @brief WindowsTcpSocketServer, constructor of the Windows implementation of class TcpSocketServer + * @param ipToBind The ipv4 address on which the server should bind and listen + * @param port The port on which the server should bind and listen + */ + WindowsTcpSocketServer(const std::string &ipToBind, const unsigned int &port); + /** + * @brief ~WindowsTcpSocketServer, the destructor of WindowsTcpSocketServer + */ + ~WindowsTcpSocketServer(); + /** + * @brief The real implementation TcpSocketServer::StartListening method. + * + * This method launches the listening loop that will handle client connections. + * The return value depends on the current listening states : + * - not listening and no error come up while bind and listen returns true + * - not listening but error happen on bind or listen returns false + * - is called while listening returns false + * + * @return A boolean that indicates the success or the failure of the operation. + */ + bool StartListening(); + /** + * @brief The real implementation TcpSocketServer::StopListening method. + * + * This method stops the listening loop that will handle client connections. + * The return value depends on the current listening states : + * - listening and successfully stops the listen loop returns true + * - is called while not listening returns false + * + * @return A boolean that indicates the success or the failure of the operation. + */ + bool StopListening(); - /** - * @brief The real implementation TcpSocketServer::SendResponse method. - * - * This method sends the result of the RPC Call over the tcp socket that the client has used to perform its request. - * @param response The response to send to the client - * @param addInfo Additionnal parameters (mainly client socket file descriptor) - * @return A boolean that indicates the success or the failure of the operation. - */ - bool SendResponse(const std::string& response, void* addInfo = NULL); + /** + * @brief The real implementation TcpSocketServer::SendResponse method. + * + * This method sends the result of the RPC Call over the tcp socket that the client has used to perform its request. + * @param response The response to send to the client + * @param addInfo Additionnal parameters (mainly client socket file descriptor) + * @return A boolean that indicates the success or the failure of the operation. + */ + bool SendResponse(const std::string &response, void *addInfo = NULL); - protected: - bool running; /*!< A boolean that is used to know the listening state*/ - std::string ipToBind; /*!< The ipv4 address on which the server should bind and listen*/ - unsigned int port; /*!< The port on which the server should bind and listen*/ - SOCKET socket_fd; /*!< The file descriptior of the listening socket*/ - SOCKADDR_IN address; /*!< The listening socket*/ + protected: + bool running; /*!< A boolean that is used to know the listening state*/ + std::string ipToBind; /*!< The ipv4 address on which the server should bind and listen*/ + unsigned int port; /*!< The port on which the server should bind and listen*/ + SOCKET socket_fd; /*!< The file descriptior of the listening socket*/ + SOCKADDR_IN address; /*!< The listening socket*/ - DWORD listenning_thread; /*!< The identifier of the listen loop thread*/ + DWORD listenning_thread; /*!< The identifier of the listen loop thread*/ - /** - * @brief The static method that is used as listening thread entry point - * @param lp_data The parameters for the thread entry point method - */ - static DWORD WINAPI LaunchLoop(LPVOID lp_data); - /** - * @brief The method that launches the listenning loop - */ - void ListenLoop(); - struct GenerateResponseParameters - { - WindowsTcpSocketServer *instance; - SOCKET connection_fd; - }; /*!< The structure used to give parameters to the Response generating method*/ - /** - * @brief The static method that is used as client request handling entry point - * @param lp_data The parameters for the thread entry point method - */ - static DWORD WINAPI GenerateResponse(LPVOID lp_data); - /** - * @brief A method that write a message to socket - * - * Tries to send the full message. - * @param fd The file descriptor of the socket message should be sent - * @param toSend The message to send over socket - * @returns A boolean indicating the success or the failure of the operation - */ - bool WriteToSocket(const SOCKET& fd, const std::string& toSend); - /** - * @brief A method that wait for the client to close the tcp session - * - * This method wait for the client to close the tcp session in order to avoid the server to enter in TIME_WAIT status. - * Entering in TIME_WAIT status with too many clients may occur in a DOS attack - * since server will not be able to use a new socket when a new client connects. - * @param fd The file descriptor of the socket that should be closed by the client - * @param timeout The maximum time the server will wait for the client to close the tcp session in milliseconds. - * @returns A boolean indicating the success or the failure of the operation - */ - bool WaitClientClose(const SOCKET& fd, const int &timeout = 100); - /** - * @brief A method that close a socket by reseting it - * - * This method reset the tcp session in order to avoid enter in TIME_WAIT state. - * @param fd The file descriptor of the socket that should be reset - * @returns The return value of POSIX close() method - */ - int CloseByReset(const SOCKET& fd); - /** - * @brief A method that cleanly close a socket by avoid TIME_WAIT state - * - * This method uses WaitClientClose and ClodeByReset to clenly close a tcp session with a client - * (avoiding TIME_WAIT to avoid DOS attacks). - * @param fd The file descriptor of the socket that should be cleanly closed - * @returns The return value of POSIX close() method - */ - int CleanClose(const SOCKET& fd); - }; + /** + * @brief The static method that is used as listening thread entry point + * @param lp_data The parameters for the thread entry point method + */ + static DWORD WINAPI LaunchLoop(LPVOID lp_data); + /** + * @brief The method that launches the listenning loop + */ + void ListenLoop(); + struct GenerateResponseParameters { + WindowsTcpSocketServer *instance; + SOCKET connection_fd; + }; /*!< The structure used to give parameters to the Response generating method*/ + /** + * @brief The static method that is used as client request handling entry point + * @param lp_data The parameters for the thread entry point method + */ + static DWORD WINAPI GenerateResponse(LPVOID lp_data); + /** + * @brief A method that write a message to socket + * + * Tries to send the full message. + * @param fd The file descriptor of the socket message should be sent + * @param toSend The message to send over socket + * @returns A boolean indicating the success or the failure of the operation + */ + bool WriteToSocket(const SOCKET &fd, const std::string &toSend); + /** + * @brief A method that wait for the client to close the tcp session + * + * This method wait for the client to close the tcp session in order to avoid the server to enter in TIME_WAIT status. + * Entering in TIME_WAIT status with too many clients may occur in a DOS attack + * since server will not be able to use a new socket when a new client connects. + * @param fd The file descriptor of the socket that should be closed by the client + * @param timeout The maximum time the server will wait for the client to close the tcp session in milliseconds. + * @returns A boolean indicating the success or the failure of the operation + */ + bool WaitClientClose(const SOCKET &fd, const int &timeout = 100); + /** + * @brief A method that close a socket by reseting it + * + * This method reset the tcp session in order to avoid enter in TIME_WAIT state. + * @param fd The file descriptor of the socket that should be reset + * @returns The return value of POSIX close() method + */ + int CloseByReset(const SOCKET &fd); + /** + * @brief A method that cleanly close a socket by avoid TIME_WAIT state + * + * This method uses WaitClientClose and ClodeByReset to clenly close a tcp session with a client + * (avoiding TIME_WAIT to avoid DOS attacks). + * @param fd The file descriptor of the socket that should be cleanly closed + * @returns The return value of POSIX close() method + */ + int CleanClose(const SOCKET &fd); + }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_WINDOWSTCPSOCKETSERVERCONNECTOR_H_ */ diff --git a/src/jsonrpccpp/server/iclientconnectionhandler.h b/src/jsonrpccpp/server/iclientconnectionhandler.h index f8f7899b..ce76f02a 100644 --- a/src/jsonrpccpp/server/iclientconnectionhandler.h +++ b/src/jsonrpccpp/server/iclientconnectionhandler.h @@ -12,23 +12,21 @@ #include -namespace jsonrpc -{ - class Procedure; - class IClientConnectionHandler { - public: - virtual ~IClientConnectionHandler() {} +namespace jsonrpc { + class Procedure; + class IClientConnectionHandler { + public: + virtual ~IClientConnectionHandler() {} - virtual void HandleRequest(const std::string& request, std::string& retValue) = 0; - }; + virtual void HandleRequest(const std::string &request, std::string &retValue) = 0; + }; - class IProtocolHandler : public IClientConnectionHandler - { - public: - virtual ~IProtocolHandler(){} + class IProtocolHandler : public IClientConnectionHandler { + public: + virtual ~IProtocolHandler() {} - virtual void AddProcedure(const Procedure& procedure) = 0; - }; -} + virtual void AddProcedure(const Procedure &procedure) = 0; + }; +} // namespace jsonrpc #endif // JSONRPC_CPP_ICLIENTCONNECTIONHANDLER_H diff --git a/src/jsonrpccpp/server/iprocedureinvokationhandler.h b/src/jsonrpccpp/server/iprocedureinvokationhandler.h index 5b96c286..141db3c9 100644 --- a/src/jsonrpccpp/server/iprocedureinvokationhandler.h +++ b/src/jsonrpccpp/server/iprocedureinvokationhandler.h @@ -11,19 +11,19 @@ #define JSONRPC_CPP_IPROCEDUREINVOKATIONHANDLER_H namespace Json { - class Value; + class Value; } namespace jsonrpc { - class Procedure; + class Procedure; - class IProcedureInvokationHandler { - public: - virtual ~IProcedureInvokationHandler() {} - virtual void HandleMethodCall(Procedure& proc, const Json::Value& input, Json::Value& output) = 0; - virtual void HandleNotificationCall(Procedure& proc, const Json::Value& input) = 0; - }; -} + class IProcedureInvokationHandler { + public: + virtual ~IProcedureInvokationHandler() {} + virtual void HandleMethodCall(Procedure &proc, const Json::Value &input, Json::Value &output) = 0; + virtual void HandleNotificationCall(Procedure &proc, const Json::Value &input) = 0; + }; +} // namespace jsonrpc -#endif //JSONRPC_CPP_IPROCEDUREINVOKATIONHANDLER_H +#endif // JSONRPC_CPP_IPROCEDUREINVOKATIONHANDLER_H diff --git a/src/jsonrpccpp/server/requesthandlerfactory.cpp b/src/jsonrpccpp/server/requesthandlerfactory.cpp index 16c1b5b8..bb52e864 100644 --- a/src/jsonrpccpp/server/requesthandlerfactory.cpp +++ b/src/jsonrpccpp/server/requesthandlerfactory.cpp @@ -14,8 +14,7 @@ using namespace jsonrpc; -IProtocolHandler *RequestHandlerFactory::createProtocolHandler( - serverVersion_t type, IProcedureInvokationHandler &handler) { +IProtocolHandler *RequestHandlerFactory::createProtocolHandler(serverVersion_t type, IProcedureInvokationHandler &handler) { IProtocolHandler *result = NULL; switch (type) { case JSONRPC_SERVER_V1: diff --git a/src/jsonrpccpp/server/requesthandlerfactory.h b/src/jsonrpccpp/server/requesthandlerfactory.h index 5ec50afc..11d217d6 100644 --- a/src/jsonrpccpp/server/requesthandlerfactory.h +++ b/src/jsonrpccpp/server/requesthandlerfactory.h @@ -10,18 +10,17 @@ #ifndef JSONRPC_REQUESTHANDLERFACTORY_H #define JSONRPC_REQUESTHANDLERFACTORY_H -#include "iprocedureinvokationhandler.h" #include "iclientconnectionhandler.h" +#include "iprocedureinvokationhandler.h" namespace jsonrpc { - typedef enum {JSONRPC_SERVER_V1, JSONRPC_SERVER_V2, JSONRPC_SERVER_V1V2} serverVersion_t; + typedef enum { JSONRPC_SERVER_V1, JSONRPC_SERVER_V2, JSONRPC_SERVER_V1V2 } serverVersion_t; - class RequestHandlerFactory - { - public: - static IProtocolHandler* createProtocolHandler(serverVersion_t type, IProcedureInvokationHandler& handler); - }; + class RequestHandlerFactory { + public: + static IProtocolHandler *createProtocolHandler(serverVersion_t type, IProcedureInvokationHandler &handler); + }; } // namespace jsonrpc diff --git a/src/jsonrpccpp/server/rpcprotocolserver12.cpp b/src/jsonrpccpp/server/rpcprotocolserver12.cpp index 214dcd71..fff03984 100644 --- a/src/jsonrpccpp/server/rpcprotocolserver12.cpp +++ b/src/jsonrpccpp/server/rpcprotocolserver12.cpp @@ -12,16 +12,14 @@ using namespace jsonrpc; -RpcProtocolServer12::RpcProtocolServer12(IProcedureInvokationHandler &handler) - : rpc1(handler), rpc2(handler) {} +RpcProtocolServer12::RpcProtocolServer12(IProcedureInvokationHandler &handler) : rpc1(handler), rpc2(handler) {} void RpcProtocolServer12::AddProcedure(const Procedure &procedure) { this->rpc1.AddProcedure(procedure); this->rpc2.AddProcedure(procedure); } -void RpcProtocolServer12::HandleRequest(const std::string &request, - std::string &retValue) { +void RpcProtocolServer12::HandleRequest(const std::string &request, std::string &retValue) { Json::Reader reader; Json::Value req; Json::Value resp; @@ -32,24 +30,18 @@ void RpcProtocolServer12::HandleRequest(const std::string &request, if (reader.parse(request, req, false)) { this->GetHandler(req).HandleJsonRequest(req, resp); } else { - this->GetHandler(req).WrapError( - Json::nullValue, Errors::ERROR_RPC_JSON_PARSE_ERROR, - Errors::GetErrorMessage(Errors::ERROR_RPC_JSON_PARSE_ERROR), resp); + this->GetHandler(req).WrapError(Json::nullValue, Errors::ERROR_RPC_JSON_PARSE_ERROR, Errors::GetErrorMessage(Errors::ERROR_RPC_JSON_PARSE_ERROR), resp); } } catch (const Json::Exception &e) { - this->GetHandler(req).WrapError( - Json::nullValue, Errors::ERROR_RPC_JSON_PARSE_ERROR, - Errors::GetErrorMessage(Errors::ERROR_RPC_JSON_PARSE_ERROR), resp); + this->GetHandler(req).WrapError(Json::nullValue, Errors::ERROR_RPC_JSON_PARSE_ERROR, Errors::GetErrorMessage(Errors::ERROR_RPC_JSON_PARSE_ERROR), resp); } if (resp != Json::nullValue) retValue = Json::writeString(wbuilder, resp); } -AbstractProtocolHandler & -RpcProtocolServer12::GetHandler(const Json::Value &request) { - if (request.isArray() || (request.isObject() && request.isMember("jsonrpc") && - request["jsonrpc"].asString() == "2.0")) +AbstractProtocolHandler &RpcProtocolServer12::GetHandler(const Json::Value &request) { + if (request.isArray() || (request.isObject() && request.isMember("jsonrpc") && request["jsonrpc"].asString() == "2.0")) return rpc2; return rpc1; } diff --git a/src/jsonrpccpp/server/rpcprotocolserver12.h b/src/jsonrpccpp/server/rpcprotocolserver12.h index 0779d4d7..b0a881fd 100644 --- a/src/jsonrpccpp/server/rpcprotocolserver12.h +++ b/src/jsonrpccpp/server/rpcprotocolserver12.h @@ -16,20 +16,19 @@ namespace jsonrpc { - class RpcProtocolServer12 : public IProtocolHandler - { - public: - RpcProtocolServer12(IProcedureInvokationHandler &handler); + class RpcProtocolServer12 : public IProtocolHandler { + public: + RpcProtocolServer12(IProcedureInvokationHandler &handler); - void AddProcedure(const Procedure& procedure); - void HandleRequest(const std::string& request, std::string& retValue); + void AddProcedure(const Procedure &procedure); + void HandleRequest(const std::string &request, std::string &retValue); - private: - RpcProtocolServerV1 rpc1; - RpcProtocolServerV2 rpc2; + private: + RpcProtocolServerV1 rpc1; + RpcProtocolServerV2 rpc2; - AbstractProtocolHandler& GetHandler(const Json::Value& request); - }; + AbstractProtocolHandler &GetHandler(const Json::Value &request); + }; } // namespace jsonrpc diff --git a/src/jsonrpccpp/server/rpcprotocolserverv1.cpp b/src/jsonrpccpp/server/rpcprotocolserverv1.cpp index 4ffa633d..0cabba48 100644 --- a/src/jsonrpccpp/server/rpcprotocolserverv1.cpp +++ b/src/jsonrpccpp/server/rpcprotocolserverv1.cpp @@ -13,11 +13,9 @@ using namespace jsonrpc; -RpcProtocolServerV1::RpcProtocolServerV1(IProcedureInvokationHandler &handler) - : AbstractProtocolHandler(handler) {} +RpcProtocolServerV1::RpcProtocolServerV1(IProcedureInvokationHandler &handler) : AbstractProtocolHandler(handler) {} -void RpcProtocolServerV1::HandleJsonRequest(const Json::Value &req, - Json::Value &response) { +void RpcProtocolServerV1::HandleJsonRequest(const Json::Value &req, Json::Value &response) { if (req.isObject()) { int error = this->ValidateRequest(req); if (error == 0) { @@ -30,37 +28,29 @@ void RpcProtocolServerV1::HandleJsonRequest(const Json::Value &req, this->WrapError(req, error, Errors::GetErrorMessage(error), response); } } else { - this->WrapError(Json::nullValue, Errors::ERROR_RPC_INVALID_REQUEST, - Errors::GetErrorMessage(Errors::ERROR_RPC_INVALID_REQUEST), - response); + this->WrapError(Json::nullValue, Errors::ERROR_RPC_INVALID_REQUEST, Errors::GetErrorMessage(Errors::ERROR_RPC_INVALID_REQUEST), response); } } bool RpcProtocolServerV1::ValidateRequestFields(const Json::Value &request) { - if (!(request.isMember(KEY_REQUEST_METHODNAME) && - request[KEY_REQUEST_METHODNAME].isString())) + if (!(request.isMember(KEY_REQUEST_METHODNAME) && request[KEY_REQUEST_METHODNAME].isString())) return false; if (!request.isMember(KEY_REQUEST_ID)) return false; if (!request.isMember(KEY_REQUEST_PARAMETERS)) return false; - if (!(request[KEY_REQUEST_PARAMETERS].isArray() || - request[KEY_REQUEST_PARAMETERS].isNull())) + if (!(request[KEY_REQUEST_PARAMETERS].isArray() || request[KEY_REQUEST_PARAMETERS].isNull())) return false; return true; } -void RpcProtocolServerV1::WrapResult(const Json::Value &request, - Json::Value &response, - Json::Value &retValue) { +void RpcProtocolServerV1::WrapResult(const Json::Value &request, Json::Value &response, Json::Value &retValue) { response[KEY_RESPONSE_RESULT] = retValue; response[KEY_RESPONSE_ERROR] = Json::nullValue; response[KEY_REQUEST_ID] = request[KEY_REQUEST_ID]; } -void RpcProtocolServerV1::WrapError(const Json::Value &request, int code, - const std::string &message, - Json::Value &result) { +void RpcProtocolServerV1::WrapError(const Json::Value &request, int code, const std::string &message, Json::Value &result) { result["error"]["code"] = code; result["error"]["message"] = message; result["result"] = Json::nullValue; @@ -71,9 +61,7 @@ void RpcProtocolServerV1::WrapError(const Json::Value &request, int code, } } -void RpcProtocolServerV1::WrapException(const Json::Value &request, - const JsonRpcException &exception, - Json::Value &result) { +void RpcProtocolServerV1::WrapException(const Json::Value &request, const JsonRpcException &exception, Json::Value &result) { this->WrapError(request, exception.GetCode(), exception.GetMessage(), result); result["error"]["data"] = exception.GetData(); } diff --git a/src/jsonrpccpp/server/rpcprotocolserverv1.h b/src/jsonrpccpp/server/rpcprotocolserverv1.h index 7e96c673..944eb714 100644 --- a/src/jsonrpccpp/server/rpcprotocolserverv1.h +++ b/src/jsonrpccpp/server/rpcprotocolserverv1.h @@ -10,24 +10,22 @@ #ifndef JSONRPC_CPP_RPCPROTOCOLSERVERV1_H #define JSONRPC_CPP_RPCPROTOCOLSERVERV1_H -#include #include "abstractprotocolhandler.h" +#include namespace jsonrpc { - class RpcProtocolServerV1 : public AbstractProtocolHandler - { - public: - RpcProtocolServerV1(IProcedureInvokationHandler &handler); - - bool ValidateRequestFields(const Json::Value &request); - void HandleJsonRequest(const Json::Value &request, Json::Value &response); - void WrapResult(const Json::Value& request, Json::Value& response, Json::Value& retValue); - void WrapError(const Json::Value& request, int code, const std::string &message, Json::Value& result); - void WrapException(const Json::Value& request, const JsonRpcException& exception, Json::Value& result); - procedure_t GetRequestType(const Json::Value& request); - - }; + class RpcProtocolServerV1 : public AbstractProtocolHandler { + public: + RpcProtocolServerV1(IProcedureInvokationHandler &handler); + + bool ValidateRequestFields(const Json::Value &request); + void HandleJsonRequest(const Json::Value &request, Json::Value &response); + void WrapResult(const Json::Value &request, Json::Value &response, Json::Value &retValue); + void WrapError(const Json::Value &request, int code, const std::string &message, Json::Value &result); + void WrapException(const Json::Value &request, const JsonRpcException &exception, Json::Value &result); + procedure_t GetRequestType(const Json::Value &request); + }; } // namespace jsonrpc diff --git a/src/jsonrpccpp/server/rpcprotocolserverv2.cpp b/src/jsonrpccpp/server/rpcprotocolserverv2.cpp index 72d6e131..a22cf1e9 100644 --- a/src/jsonrpccpp/server/rpcprotocolserverv2.cpp +++ b/src/jsonrpccpp/server/rpcprotocolserverv2.cpp @@ -14,11 +14,9 @@ using namespace std; using namespace jsonrpc; -RpcProtocolServerV2::RpcProtocolServerV2(IProcedureInvokationHandler &handler) - : AbstractProtocolHandler(handler) {} +RpcProtocolServerV2::RpcProtocolServerV2(IProcedureInvokationHandler &handler) : AbstractProtocolHandler(handler) {} -void RpcProtocolServerV2::HandleJsonRequest(const Json::Value &req, - Json::Value &response) { +void RpcProtocolServerV2::HandleJsonRequest(const Json::Value &req, Json::Value &response) { // It could be a Batch Request if (req.isArray()) { this->HandleBatchRequest(req, response); @@ -26,13 +24,10 @@ void RpcProtocolServerV2::HandleJsonRequest(const Json::Value &req, else if (req.isObject()) { this->HandleSingleRequest(req, response); } else { - this->WrapError(Json::nullValue, Errors::ERROR_RPC_INVALID_REQUEST, - Errors::GetErrorMessage(Errors::ERROR_RPC_INVALID_REQUEST), - response); + this->WrapError(Json::nullValue, Errors::ERROR_RPC_INVALID_REQUEST, Errors::GetErrorMessage(Errors::ERROR_RPC_INVALID_REQUEST), response); } } -void RpcProtocolServerV2::HandleSingleRequest(const Json::Value &req, - Json::Value &response) { +void RpcProtocolServerV2::HandleSingleRequest(const Json::Value &req, Json::Value &response) { int error = this->ValidateRequest(req); if (error == 0) { try { @@ -44,12 +39,9 @@ void RpcProtocolServerV2::HandleSingleRequest(const Json::Value &req, this->WrapError(req, error, Errors::GetErrorMessage(error), response); } } -void RpcProtocolServerV2::HandleBatchRequest(const Json::Value &req, - Json::Value &response) { +void RpcProtocolServerV2::HandleBatchRequest(const Json::Value &req, Json::Value &response) { if (req.empty()) - this->WrapError(Json::nullValue, Errors::ERROR_RPC_INVALID_REQUEST, - Errors::GetErrorMessage(Errors::ERROR_RPC_INVALID_REQUEST), - response); + this->WrapError(Json::nullValue, Errors::ERROR_RPC_INVALID_REQUEST, Errors::GetErrorMessage(Errors::ERROR_RPC_INVALID_REQUEST), response); else { for (unsigned int i = 0; i < req.size(); i++) { Json::Value result; @@ -62,52 +54,37 @@ void RpcProtocolServerV2::HandleBatchRequest(const Json::Value &req, bool RpcProtocolServerV2::ValidateRequestFields(const Json::Value &request) { if (!request.isObject()) return false; - if (!(request.isMember(KEY_REQUEST_METHODNAME) && - request[KEY_REQUEST_METHODNAME].isString())) + if (!(request.isMember(KEY_REQUEST_METHODNAME) && request[KEY_REQUEST_METHODNAME].isString())) return false; - if (!(request.isMember(KEY_REQUEST_VERSION) && - request[KEY_REQUEST_VERSION].isString() && - request[KEY_REQUEST_VERSION].asString() == JSON_RPC_VERSION2)) + if (!(request.isMember(KEY_REQUEST_VERSION) && request[KEY_REQUEST_VERSION].isString() && request[KEY_REQUEST_VERSION].asString() == JSON_RPC_VERSION2)) return false; - if (request.isMember(KEY_REQUEST_ID) && - !(request[KEY_REQUEST_ID].isIntegral() || - request[KEY_REQUEST_ID].isString() || request[KEY_REQUEST_ID].isNull())) + if (request.isMember(KEY_REQUEST_ID) && !(request[KEY_REQUEST_ID].isIntegral() || request[KEY_REQUEST_ID].isString() || request[KEY_REQUEST_ID].isNull())) return false; if (request.isMember(KEY_REQUEST_PARAMETERS) && - !(request[KEY_REQUEST_PARAMETERS].isObject() || - request[KEY_REQUEST_PARAMETERS].isArray() || - request[KEY_REQUEST_PARAMETERS].isNull())) + !(request[KEY_REQUEST_PARAMETERS].isObject() || request[KEY_REQUEST_PARAMETERS].isArray() || request[KEY_REQUEST_PARAMETERS].isNull())) return false; return true; } -void RpcProtocolServerV2::WrapResult(const Json::Value &request, - Json::Value &response, - Json::Value &result) { +void RpcProtocolServerV2::WrapResult(const Json::Value &request, Json::Value &response, Json::Value &result) { response[KEY_REQUEST_VERSION] = JSON_RPC_VERSION2; response[KEY_RESPONSE_RESULT] = result; response[KEY_REQUEST_ID] = request[KEY_REQUEST_ID]; } -void RpcProtocolServerV2::WrapError(const Json::Value &request, int code, - const string &message, - Json::Value &result) { +void RpcProtocolServerV2::WrapError(const Json::Value &request, int code, const string &message, Json::Value &result) { result["jsonrpc"] = "2.0"; result["error"]["code"] = code; result["error"]["message"] = message; - if (request.isObject() && request.isMember("id") && - (request["id"].isNull() || request["id"].isIntegral() || - request["id"].isString())) { + if (request.isObject() && request.isMember("id") && (request["id"].isNull() || request["id"].isIntegral() || request["id"].isString())) { result["id"] = request["id"]; } else { result["id"] = Json::nullValue; } } -void RpcProtocolServerV2::WrapException(const Json::Value &request, - const JsonRpcException &exception, - Json::Value &result) { +void RpcProtocolServerV2::WrapException(const Json::Value &request, const JsonRpcException &exception, Json::Value &result) { this->WrapError(request, exception.GetCode(), exception.GetMessage(), result); result["error"]["data"] = exception.GetData(); } diff --git a/src/jsonrpccpp/server/rpcprotocolserverv2.h b/src/jsonrpccpp/server/rpcprotocolserverv2.h index 20b421bb..6f9e1253 100644 --- a/src/jsonrpccpp/server/rpcprotocolserverv2.h +++ b/src/jsonrpccpp/server/rpcprotocolserverv2.h @@ -10,35 +10,32 @@ #ifndef JSONRPC_CPP_RPCPROTOCOLSERVERV2_H_ #define JSONRPC_CPP_RPCPROTOCOLSERVERV2_H_ +#include #include #include -#include -#include #include "abstractprotocolhandler.h" +#include - -#define KEY_REQUEST_VERSION "jsonrpc" -#define JSON_RPC_VERSION2 "2.0" - -namespace jsonrpc -{ - class RpcProtocolServerV2 : public AbstractProtocolHandler - { - public: - RpcProtocolServerV2(IProcedureInvokationHandler &handler); - - void HandleJsonRequest(const Json::Value& request, Json::Value& response); - bool ValidateRequestFields(const Json::Value &val); - void WrapResult(const Json::Value& request, Json::Value& response, Json::Value& retValue); - void WrapError(const Json::Value& request, int code, const std::string &message, Json::Value& result); - void WrapException(const Json::Value& request, const JsonRpcException &exception, Json::Value& result); - procedure_t GetRequestType(const Json::Value& request); - - private: - void HandleSingleRequest(const Json::Value& request, Json::Value& response); - void HandleBatchRequest(const Json::Value& requests, Json::Value& response); - }; +#define KEY_REQUEST_VERSION "jsonrpc" +#define JSON_RPC_VERSION2 "2.0" + +namespace jsonrpc { + class RpcProtocolServerV2 : public AbstractProtocolHandler { + public: + RpcProtocolServerV2(IProcedureInvokationHandler &handler); + + void HandleJsonRequest(const Json::Value &request, Json::Value &response); + bool ValidateRequestFields(const Json::Value &val); + void WrapResult(const Json::Value &request, Json::Value &response, Json::Value &retValue); + void WrapError(const Json::Value &request, int code, const std::string &message, Json::Value &result); + void WrapException(const Json::Value &request, const JsonRpcException &exception, Json::Value &result); + procedure_t GetRequestType(const Json::Value &request); + + private: + void HandleSingleRequest(const Json::Value &request, Json::Value &response); + void HandleBatchRequest(const Json::Value &requests, Json::Value &response); + }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_RPCPROTOCOLSERVERV2_H_ */ diff --git a/src/jsonrpccpp/server/threadpool.h b/src/jsonrpccpp/server/threadpool.h index 09dc0362..1b73941c 100644 --- a/src/jsonrpccpp/server/threadpool.h +++ b/src/jsonrpccpp/server/threadpool.h @@ -24,101 +24,88 @@ distribution. #ifndef THREAD_POOL_H #define THREAD_POOL_H -#include -#include -#include -#include -#include #include -#include #include +#include +#include +#include +#include #include +#include +#include namespace jsonrpc { -class ThreadPool { -public: + class ThreadPool { + public: ThreadPool(size_t); - template - auto enqueue(F&& f, Args&&... args) - -> std::future::type>; + template + auto enqueue(F &&f, Args &&...args) -> std::future::type>; ~ThreadPool(); -private: + + private: // need to keep track of threads so we can join them - std::vector< std::thread > workers; + std::vector workers; // the task queue - std::queue< std::function > tasks; + std::queue> tasks; // synchronization std::mutex queue_mutex; std::condition_variable condition; bool stop; -}; - -// the constructor just launches some amount of workers -inline ThreadPool::ThreadPool(size_t threads) - : stop(false) -{ - for(size_t i = 0;i task; - - { - std::unique_lock lock(this->queue_mutex); - this->condition.wait(lock, - [this]{ return this->stop || !this->tasks.empty(); }); - if(this->stop && this->tasks.empty()) - return; - task = std::move(this->tasks.front()); - this->tasks.pop(); - } - - task(); - } - } - ); -} - -// add new work item to the pool -template -auto ThreadPool::enqueue(F&& f, Args&&... args) - -> std::future::type> -{ + }; + + // the constructor just launches some amount of workers + inline ThreadPool::ThreadPool(size_t threads) : stop(false) { + for (size_t i = 0; i < threads; ++i) + workers.emplace_back([this] { + for (;;) { + std::function task; + + { + std::unique_lock lock(this->queue_mutex); + this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); }); + if (this->stop && this->tasks.empty()) + return; + task = std::move(this->tasks.front()); + this->tasks.pop(); + } + + task(); + } + }); + } + + // add new work item to the pool + template + auto ThreadPool::enqueue(F &&f, Args &&...args) -> std::future::type> { using return_type = typename std::result_of::type; - auto task = std::make_shared< std::packaged_task >( - std::bind(std::forward(f), std::forward(args)...) - ); + auto task = std::make_shared>(std::bind(std::forward(f), std::forward(args)...)); std::future res = task->get_future(); { - std::unique_lock lock(queue_mutex); + std::unique_lock lock(queue_mutex); - // don't allow enqueueing after stopping the pool - if(stop) - throw std::runtime_error("enqueue on stopped ThreadPool"); + // don't allow enqueueing after stopping the pool + if (stop) + throw std::runtime_error("enqueue on stopped ThreadPool"); - tasks.emplace([task](){ (*task)(); }); + tasks.emplace([task]() { (*task)(); }); } condition.notify_one(); return res; -} + } -// the destructor joins all threads -inline ThreadPool::~ThreadPool() -{ + // the destructor joins all threads + inline ThreadPool::~ThreadPool() { { - std::unique_lock lock(queue_mutex); - stop = true; + std::unique_lock lock(queue_mutex); + stop = true; } condition.notify_all(); - for(std::thread &worker: workers) - worker.join(); -} -} - + for (std::thread &worker : workers) + worker.join(); + } +} // namespace jsonrpc #endif diff --git a/src/stubgenerator/CMakeLists.txt b/src/stubgenerator/CMakeLists.txt index 155e892d..9b16cb7e 100644 --- a/src/stubgenerator/CMakeLists.txt +++ b/src/stubgenerator/CMakeLists.txt @@ -9,54 +9,54 @@ set(ALL_LIBS) if (BUILD_SHARED_LIBS) - add_library(libjsonrpcstub SHARED ${jsonrpcstub_source} ${jsonrpcstub_header} ${jsonrpc_helper_source_common}) - target_link_libraries(libjsonrpcstub jsonrpccommon ${ARGTABLE_LIBRARIES}) - set_target_properties(libjsonrpcstub PROPERTIES OUTPUT_NAME jsonrpccpp-stub) - list(APPEND ALL_LIBS libjsonrpcstub) -endif() + add_library(libjsonrpcstub SHARED ${jsonrpcstub_source} ${jsonrpcstub_header} ${jsonrpc_helper_source_common}) + target_link_libraries(libjsonrpcstub jsonrpccommon ${ARGTABLE_LIBRARIES}) + set_target_properties(libjsonrpcstub PROPERTIES OUTPUT_NAME jsonrpccpp-stub) + list(APPEND ALL_LIBS libjsonrpcstub) +endif () # setup static common library if (BUILD_STATIC_LIBS OR MSVC) - add_library(libjsonrpcstubStatic STATIC ${jsonrpcstub_source} ${jsonrpcstub_header} ${jsonrpc_helper_source_common}) - target_link_libraries(libjsonrpcstubStatic common ${ARGTABLE_LIBRARIES}) - set_target_properties(libjsonrpcstubStatic PROPERTIES OUTPUT_NAME jsonrpccpp-stub) + add_library(libjsonrpcstubStatic STATIC ${jsonrpcstub_source} ${jsonrpcstub_header} ${jsonrpc_helper_source_common}) + target_link_libraries(libjsonrpcstubStatic common ${ARGTABLE_LIBRARIES}) + set_target_properties(libjsonrpcstubStatic PROPERTIES OUTPUT_NAME jsonrpccpp-stub) if (NOT BUILD_SHARED_LIBS) add_library(libjsonrpcstub ALIAS libjsonrpcstubStatic) - endif() + endif () list(APPEND ALL_LIBS libjsonrpcstubStatic) -endif() +endif () set(VERSION_STRING ${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_VERSION}) set_target_properties(${ALL_LIBS} PROPERTIES VERSION "${VERSION_STRING}" SOVERSION "${SO_VERSION}") add_executable(jsonrpcstub main.cpp) if (BUILD_STATIC_LIBS AND NOT BUILD_SHARED_LIBS) - target_link_libraries(jsonrpcstub common libjsonrpcstubStatic ) -else() - target_link_libraries(jsonrpcstub jsonrpccommon libjsonrpcstub ) -endif() + target_link_libraries(jsonrpcstub common libjsonrpcstubStatic) +else () + target_link_libraries(jsonrpcstub jsonrpccommon libjsonrpcstub) +endif () #Generate manpage if (NOT ${CMAKE_SYSTEM_NAME} STREQUAL "Windows") configure_file("${CMAKE_SOURCE_DIR}/doc/manpage.in" "${CMAKE_BINARY_DIR}/jsonrpcstub.1" @ONLY) add_custom_target(manpage ALL DEPENDS ${CMAKE_BINARY_DIR}/jsonrpcstub.1) install(FILES ${CMAKE_BINARY_DIR}/jsonrpcstub.1 DESTINATION ${CMAKE_INSTALL_MANDIR}/man1/) add_dependencies(jsonrpcstub manpage) -endif() +endif () configure_file(${CMAKE_SOURCE_DIR}/cmake/libjsonrpccpp-stub.pc.cmake ${CMAKE_BINARY_DIR}/libjsonrpccpp-stub.pc) install(FILES - "${CMAKE_BINARY_DIR}/libjsonrpccpp-stub.pc" - DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") + "${CMAKE_BINARY_DIR}/libjsonrpccpp-stub.pc" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") install(DIRECTORY ${CMAKE_SOURCE_DIR}/src/stubgenerator/ - DESTINATION include/jsonrpccpp/stubgen - FILES_MATCHING PATTERN "*.h") + DESTINATION include/jsonrpccpp/stubgen + FILES_MATCHING PATTERN "*.h") install(TARGETS ${ALL_LIBS} jsonrpcstub - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - RUNTIME DESTINATION bin -) + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION bin + ) diff --git a/src/stubgenerator/client/cppclientstubgenerator.cpp b/src/stubgenerator/client/cppclientstubgenerator.cpp index f4fa8527..71f3dddb 100644 --- a/src/stubgenerator/client/cppclientstubgenerator.cpp +++ b/src/stubgenerator/client/cppclientstubgenerator.cpp @@ -12,8 +12,8 @@ #define TEMPLATE_CPPCLIENT_SIGCLASS "class : public jsonrpc::Client" -#define TEMPLATE_CPPCLIENT_SIGCONSTRUCTOR \ - "(jsonrpc::IClientConnector &conn, jsonrpc::clientVersion_t type " \ +#define TEMPLATE_CPPCLIENT_SIGCONSTRUCTOR \ + "(jsonrpc::IClientConnector &conn, jsonrpc::clientVersion_t type " \ "= jsonrpc::JSONRPC_CLIENT_V2) : jsonrpc::Client(conn, type) {}" #define TEMPLATE_CPPCLIENT_SIGMETHOD " () " @@ -21,8 +21,7 @@ #define TEMPLATE_NAMED_ASSIGNMENT "p[\"\"] = ;" #define TEMPLATE_POSITION_ASSIGNMENT "p.append();" -#define TEMPLATE_METHODCALL \ - "Json::Value result = this->CallMethod(\"\",p);" +#define TEMPLATE_METHODCALL "Json::Value result = this->CallMethod(\"\",p);" #define TEMPLATE_NOTIFICATIONCALL "this->CallNotification(\"\",p);" #define TEMPLATE_RETURNCHECK "if (result)" @@ -31,14 +30,10 @@ using namespace std; using namespace jsonrpc; -CPPClientStubGenerator::CPPClientStubGenerator( - const string &stubname, std::vector &procedures, - std::ostream &outputstream) +CPPClientStubGenerator::CPPClientStubGenerator(const string &stubname, std::vector &procedures, std::ostream &outputstream) : StubGenerator(stubname, procedures, outputstream) {} -CPPClientStubGenerator::CPPClientStubGenerator( - const string &stubname, std::vector &procedures, - const string filename) +CPPClientStubGenerator::CPPClientStubGenerator(const string &stubname, std::vector &procedures, const string filename) : StubGenerator(stubname, procedures, filename) {} void CPPClientStubGenerator::generateStub() { @@ -49,15 +44,13 @@ void CPPClientStubGenerator::generateStub() { int depth = CPPHelper::namespaceOpen(*this, stubname); - this->writeLine(replaceAll(TEMPLATE_CPPCLIENT_SIGCLASS, "", - classname.at(classname.size() - 1))); + this->writeLine(replaceAll(TEMPLATE_CPPCLIENT_SIGCLASS, "", classname.at(classname.size() - 1))); this->writeLine("{"); this->increaseIndentation(); this->writeLine("public:"); this->increaseIndentation(); - this->writeLine(replaceAll(TEMPLATE_CPPCLIENT_SIGCONSTRUCTOR, "", - classname.at(classname.size() - 1))); + this->writeLine(replaceAll(TEMPLATE_CPPCLIENT_SIGCONSTRUCTOR, "", classname.at(classname.size() - 1))); this->writeNewLine(); for (unsigned int i = 0; i < procedures.size(); i++) { @@ -80,10 +73,8 @@ void CPPClientStubGenerator::generateMethod(Procedure &proc) { returntype = "void"; replaceAll2(procsignature, "", returntype); - replaceAll2(procsignature, "", - CPPHelper::normalizeString(proc.GetProcedureName())); - replaceAll2(procsignature, "", - CPPHelper::generateParameterDeclarationList(proc)); + replaceAll2(procsignature, "", CPPHelper::normalizeString(proc.GetProcedureName())); + replaceAll2(procsignature, "", CPPHelper::generateParameterDeclarationList(proc)); this->writeLine(procsignature); this->writeLine("{"); @@ -102,8 +93,7 @@ void CPPClientStubGenerator::generateAssignments(Procedure &proc) { string assignment; parameterNameList_t list = proc.GetParameters(); if (!list.empty()) { - for (parameterNameList_t::iterator it = list.begin(); it != list.end(); - ++it) { + for (parameterNameList_t::iterator it = list.begin(); it != list.end(); ++it) { if (proc.GetParameterDeclarationType() == PARAMS_BY_NAME) { assignment = TEMPLATE_NAMED_ASSIGNMENT; @@ -124,13 +114,11 @@ void CPPClientStubGenerator::generateProcCall(Procedure &proc) { call = TEMPLATE_METHODCALL; this->writeLine(replaceAll(call, "", proc.GetProcedureName())); call = TEMPLATE_RETURNCHECK; - replaceAll2(call, "", - CPPHelper::isCppConversion(proc.GetReturnType())); + replaceAll2(call, "", CPPHelper::isCppConversion(proc.GetReturnType())); this->writeLine(call); this->increaseIndentation(); call = TEMPLATE_RETURN; - replaceAll2(call, "", - CPPHelper::toCppConversion(proc.GetReturnType())); + replaceAll2(call, "", CPPHelper::toCppConversion(proc.GetReturnType())); this->writeLine(call); this->decreaseIndentation(); this->writeLine("else"); diff --git a/src/stubgenerator/client/cppclientstubgenerator.h b/src/stubgenerator/client/cppclientstubgenerator.h index c480c258..38261356 100644 --- a/src/stubgenerator/client/cppclientstubgenerator.h +++ b/src/stubgenerator/client/cppclientstubgenerator.h @@ -10,24 +10,20 @@ #ifndef JSONRPC_CPP_CLIENTSTUBGENERATOR_H #define JSONRPC_CPP_CLIENTSTUBGENERATOR_H -#include "../stubgenerator.h" #include "../codegenerator.h" +#include "../stubgenerator.h" -namespace jsonrpc -{ - class CPPClientStubGenerator : public StubGenerator - { - public: - - - CPPClientStubGenerator(const std::string& stubname, std::vector &procedures, std::ostream& outputstream); - CPPClientStubGenerator(const std::string& stubname, std::vector &procedures, const std::string filename); +namespace jsonrpc { + class CPPClientStubGenerator : public StubGenerator { + public: + CPPClientStubGenerator(const std::string &stubname, std::vector &procedures, std::ostream &outputstream); + CPPClientStubGenerator(const std::string &stubname, std::vector &procedures, const std::string filename); - virtual void generateStub(); + virtual void generateStub(); - void generateMethod(Procedure& proc); - void generateAssignments(Procedure& proc); - void generateProcCall(Procedure &proc); - }; -} + void generateMethod(Procedure &proc); + void generateAssignments(Procedure &proc); + void generateProcCall(Procedure &proc); + }; +} // namespace jsonrpc #endif // JSONRPC_CPP_CLIENTSTUBGENERATOR_H diff --git a/src/stubgenerator/client/jsclientstubgenerator.cpp b/src/stubgenerator/client/jsclientstubgenerator.cpp index 5e3b0fcf..0dede045 100644 --- a/src/stubgenerator/client/jsclientstubgenerator.cpp +++ b/src/stubgenerator/client/jsclientstubgenerator.cpp @@ -13,7 +13,7 @@ using namespace jsonrpc; using namespace std; -#define TEMPLATE_JS_PROLOG \ +#define TEMPLATE_JS_PROLOG \ "function (url) {\n\ this.url = url;\n\ var id = 1;\n\ @@ -59,27 +59,23 @@ using namespace std; }\n\ }\n" -#define TEMPLATE_JS_METHOD \ - ".prototype. = function(callbackSuccess, " \ +#define TEMPLATE_JS_METHOD \ + ".prototype. = function(callbackSuccess, " \ "callbackError) {" #define TEMPLATE_JS_PARAM_NAMED "var params = {};" #define TEMPLATE_JS_PARAM_POSITIONAL "var params = [];" #define TEMPLATE_JS_PARAM_EMPTY "var params = null;" -#define TEMPLATE_JS_CALL_METHOD \ - "return this.doRPC(\"\", params, true, callbackSuccess, " \ +#define TEMPLATE_JS_CALL_METHOD \ + "return this.doRPC(\"\", params, true, callbackSuccess, " \ "callbackError);" -#define TEMPLATE_JS_CALL_NOTIFICATION \ - "this.doRPC(\"\", params, false, callbackSuccess, " \ +#define TEMPLATE_JS_CALL_NOTIFICATION \ + "this.doRPC(\"\", params, false, callbackSuccess, " \ "callbackError);" -JSClientStubGenerator::JSClientStubGenerator(const string &stubname, - std::vector &procedures, - ostream &outputstream) +JSClientStubGenerator::JSClientStubGenerator(const string &stubname, std::vector &procedures, ostream &outputstream) : StubGenerator(stubname, procedures, outputstream) {} -JSClientStubGenerator::JSClientStubGenerator(const string &stubname, - std::vector &procedures, - const string &filename) +JSClientStubGenerator::JSClientStubGenerator(const string &stubname, std::vector &procedures, const string &filename) : StubGenerator(stubname, procedures, filename) {} string JSClientStubGenerator::class2Filename(const string &classname) { @@ -90,8 +86,7 @@ string JSClientStubGenerator::class2Filename(const string &classname) { void JSClientStubGenerator::generateStub() { this->writeLine("/**"); - this->writeLine( - " * This file is generated by jsonrpcstub, DO NOT CHANGE IT MANUALLY!"); + this->writeLine(" * This file is generated by jsonrpcstub, DO NOT CHANGE IT MANUALLY!"); this->writeLine(" */"); this->write(replaceAll(TEMPLATE_JS_PROLOG, "", stubname)); this->writeNewLine(); @@ -104,8 +99,7 @@ void JSClientStubGenerator::generateStub() { void JSClientStubGenerator::generateMethod(Procedure &proc) { string method = TEMPLATE_JS_METHOD; replaceAll2(method, "", stubname); - replaceAll2(method, "", - noramlizeJsLiteral(proc.GetProcedureName())); + replaceAll2(method, "", noramlizeJsLiteral(proc.GetProcedureName())); stringstream param_string; stringstream params_assignment; @@ -160,9 +154,8 @@ void JSClientStubGenerator::generateMethod(Procedure &proc) { string JSClientStubGenerator::noramlizeJsLiteral(const string &literal) { string result = literal; for (unsigned int i = 0; i < literal.length(); i++) { - if (!((literal[i] >= 'a' && literal[i] <= 'z') || - (literal[i] >= 'A' && literal[i] <= 'Z') || - (literal[i] >= '0' && literal[i] <= '9') || literal[i] == '_')) { + if (!((literal[i] >= 'a' && literal[i] <= 'z') || (literal[i] >= 'A' && literal[i] <= 'Z') || (literal[i] >= '0' && literal[i] <= '9') || + literal[i] == '_')) { result[i] = '_'; } } diff --git a/src/stubgenerator/client/jsclientstubgenerator.h b/src/stubgenerator/client/jsclientstubgenerator.h index bd8e9f59..b129a4b3 100644 --- a/src/stubgenerator/client/jsclientstubgenerator.h +++ b/src/stubgenerator/client/jsclientstubgenerator.h @@ -14,21 +14,19 @@ namespace jsonrpc { - class JSClientStubGenerator : public StubGenerator - { - public: - JSClientStubGenerator(const std::string& stubname, std::vector &procedures, std::ostream &outputstream); - JSClientStubGenerator(const std::string& stubname, std::vector &procedures, const std::string &filename); + class JSClientStubGenerator : public StubGenerator { + public: + JSClientStubGenerator(const std::string &stubname, std::vector &procedures, std::ostream &outputstream); + JSClientStubGenerator(const std::string &stubname, std::vector &procedures, const std::string &filename); - static std::string class2Filename(const std::string &classname); + static std::string class2Filename(const std::string &classname); - virtual void generateStub(); + virtual void generateStub(); - private: - virtual void generateMethod(Procedure &proc); - static std::string noramlizeJsLiteral(const std::string &literal); - - }; + private: + virtual void generateMethod(Procedure &proc); + static std::string noramlizeJsLiteral(const std::string &literal); + }; } // namespace jsonrpc diff --git a/src/stubgenerator/client/pyclientstubgenerator.cpp b/src/stubgenerator/client/pyclientstubgenerator.cpp index 9a825aee..5a1d7331 100644 --- a/src/stubgenerator/client/pyclientstubgenerator.cpp +++ b/src/stubgenerator/client/pyclientstubgenerator.cpp @@ -3,8 +3,8 @@ #define TEMPLATE_PYTHON_CLIENT_SIGCLASS "class (client.Client):" -#define TEMPLATE_PYTHON_CLIENT_SIGCONSTRUCTOR \ - "def __init__(self, connector, version='2.0'):\n super(, " \ +#define TEMPLATE_PYTHON_CLIENT_SIGCONSTRUCTOR \ + "def __init__(self, connector, version='2.0'):\n super(, " \ "self).__init__(connector, version)" #define TEMPLATE_PYTHON_CLIENT_SIGMETHOD "def (self):" @@ -13,26 +13,20 @@ #define TEMPLATE_POSITION_ASSIGNMENT "parameters.append()" #define TEMPLATE_METHODCALL "result = self.call_method(\'\', parameters)" -#define TEMPLATE_NOTIFICATIONCALL \ - "self.call_notification(\'\', parameters)" +#define TEMPLATE_NOTIFICATIONCALL "self.call_notification(\'\', parameters)" using namespace std; using namespace jsonrpc; -PythonClientStubGenerator::PythonClientStubGenerator( - const string &stubname, std::vector &procedures, - std::ostream &outputstream) +PythonClientStubGenerator::PythonClientStubGenerator(const string &stubname, std::vector &procedures, std::ostream &outputstream) : StubGenerator(stubname, procedures, outputstream) {} -PythonClientStubGenerator::PythonClientStubGenerator( - const string &stubname, std::vector &procedures, - const string filename) +PythonClientStubGenerator::PythonClientStubGenerator(const string &stubname, std::vector &procedures, const string filename) : StubGenerator(stubname, procedures, filename) {} void PythonClientStubGenerator::generateStub() { this->writeLine("#"); - this->writeLine( - "# This file is generated by jsonrpcstub, DO NOT CHANGE IT MANUALLY!"); + this->writeLine("# This file is generated by jsonrpcstub, DO NOT CHANGE IT MANUALLY!"); this->writeLine("#"); this->writeNewLine(); this->writeLine("#"); @@ -43,12 +37,10 @@ void PythonClientStubGenerator::generateStub() { this->writeLine("from jsonrpc_pyclient import client"); this->writeNewLine(); - this->writeLine(replaceAll(TEMPLATE_PYTHON_CLIENT_SIGCLASS, "", - this->stubname)); + this->writeLine(replaceAll(TEMPLATE_PYTHON_CLIENT_SIGCLASS, "", this->stubname)); this->increaseIndentation(); - this->writeLine(replaceAll(TEMPLATE_PYTHON_CLIENT_SIGCONSTRUCTOR, - "", this->stubname)); + this->writeLine(replaceAll(TEMPLATE_PYTHON_CLIENT_SIGCONSTRUCTOR, "", this->stubname)); this->writeNewLine(); for (unsigned int i = 0; i < procedures.size(); i++) { @@ -61,8 +53,7 @@ void PythonClientStubGenerator::generateStub() { void PythonClientStubGenerator::generateMethod(Procedure &proc) { string procsignature = TEMPLATE_PYTHON_CLIENT_SIGMETHOD; - replaceAll2(procsignature, "", - normalizeString(proc.GetProcedureName())); + replaceAll2(procsignature, "", normalizeString(proc.GetProcedureName())); // generate parameters string string params = generateParameterDeclarationList(proc); @@ -79,13 +70,11 @@ void PythonClientStubGenerator::generateMethod(Procedure &proc) { this->decreaseIndentation(); } -string -PythonClientStubGenerator::generateParameterDeclarationList(Procedure &proc) { +string PythonClientStubGenerator::generateParameterDeclarationList(Procedure &proc) { stringstream param_string; parameterNameList_t list = proc.GetParameters(); - for (parameterNameList_t::iterator it = list.begin(); it != list.end(); - ++it) { + for (parameterNameList_t::iterator it = list.begin(); it != list.end(); ++it) { param_string << ", "; param_string << it->first; } @@ -104,8 +93,7 @@ void PythonClientStubGenerator::generateAssignments(Procedure &proc) { this->writeLine("parameters = []"); } - for (parameterNameList_t::iterator it = list.begin(); it != list.end(); - ++it) { + for (parameterNameList_t::iterator it = list.begin(); it != list.end(); ++it) { if (declType == PARAMS_BY_NAME) { assignment = TEMPLATE_NAMED_ASSIGNMENT; @@ -142,9 +130,7 @@ string PythonClientStubGenerator::class2Filename(const string &classname) { string PythonClientStubGenerator::normalizeString(const string &text) { string result = text; for (unsigned int i = 0; i < text.length(); i++) { - if (!((text[i] >= 'a' && text[i] <= 'z') || - (text[i] >= 'A' && text[i] <= 'Z') || - (text[i] >= '0' && text[i] <= '9') || text[i] == '_')) { + if (!((text[i] >= 'a' && text[i] <= 'z') || (text[i] >= 'A' && text[i] <= 'Z') || (text[i] >= '0' && text[i] <= '9') || text[i] == '_')) { result[i] = '_'; } } diff --git a/src/stubgenerator/client/pyclientstubgenerator.h b/src/stubgenerator/client/pyclientstubgenerator.h index e3a365ce..89cbd42e 100644 --- a/src/stubgenerator/client/pyclientstubgenerator.h +++ b/src/stubgenerator/client/pyclientstubgenerator.h @@ -3,29 +3,25 @@ #include "../stubgenerator.h" -namespace jsonrpc -{ - /** - * The stub client this class generates requires jsonrpc_pyclient - * to be installed from pypi. - * https://github.com/tvannoy/jsonrpc_pyclient - */ - class PythonClientStubGenerator : public StubGenerator - { - public: +namespace jsonrpc { + /** + * The stub client this class generates requires jsonrpc_pyclient + * to be installed from pypi. + * https://github.com/tvannoy/jsonrpc_pyclient + */ + class PythonClientStubGenerator : public StubGenerator { + public: + PythonClientStubGenerator(const std::string &stubname, std::vector &procedures, std::ostream &outputstream); + PythonClientStubGenerator(const std::string &stubname, std::vector &procedures, const std::string filename); + virtual void generateStub(); - PythonClientStubGenerator(const std::string& stubname, std::vector &procedures, std::ostream& outputstream); - PythonClientStubGenerator(const std::string& stubname, std::vector &procedures, const std::string filename); - - virtual void generateStub(); - - void generateMethod(Procedure& proc); - void generateAssignments(Procedure& proc); - void generateProcCall(Procedure &proc); - std::string generateParameterDeclarationList(Procedure &proc); - static std::string class2Filename(const std::string &classname); - static std::string normalizeString(const std::string &text); - }; -} + void generateMethod(Procedure &proc); + void generateAssignments(Procedure &proc); + void generateProcCall(Procedure &proc); + std::string generateParameterDeclarationList(Procedure &proc); + static std::string class2Filename(const std::string &classname); + static std::string normalizeString(const std::string &text); + }; +} // namespace jsonrpc #endif // PYTHON_CLIENT_STUB_GENERATOR_H diff --git a/src/stubgenerator/codegenerator.cpp b/src/stubgenerator/codegenerator.cpp index 106b69a3..b0a3b490 100644 --- a/src/stubgenerator/codegenerator.cpp +++ b/src/stubgenerator/codegenerator.cpp @@ -12,16 +12,13 @@ using namespace jsonrpc; using namespace std; -CodeGenerator::CodeGenerator(const ::string &filename) - : indentation(0), atBeginning(true) { +CodeGenerator::CodeGenerator(const ::string &filename) : indentation(0), atBeginning(true) { this->file.open(filename.c_str()); this->output = &this->file; this->indentSymbol = " "; } -CodeGenerator::CodeGenerator(::ostream &outputstream) - : output(&outputstream), indentSymbol(" "), indentation(0), - atBeginning(true) {} +CodeGenerator::CodeGenerator(::ostream &outputstream) : output(&outputstream), indentSymbol(" "), indentation(0), atBeginning(true) {} CodeGenerator::~CodeGenerator() { this->output->flush(); @@ -53,6 +50,4 @@ void CodeGenerator::increaseIndentation() { this->indentation++; } void CodeGenerator::decreaseIndentation() { this->indentation--; } -void CodeGenerator::setIndentSymbol(const ::string &symbol) { - this->indentSymbol = symbol; -} +void CodeGenerator::setIndentSymbol(const ::string &symbol) { this->indentSymbol = symbol; } diff --git a/src/stubgenerator/codegenerator.h b/src/stubgenerator/codegenerator.h index ed7e4f42..4cf53b6d 100644 --- a/src/stubgenerator/codegenerator.h +++ b/src/stubgenerator/codegenerator.h @@ -10,35 +10,33 @@ #ifndef JSONRPC_CPP_CODEGENERATOR_H #define JSONRPC_CPP_CODEGENERATOR_H -#include -#include #include +#include #include +#include -namespace jsonrpc -{ - class CodeGenerator - { - public: - CodeGenerator(const std::string &filename); - CodeGenerator(std::ostream &outputstream); - virtual ~CodeGenerator(); +namespace jsonrpc { + class CodeGenerator { + public: + CodeGenerator(const std::string &filename); + CodeGenerator(std::ostream &outputstream); + virtual ~CodeGenerator(); - void write (const std::string &line); - void writeLine(const std::string &line); - void writeNewLine(); - void increaseIndentation(); - void decreaseIndentation(); + void write(const std::string &line); + void writeLine(const std::string &line); + void writeNewLine(); + void increaseIndentation(); + void decreaseIndentation(); - void setIndentSymbol(const std::string &symbol); + void setIndentSymbol(const std::string &symbol); - private: - std::ostream *output; - std::ofstream file; - std::string indentSymbol; - int indentation; - bool atBeginning; - }; -} + private: + std::ostream *output; + std::ofstream file; + std::string indentSymbol; + int indentation; + bool atBeginning; + }; +} // namespace jsonrpc #endif // JSONRPC_CPP_CODEGENERATOR_H diff --git a/src/stubgenerator/helper/cpphelper.cpp b/src/stubgenerator/helper/cpphelper.cpp index c8bd5bd2..0ae9dda4 100644 --- a/src/stubgenerator/helper/cpphelper.cpp +++ b/src/stubgenerator/helper/cpphelper.cpp @@ -113,9 +113,7 @@ string CPPHelper::generateParameterDeclarationList(Procedure &proc) { return param_string.str(); } -string CPPHelper::toCppReturntype(jsontype_t type) { - return toCppType(type, false, false); -} +string CPPHelper::toCppReturntype(jsontype_t type) { return toCppType(type, false, false); } string CPPHelper::toCppParamType(jsontype_t type) { if (type == JSON_ARRAY || type == JSON_OBJECT || type == JSON_STRING) @@ -146,30 +144,24 @@ std::vector CPPHelper::splitPackages(const string &classname) { void CPPHelper::prolog(CodeGenerator &cg, const string &stubname) { cg.writeLine("/**"); - cg.writeLine( - " * This file is generated by jsonrpcstub, DO NOT CHANGE IT MANUALLY!"); + cg.writeLine(" * This file is generated by jsonrpcstub, DO NOT CHANGE IT MANUALLY!"); cg.writeLine(" */"); cg.writeNewLine(); string stub_upper = stubname; - std::transform(stub_upper.begin(), stub_upper.end(), stub_upper.begin(), - ::toupper); + std::transform(stub_upper.begin(), stub_upper.end(), stub_upper.begin(), ::toupper); StubGenerator::replaceAll2(stub_upper, "::", "_"); - cg.writeLine(StubGenerator::replaceAll(TEMPLATE_CPPSERVER_GUARD1, - "", stub_upper)); - cg.writeLine(StubGenerator::replaceAll(TEMPLATE_CPPSERVER_GUARD2, - "", stub_upper)); + cg.writeLine(StubGenerator::replaceAll(TEMPLATE_CPPSERVER_GUARD1, "", stub_upper)); + cg.writeLine(StubGenerator::replaceAll(TEMPLATE_CPPSERVER_GUARD2, "", stub_upper)); cg.writeNewLine(); } void CPPHelper::epilog(CodeGenerator &cg, const string &stubname) { string stub_upper = stubname; - std::transform(stub_upper.begin(), stub_upper.end(), stub_upper.begin(), - ::toupper); + std::transform(stub_upper.begin(), stub_upper.end(), stub_upper.begin(), ::toupper); StubGenerator::replaceAll2(stub_upper, "::", "_"); - cg.writeLine( - StubGenerator::replaceAll(TEMPLATE_EPILOG, "", stub_upper)); + cg.writeLine(StubGenerator::replaceAll(TEMPLATE_EPILOG, "", stub_upper)); } int CPPHelper::namespaceOpen(CodeGenerator &cg, const string &classname) { @@ -194,9 +186,7 @@ void CPPHelper::namespaceClose(CodeGenerator &cg, int depth) { string CPPHelper::normalizeString(const string &text) { string result = text; for (unsigned int i = 0; i < text.length(); i++) { - if (!((text[i] >= 'a' && text[i] <= 'z') || - (text[i] >= 'A' && text[i] <= 'Z') || - (text[i] >= '0' && text[i] <= '9') || text[i] == '_')) { + if (!((text[i] >= 'a' && text[i] <= 'z') || (text[i] >= 'A' && text[i] <= 'Z') || (text[i] >= '0' && text[i] <= '9') || text[i] == '_')) { result[i] = '_'; } } diff --git a/src/stubgenerator/helper/cpphelper.h b/src/stubgenerator/helper/cpphelper.h index 48b7c3cb..535e286c 100644 --- a/src/stubgenerator/helper/cpphelper.h +++ b/src/stubgenerator/helper/cpphelper.h @@ -10,36 +10,33 @@ #ifndef JSONRPC_CPP_CPPHELPER_H #define JSONRPC_CPP_CPPHELPER_H +#include "../codegenerator.h" +#include #include #include -#include -#include "../codegenerator.h" - -namespace jsonrpc -{ - class CPPHelper - { - public: - static std::string normalizeString (const std::string &text); - static std::string toCppType (jsontype_t type, bool isConst = false, bool isReference = false); - static std::string toCppConversion (jsontype_t); - static std::string isCppConversion(jsontype_t); - static std::string toString (jsontype_t type); - static std::string generateParameterDeclarationList(Procedure& proc); - - static std::string toCppReturntype (jsontype_t type); - static std::string toCppParamType (jsontype_t type); - - static std::string class2Filename(const std::string &classname); - static std::vector splitPackages(const std::string &classname); - - static void prolog(CodeGenerator &cg, const std::string &stubname); - static void epilog(CodeGenerator &cg, const std::string &stubname); - - static int namespaceOpen(CodeGenerator &cg, const std::string &classname); - static void namespaceClose(CodeGenerator &cg, int depth); - }; -} +namespace jsonrpc { + class CPPHelper { + public: + static std::string normalizeString(const std::string &text); + static std::string toCppType(jsontype_t type, bool isConst = false, bool isReference = false); + static std::string toCppConversion(jsontype_t); + static std::string isCppConversion(jsontype_t); + static std::string toString(jsontype_t type); + static std::string generateParameterDeclarationList(Procedure &proc); + + static std::string toCppReturntype(jsontype_t type); + static std::string toCppParamType(jsontype_t type); + + static std::string class2Filename(const std::string &classname); + static std::vector splitPackages(const std::string &classname); + + static void prolog(CodeGenerator &cg, const std::string &stubname); + static void epilog(CodeGenerator &cg, const std::string &stubname); + + static int namespaceOpen(CodeGenerator &cg, const std::string &classname); + static void namespaceClose(CodeGenerator &cg, int depth); + }; +} // namespace jsonrpc #endif // JSONRPC_CPP_CPPSTUBGENERATOR_H diff --git a/src/stubgenerator/main.cpp b/src/stubgenerator/main.cpp index 7acc2092..ed5de256 100644 --- a/src/stubgenerator/main.cpp +++ b/src/stubgenerator/main.cpp @@ -19,8 +19,7 @@ int main(int argc, char **argv) { vector stubgens; vector procedures; - bool result = StubGeneratorFactory::createStubGenerators( - argc, argv, procedures, stubgens, stdout, stderr); + bool result = StubGeneratorFactory::createStubGenerators(argc, argv, procedures, stubgens, stdout, stderr); for (unsigned int i = 0; i < stubgens.size(); ++i) { stubgens[i]->generateStub(); diff --git a/src/stubgenerator/server/cppserverstubgenerator.cpp b/src/stubgenerator/server/cppserverstubgenerator.cpp index 667dbed8..2666a0a5 100644 --- a/src/stubgenerator/server/cppserverstubgenerator.cpp +++ b/src/stubgenerator/server/cppserverstubgenerator.cpp @@ -14,46 +14,38 @@ #include #include -#define TEMPLATE_CPPSERVER_METHODBINDING \ - "this->bindAndAddMethod(jsonrpc::Procedure(\"\", " \ - ", , NULL), " \ +#define TEMPLATE_CPPSERVER_METHODBINDING \ + "this->bindAndAddMethod(jsonrpc::Procedure(\"\", " \ + ", , NULL), " \ "&::I);" -#define TEMPLATE_CPPSERVER_NOTIFICATIONBINDING \ - "this->bindAndAddNotification(jsonrpc::Procedure(\"\", " \ +#define TEMPLATE_CPPSERVER_NOTIFICATIONBINDING \ + "this->bindAndAddNotification(jsonrpc::Procedure(\"\", " \ ", NULL), &::I);" -#define TEMPLATE_CPPSERVER_SIGCLASS \ - "class : public jsonrpc::AbstractServer<>" -#define TEMPLATE_CPPSERVER_SIGCONSTRUCTOR \ - "(jsonrpc::AbstractServerConnector &conn, " \ - "jsonrpc::serverVersion_t type = jsonrpc::JSONRPC_SERVER_V2) : " \ +#define TEMPLATE_CPPSERVER_SIGCLASS "class : public jsonrpc::AbstractServer<>" +#define TEMPLATE_CPPSERVER_SIGCONSTRUCTOR \ + "(jsonrpc::AbstractServerConnector &conn, " \ + "jsonrpc::serverVersion_t type = jsonrpc::JSONRPC_SERVER_V2) : " \ "jsonrpc::AbstractServer<>(conn, type)" -#define TEMPLATE_CPPSERVER_SIGMETHOD \ - "inline virtual void I(const Json::Value &request, " \ +#define TEMPLATE_CPPSERVER_SIGMETHOD \ + "inline virtual void I(const Json::Value &request, " \ "Json::Value &response)" -#define TEMPLATE_CPPSERVER_SIGMETHOD_WITHOUT_PARAMS \ - "inline virtual void I(const Json::Value &/*request*/, " \ +#define TEMPLATE_CPPSERVER_SIGMETHOD_WITHOUT_PARAMS \ + "inline virtual void I(const Json::Value &/*request*/, " \ "Json::Value &response)" -#define TEMPLATE_CPPSERVER_SIGNOTIFICATION \ - "inline virtual void I(const Json::Value &request)" -#define TEMPLATE_CPPSERVER_SIGNOTIFICATION_WITHOUT_PARAMS \ - "inline virtual void I(const Json::Value &/*request*/)" +#define TEMPLATE_CPPSERVER_SIGNOTIFICATION "inline virtual void I(const Json::Value &request)" +#define TEMPLATE_CPPSERVER_SIGNOTIFICATION_WITHOUT_PARAMS "inline virtual void I(const Json::Value &/*request*/)" -#define TEMPLATE_SERVER_ABSTRACTDEFINITION \ - "virtual () = 0;" +#define TEMPLATE_SERVER_ABSTRACTDEFINITION "virtual () = 0;" using namespace std; using namespace jsonrpc; -CPPServerStubGenerator::CPPServerStubGenerator(const std::string &stubname, - vector &procedures, - ostream &outputstream) +CPPServerStubGenerator::CPPServerStubGenerator(const std::string &stubname, vector &procedures, ostream &outputstream) : StubGenerator(stubname, procedures, outputstream) {} -CPPServerStubGenerator::CPPServerStubGenerator( - const string &stubname, std::vector &procedures, - const string &filename) +CPPServerStubGenerator::CPPServerStubGenerator(const string &stubname, std::vector &procedures, const string &filename) : StubGenerator(stubname, procedures, filename) {} void CPPServerStubGenerator::generateStub() { @@ -65,15 +57,13 @@ void CPPServerStubGenerator::generateStub() { int depth = CPPHelper::namespaceOpen(*this, stubname); - this->writeLine(replaceAll(TEMPLATE_CPPSERVER_SIGCLASS, "", - classname.at(classname.size() - 1))); + this->writeLine(replaceAll(TEMPLATE_CPPSERVER_SIGCLASS, "", classname.at(classname.size() - 1))); this->writeLine("{"); this->increaseIndentation(); this->writeLine("public:"); this->increaseIndentation(); - this->writeLine(replaceAll(TEMPLATE_CPPSERVER_SIGCONSTRUCTOR, "", - classname.at(classname.size() - 1))); + this->writeLine(replaceAll(TEMPLATE_CPPSERVER_SIGCONSTRUCTOR, "", classname.at(classname.size() - 1))); this->writeLine("{"); this->generateBindings(); this->writeLine("}"); @@ -96,8 +86,7 @@ void CPPServerStubGenerator::generateStub() { void CPPServerStubGenerator::generateBindings() { string tmp; this->increaseIndentation(); - for (vector::const_iterator it = this->procedures.begin(); - it != this->procedures.end(); ++it) { + for (vector::const_iterator it = this->procedures.begin(); it != this->procedures.end(); ++it) { const Procedure &proc = *it; if (proc.GetProcedureType() == RPC_METHOD) { tmp = TEMPLATE_CPPSERVER_METHODBINDING; @@ -105,8 +94,7 @@ void CPPServerStubGenerator::generateBindings() { tmp = TEMPLATE_CPPSERVER_NOTIFICATIONBINDING; } replaceAll2(tmp, "", proc.GetProcedureName()); - replaceAll2(tmp, "", - CPPHelper::normalizeString(proc.GetProcedureName())); + replaceAll2(tmp, "", CPPHelper::normalizeString(proc.GetProcedureName())); replaceAll2(tmp, "", CPPHelper::toString(proc.GetReturnType())); replaceAll2(tmp, "", generateBindingParameterlist(proc)); replaceAll2(tmp, "", this->stubname); @@ -123,29 +111,19 @@ void CPPServerStubGenerator::generateBindings() { } void CPPServerStubGenerator::generateProcedureDefinitions() { - for (vector::const_iterator it = this->procedures.begin(); - it != this->procedures.end(); ++it) { + for (vector::const_iterator it = this->procedures.begin(); it != this->procedures.end(); ++it) { const Procedure &proc = *it; if (proc.GetProcedureType() == RPC_METHOD) { if (!proc.GetParameters().empty()) { - this->writeLine( - replaceAll(TEMPLATE_CPPSERVER_SIGMETHOD, "", - CPPHelper::normalizeString(proc.GetProcedureName()))); + this->writeLine(replaceAll(TEMPLATE_CPPSERVER_SIGMETHOD, "", CPPHelper::normalizeString(proc.GetProcedureName()))); } else { - this->writeLine(replaceAll( - TEMPLATE_CPPSERVER_SIGMETHOD_WITHOUT_PARAMS, "", - CPPHelper::normalizeString(proc.GetProcedureName()))); + this->writeLine(replaceAll(TEMPLATE_CPPSERVER_SIGMETHOD_WITHOUT_PARAMS, "", CPPHelper::normalizeString(proc.GetProcedureName()))); } } else { if (!proc.GetParameters().empty()) { - this->writeLine( - replaceAll(TEMPLATE_CPPSERVER_SIGNOTIFICATION, "", - CPPHelper::normalizeString(proc.GetProcedureName()))); + this->writeLine(replaceAll(TEMPLATE_CPPSERVER_SIGNOTIFICATION, "", CPPHelper::normalizeString(proc.GetProcedureName()))); } else { - this->writeLine( - replaceAll(TEMPLATE_CPPSERVER_SIGNOTIFICATION_WITHOUT_PARAMS, - "", - CPPHelper::normalizeString(proc.GetProcedureName()))); + this->writeLine(replaceAll(TEMPLATE_CPPSERVER_SIGNOTIFICATION_WITHOUT_PARAMS, "", CPPHelper::normalizeString(proc.GetProcedureName()))); } } @@ -166,8 +144,7 @@ void CPPServerStubGenerator::generateProcedureDefinitions() { void CPPServerStubGenerator::generateAbstractDefinitions() { string tmp; - for (vector::iterator it = this->procedures.begin(); - it != this->procedures.end(); ++it) { + for (vector::iterator it = this->procedures.begin(); it != this->procedures.end(); ++it) { Procedure &proc = *it; tmp = TEMPLATE_SERVER_ABSTRACTDEFINITION; string returntype = "void"; @@ -175,23 +152,18 @@ void CPPServerStubGenerator::generateAbstractDefinitions() { returntype = CPPHelper::toCppReturntype(proc.GetReturnType()); } replaceAll2(tmp, "", returntype); - replaceAll2(tmp, "", - CPPHelper::normalizeString(proc.GetProcedureName())); - replaceAll2(tmp, "", - CPPHelper::generateParameterDeclarationList(proc)); + replaceAll2(tmp, "", CPPHelper::normalizeString(proc.GetProcedureName())); + replaceAll2(tmp, "", CPPHelper::generateParameterDeclarationList(proc)); this->writeLine(tmp); } } -string -CPPServerStubGenerator::generateBindingParameterlist(const Procedure &proc) { +string CPPServerStubGenerator::generateBindingParameterlist(const Procedure &proc) { stringstream parameter; const parameterNameList_t &list = proc.GetParameters(); - for (parameterNameList_t::const_iterator it2 = list.begin(); - it2 != list.end(); ++it2) { - parameter << "\"" << it2->first << "\"," << CPPHelper::toString(it2->second) - << ","; + for (parameterNameList_t::const_iterator it2 = list.begin(); it2 != list.end(); ++it2) { + parameter << "\"" << it2->first << "\"," << CPPHelper::toString(it2->second) << ","; } return parameter.str(); } @@ -200,15 +172,12 @@ void CPPServerStubGenerator::generateParameterMapping(const Procedure &proc) { string tmp; const parameterNameList_t ¶ms = proc.GetParameters(); int i = 0; - for (parameterNameList_t::const_iterator it2 = params.begin(); - it2 != params.end(); ++it2) { + for (parameterNameList_t::const_iterator it2 = params.begin(); it2 != params.end(); ++it2) { if (proc.GetParameterDeclarationType() == PARAMS_BY_NAME) { - tmp = "request[\"" + it2->first + "\"]" + - CPPHelper::toCppConversion(it2->second); + tmp = "request[\"" + it2->first + "\"]" + CPPHelper::toCppConversion(it2->second); } else { stringstream tmp2; - tmp2 << "request[" << i << "u]" - << CPPHelper::toCppConversion(it2->second); + tmp2 << "request[" << i << "u]" << CPPHelper::toCppConversion(it2->second); tmp = tmp2.str(); } this->write(tmp); diff --git a/src/stubgenerator/server/cppserverstubgenerator.h b/src/stubgenerator/server/cppserverstubgenerator.h index e9f4deee..23b5762f 100644 --- a/src/stubgenerator/server/cppserverstubgenerator.h +++ b/src/stubgenerator/server/cppserverstubgenerator.h @@ -10,25 +10,23 @@ #ifndef JSONRPC_CPP_SERVERSTUBGENERATOR_H #define JSONRPC_CPP_SERVERSTUBGENERATOR_H -#include "../stubgenerator.h" #include "../codegenerator.h" +#include "../stubgenerator.h" -namespace jsonrpc -{ - class CPPServerStubGenerator : public StubGenerator - { - public: - CPPServerStubGenerator(const std::string& stubname, std::vector &procedures, std::ostream &outputstream); - CPPServerStubGenerator(const std::string& stubname, std::vector &procedures, const std::string &filename); +namespace jsonrpc { + class CPPServerStubGenerator : public StubGenerator { + public: + CPPServerStubGenerator(const std::string &stubname, std::vector &procedures, std::ostream &outputstream); + CPPServerStubGenerator(const std::string &stubname, std::vector &procedures, const std::string &filename); - virtual void generateStub(); + virtual void generateStub(); - void generateBindings(); - void generateProcedureDefinitions(); - void generateAbstractDefinitions(); - std::string generateBindingParameterlist(const Procedure &proc); - void generateParameterMapping(const Procedure &proc); - }; -} + void generateBindings(); + void generateProcedureDefinitions(); + void generateAbstractDefinitions(); + std::string generateBindingParameterlist(const Procedure &proc); + void generateParameterMapping(const Procedure &proc); + }; +} // namespace jsonrpc #endif // JSONRPC_CPP_SERVERSTUBGENERATOR_H diff --git a/src/stubgenerator/servertemplate.h b/src/stubgenerator/servertemplate.h index bb5b25db..3e21bc44 100644 --- a/src/stubgenerator/servertemplate.h +++ b/src/stubgenerator/servertemplate.h @@ -10,7 +10,8 @@ #ifndef JSONRPC_CPP_SERVERTEMPLATE_H #define JSONRPC_CPP_SERVERTEMPLATE_H -#define TEMPLATE_SERVER_STUB "\ +#define TEMPLATE_SERVER_STUB \ + "\ /**\n\ * THIS FILE IS GENERATED BY jsonrpcstub, DO NOT CHANGE IT!!!!!\n\ */\n\ @@ -35,25 +36,30 @@ class : public jsonrpc::AbstractServer<>\n\ #endif //__H_\n\ " -#define TEMPLATE_SERVER_METHODBINDING "\ +#define TEMPLATE_SERVER_METHODBINDING \ + "\ this->bindAndAddMethod(new jsonrpc::Procedure(\"\", , , NULL), &::I);" -#define TEMPLATE_SERVER_NOTIFICATIONBINDING "\ +#define TEMPLATE_SERVER_NOTIFICATIONBINDING \ + "\ this->bindAndAddNotification(new jsonrpc::Procedure(\"\", , NULL), &::I);" -#define TEMPLATE_SERVER_METHODDEFINITION "\ +#define TEMPLATE_SERVER_METHODDEFINITION \ + "\ inline virtual void I(const Json::Value& request, Json::Value& response) \n\ {\n\ response = this->();\n\ }\n\ " -#define TEMPLATE_SERVER_NOTIFICAITONDEFINITION "\ +#define TEMPLATE_SERVER_NOTIFICAITONDEFINITION \ + "\ inline virtual void I(const Json::Value& request) \n\ {\n\ this->();\n\ }\n\ " -#define TEMPLATE_SERVER_ABSTRACTDEFINITION "\ +#define TEMPLATE_SERVER_ABSTRACTDEFINITION \ + "\ virtual () = 0;\n\ " diff --git a/src/stubgenerator/stubgenerator.cpp b/src/stubgenerator/stubgenerator.cpp index 532769b5..3d0cfbc2 100644 --- a/src/stubgenerator/stubgenerator.cpp +++ b/src/stubgenerator/stubgenerator.cpp @@ -23,32 +23,26 @@ using namespace std; using namespace jsonrpc; -#define EXIT_ERROR(X) \ - cerr << X << endl; \ - arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); \ +#define EXIT_ERROR(X) \ + cerr << X << endl; \ + arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); \ return 1; -StubGenerator::StubGenerator(const string &stubname, - std::vector &procedures, - ostream &outputstream) +StubGenerator::StubGenerator(const string &stubname, std::vector &procedures, ostream &outputstream) : CodeGenerator(outputstream), stubname(stubname), procedures(procedures) {} -StubGenerator::StubGenerator(const string &stubname, - std::vector &procedures, - const std::string &filename) +StubGenerator::StubGenerator(const string &stubname, std::vector &procedures, const std::string &filename) : CodeGenerator(filename), stubname(stubname), procedures(procedures) {} StubGenerator::~StubGenerator() {} -string StubGenerator::replaceAll(const string &text, const string &fnd, - const string &rep) { +string StubGenerator::replaceAll(const string &text, const string &fnd, const string &rep) { string result = text; replaceAll2(result, fnd, rep); return result; } -void StubGenerator::replaceAll2(string &result, const string &find, - const string &replace) { +void StubGenerator::replaceAll2(string &result, const string &find, const string &replace) { size_t pos = result.find(find); while (pos != string::npos) { result.replace(pos, find.length(), replace); diff --git a/src/stubgenerator/stubgenerator.h b/src/stubgenerator/stubgenerator.h index ea48f913..cbf44a7d 100644 --- a/src/stubgenerator/stubgenerator.h +++ b/src/stubgenerator/stubgenerator.h @@ -10,32 +10,29 @@ #ifndef JSONRPC_CPP_STUBGENERATOR_H #define JSONRPC_CPP_STUBGENERATOR_H -#include #include +#include #include "codegenerator.h" -namespace jsonrpc -{ - enum connectiontype_t {CONNECTION_HTTP}; - - class StubGenerator : public CodeGenerator - { - public: - StubGenerator(const std::string& stubname, std::vector &procedures, std::ostream &outputstream); - StubGenerator(const std::string& stubname, std::vector &procedures, const std::string &filename); +namespace jsonrpc { + enum connectiontype_t { CONNECTION_HTTP }; - virtual ~StubGenerator(); - virtual void generateStub() = 0; + class StubGenerator : public CodeGenerator { + public: + StubGenerator(const std::string &stubname, std::vector &procedures, std::ostream &outputstream); + StubGenerator(const std::string &stubname, std::vector &procedures, const std::string &filename); - static std::string replaceAll(const std::string& text, const std::string& fnd, const std::string& rep); - static void replaceAll2(std::string &text, const std::string &find, const std::string &replace); + virtual ~StubGenerator(); + virtual void generateStub() = 0; - protected: - std::string stubname; - std::vector &procedures; - }; -} + static std::string replaceAll(const std::string &text, const std::string &fnd, const std::string &rep); + static void replaceAll2(std::string &text, const std::string &find, const std::string &replace); + protected: + std::string stubname; + std::vector &procedures; + }; +} // namespace jsonrpc #endif // JSONRPC_CPP_STUBGENERATOR_H diff --git a/src/stubgenerator/stubgeneratorfactory.cpp b/src/stubgenerator/stubgeneratorfactory.cpp index bb9e5102..b31c7cf2 100644 --- a/src/stubgenerator/stubgeneratorfactory.cpp +++ b/src/stubgenerator/stubgeneratorfactory.cpp @@ -21,44 +21,24 @@ using namespace jsonrpc; using namespace std; -bool StubGeneratorFactory::createStubGenerators( - int argc, char **argv, vector &procedures, - vector &stubgenerators, FILE *_stdout, FILE *_stderr) { - struct arg_file *inputfile = - arg_file0(NULL, NULL, "", "path of input specification file"); +bool StubGeneratorFactory::createStubGenerators(int argc, char **argv, vector &procedures, vector &stubgenerators, FILE *_stdout, + FILE *_stderr) { + struct arg_file *inputfile = arg_file0(NULL, NULL, "", "path of input specification file"); struct arg_lit *help = arg_lit0("h", "help", "print this help and exit"); struct arg_lit *version = arg_lit0(NULL, "version", "print version and exit"); - struct arg_lit *verbose = arg_lit0( - "v", "verbose", "print more information about what is happening"); - struct arg_str *cppserver = - arg_str0(NULL, "cpp-server", "", - "name of the C++ server stub class"); - struct arg_str *cppserverfile = - arg_str0(NULL, "cpp-server-file", "", - "name of the C++ server stub file"); - struct arg_str *cppclient = - arg_str0(NULL, "cpp-client", "", - "name of the C++ client stub class"); - struct arg_str *cppclientfile = - arg_str0(NULL, "cpp-client-file", "", - "name of the C++ client stub file"); - struct arg_str *jsclient = - arg_str0(NULL, "js-client", "", - "name of the JavaScript client stub class"); - struct arg_str *jsclientfile = - arg_str0(NULL, "js-client-file", "", - "name of the JavaScript client stub file"); - struct arg_str *pyclient = arg_str0(NULL, "py-client", "", - "name of the Python client stub class"); - struct arg_str *pyclientfile = - arg_str0(NULL, "py-client-file", "", - "name of the Python client stub file"); + struct arg_lit *verbose = arg_lit0("v", "verbose", "print more information about what is happening"); + struct arg_str *cppserver = arg_str0(NULL, "cpp-server", "", "name of the C++ server stub class"); + struct arg_str *cppserverfile = arg_str0(NULL, "cpp-server-file", "", "name of the C++ server stub file"); + struct arg_str *cppclient = arg_str0(NULL, "cpp-client", "", "name of the C++ client stub class"); + struct arg_str *cppclientfile = arg_str0(NULL, "cpp-client-file", "", "name of the C++ client stub file"); + struct arg_str *jsclient = arg_str0(NULL, "js-client", "", "name of the JavaScript client stub class"); + struct arg_str *jsclientfile = arg_str0(NULL, "js-client-file", "", "name of the JavaScript client stub file"); + struct arg_str *pyclient = arg_str0(NULL, "py-client", "", "name of the Python client stub class"); + struct arg_str *pyclientfile = arg_str0(NULL, "py-client-file", "", "name of the Python client stub file"); struct arg_end *end = arg_end(20); - void *argtable[] = {inputfile, help, version, verbose, - cppserver, cppserverfile, cppclient, cppclientfile, - jsclient, jsclientfile, pyclient, pyclientfile, - end}; + void *argtable[] = {inputfile, help, version, verbose, cppserver, cppserverfile, cppclient, cppclientfile, + jsclient, jsclientfile, pyclient, pyclientfile, end}; if (arg_parse(argc, argv, argtable) > 0) { arg_print_errors(_stderr, end, argv[0]); @@ -76,9 +56,7 @@ bool StubGeneratorFactory::createStubGenerators( } if (version->count > 0) { - fprintf(_stdout, "jsonrpcstub version %d.%d.%d\n", - JSONRPC_CPP_MAJOR_VERSION, JSONRPC_CPP_MINOR_VERSION, - JSONRPC_CPP_PATCH_VERSION); + fprintf(_stdout, "jsonrpcstub version %d.%d.%d\n", JSONRPC_CPP_MAJOR_VERSION, JSONRPC_CPP_MINOR_VERSION, JSONRPC_CPP_PATCH_VERSION); arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); return true; } @@ -90,11 +68,9 @@ bool StubGeneratorFactory::createStubGenerators( } try { - procedures = - SpecificationParser::GetProceduresFromFile(inputfile->filename[0]); + procedures = SpecificationParser::GetProceduresFromFile(inputfile->filename[0]); if (verbose->count > 0) { - fprintf(_stdout, "Found %zu procedures in %s\n", procedures.size(), - inputfile->filename[0]); + fprintf(_stdout, "Found %zu procedures in %s\n", procedures.size(), inputfile->filename[0]); for (unsigned int i = 0; i < procedures.size(); ++i) { if (procedures.at(i).GetProcedureType() == RPC_METHOD) { fprintf(_stdout, "\t[Method] "); @@ -113,10 +89,8 @@ bool StubGeneratorFactory::createStubGenerators( else filename = CPPHelper::class2Filename(cppserver->sval[0]); if (verbose->count > 0) - fprintf(_stdout, "Generating C++ Serverstub to: %s\n", - filename.c_str()); - stubgenerators.push_back( - new CPPServerStubGenerator(cppserver->sval[0], procedures, filename)); + fprintf(_stdout, "Generating C++ Serverstub to: %s\n", filename.c_str()); + stubgenerators.push_back(new CPPServerStubGenerator(cppserver->sval[0], procedures, filename)); } if (cppclient->count > 0) { @@ -126,10 +100,8 @@ bool StubGeneratorFactory::createStubGenerators( else filename = CPPHelper::class2Filename(cppclient->sval[0]); if (verbose->count > 0) - fprintf(_stdout, "Generating C++ Clientstub to: %s\n", - filename.c_str()); - stubgenerators.push_back( - new CPPClientStubGenerator(cppclient->sval[0], procedures, filename)); + fprintf(_stdout, "Generating C++ Clientstub to: %s\n", filename.c_str()); + stubgenerators.push_back(new CPPClientStubGenerator(cppclient->sval[0], procedures, filename)); } if (jsclient->count > 0) { @@ -140,10 +112,8 @@ bool StubGeneratorFactory::createStubGenerators( filename = JSClientStubGenerator::class2Filename(jsclient->sval[0]); if (verbose->count > 0) - fprintf(_stdout, "Generating JavaScript Clientstub to: %s\n", - filename.c_str()); - stubgenerators.push_back( - new JSClientStubGenerator(jsclient->sval[0], procedures, filename)); + fprintf(_stdout, "Generating JavaScript Clientstub to: %s\n", filename.c_str()); + stubgenerators.push_back(new JSClientStubGenerator(jsclient->sval[0], procedures, filename)); } if (pyclient->count > 0) { @@ -154,10 +124,8 @@ bool StubGeneratorFactory::createStubGenerators( filename = PythonClientStubGenerator::class2Filename(pyclient->sval[0]); if (verbose->count > 0) - fprintf(_stdout, "Generating Python Clientstub to: %s\n", - filename.c_str()); - stubgenerators.push_back(new PythonClientStubGenerator( - pyclient->sval[0], procedures, filename)); + fprintf(_stdout, "Generating Python Clientstub to: %s\n", filename.c_str()); + stubgenerators.push_back(new PythonClientStubGenerator(pyclient->sval[0], procedures, filename)); } } catch (const JsonRpcException &ex) { fprintf(_stderr, "%s\n", ex.what()); @@ -168,8 +136,7 @@ bool StubGeneratorFactory::createStubGenerators( return true; } -void StubGeneratorFactory::deleteStubGenerators( - std::vector &stubgenerators) { +void StubGeneratorFactory::deleteStubGenerators(std::vector &stubgenerators) { for (unsigned int i = 0; i < stubgenerators.size(); ++i) { delete stubgenerators[i]; } diff --git a/src/stubgenerator/stubgeneratorfactory.h b/src/stubgenerator/stubgeneratorfactory.h index b4bdedd7..e4323d86 100644 --- a/src/stubgenerator/stubgeneratorfactory.h +++ b/src/stubgenerator/stubgeneratorfactory.h @@ -10,17 +10,17 @@ #ifndef JSONRPC_CPP_STUBGENERATORFACTORY_H #define JSONRPC_CPP_STUBGENERATORFACTORY_H -#include #include "stubgenerator.h" +#include namespace jsonrpc { - class StubGeneratorFactory - { - public: - static bool createStubGenerators(int argc, char** argv, std::vector &procedures, std::vector &stubgenerators, FILE* _stdout, FILE* _stderr); - static void deleteStubGenerators(std::vector &stubgenerators); - }; + class StubGeneratorFactory { + public: + static bool createStubGenerators(int argc, char **argv, std::vector &procedures, std::vector &stubgenerators, FILE *_stdout, + FILE *_stderr); + static void deleteStubGenerators(std::vector &stubgenerators); + }; } // namespace jsonrpc diff --git a/src/stubgenerator/stubhelper.h b/src/stubgenerator/stubhelper.h index 557fbd00..16a45b4b 100644 --- a/src/stubgenerator/stubhelper.h +++ b/src/stubgenerator/stubhelper.h @@ -13,5 +13,4 @@ #include #include - #endif // STUBHELPER_H diff --git a/src/test/CMakeLists.txt b/src/test/CMakeLists.txt index ae8a508f..e481ef9a 100644 --- a/src/test/CMakeLists.txt +++ b/src/test/CMakeLists.txt @@ -6,60 +6,60 @@ include_directories(..) include_directories(${CMAKE_BINARY_DIR}) add_custom_command( - OUTPUT ${CMAKE_BINARY_DIR}/gen/abstractstubserver.h - COMMAND jsonrpcstub ARGS ${CMAKE_CURRENT_SOURCE_DIR}/spec.json --cpp-server=AbstractStubServer --cpp-server-file=${CMAKE_BINARY_DIR}/gen/abstractstubserver.h - MAIN_DEPENDENCY spec.json - DEPENDS jsonrpcstub - COMMENT "Generating Server Stubfiles" - VERBATIM + OUTPUT ${CMAKE_BINARY_DIR}/gen/abstractstubserver.h + COMMAND jsonrpcstub ARGS ${CMAKE_CURRENT_SOURCE_DIR}/spec.json --cpp-server=AbstractStubServer --cpp-server-file=${CMAKE_BINARY_DIR}/gen/abstractstubserver.h + MAIN_DEPENDENCY spec.json + DEPENDS jsonrpcstub + COMMENT "Generating Server Stubfiles" + VERBATIM ) add_custom_command( - OUTPUT ${CMAKE_BINARY_DIR}/gen/stubclient.h - COMMAND jsonrpcstub ARGS ${CMAKE_CURRENT_SOURCE_DIR}/spec.json --cpp-client=StubClient --cpp-client-file=${CMAKE_BINARY_DIR}/gen/stubclient.h - MAIN_DEPENDENCY spec.json - DEPENDS jsonrpcstub - COMMENT "Generating Client Stubfile" - VERBATIM + OUTPUT ${CMAKE_BINARY_DIR}/gen/stubclient.h + COMMAND jsonrpcstub ARGS ${CMAKE_CURRENT_SOURCE_DIR}/spec.json --cpp-client=StubClient --cpp-client-file=${CMAKE_BINARY_DIR}/gen/stubclient.h + MAIN_DEPENDENCY spec.json + DEPENDS jsonrpcstub + COMMENT "Generating Client Stubfile" + VERBATIM ) -if(HTTP_CLIENT AND HTTP_SERVER) +if (HTTP_CLIENT AND HTTP_SERVER) add_definitions(-DHTTP_TESTING) file(COPY ${CMAKE_SOURCE_DIR}/src/examples/server.key ${CMAKE_SOURCE_DIR}/src/examples/server.pem DESTINATION ${CMAKE_BINARY_DIR}) file(COPY ${CMAKE_SOURCE_DIR}/src/examples/server.key ${CMAKE_SOURCE_DIR}/src/examples/server.pem DESTINATION ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) -else() +else () list(REMOVE_ITEM test_source "${CMAKE_CURRENT_SOURCE_DIR}/testhttpserver.cpp") -endif() +endif () -if(REDIS_CLIENT AND REDIS_SERVER) +if (REDIS_CLIENT AND REDIS_SERVER) file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/redis.conf DESTINATION ${CMAKE_BINARY_DIR}) file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/redis.conf DESTINATION ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) add_definitions(-DREDIS_TESTING) -else() +else () list(REMOVE_ITEM test_source "${CMAKE_CURRENT_SOURCE_DIR}/testredisserver.cpp") -endif() +endif () -if(UNIX_DOMAIN_SOCKET_SERVER AND UNIX_DOMAIN_SOCKET_CLIENT) +if (UNIX_DOMAIN_SOCKET_SERVER AND UNIX_DOMAIN_SOCKET_CLIENT) add_definitions(-DUNIXDOMAINSOCKET_TESTING) -endif() +endif () -if(FILE_DESCRIPTOR_SERVER AND FILE_DESCRIPTOR_CLIENT) +if (FILE_DESCRIPTOR_SERVER AND FILE_DESCRIPTOR_CLIENT) add_definitions(-DFILEDESCRIPTOR_TESTING) -endif() +endif () -if(TCP_SOCKET_SERVER AND TCP_SOCKET_CLIENT) +if (TCP_SOCKET_SERVER AND TCP_SOCKET_CLIENT) add_definitions(-DTCPSOCKET_TESTING) -endif() +endif () -if(COMPILE_STUBGEN) +if (COMPILE_STUBGEN) add_definitions(-DSTUBGEN_TESTING) file(GLOB test_specs *.json) file(COPY ${test_specs} DESTINATION ${CMAKE_BINARY_DIR}) file(COPY ${test_specs} DESTINATION ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) list(APPEND test_source "${CMAKE_BINARY_DIR}/gen/abstractstubserver.h") list(APPEND test_source "${CMAKE_BINARY_DIR}/gen/stubclient.h") -endif() +endif () add_executable(unit_testsuite ${test_source}) target_link_libraries(unit_testsuite jsonrpccommon) @@ -69,41 +69,41 @@ target_link_libraries(unit_testsuite jsonrpcclient) if (NOT CATCH_FOUND) # let's wait for catch files to be downloaded add_dependencies(unit_testsuite catch) -endif() +endif () -if(COMPILE_STUBGEN) +if (COMPILE_STUBGEN) target_link_libraries(unit_testsuite libjsonrpcstub) add_dependencies(unit_testsuite libjsonrpcstub) -endif() +endif () add_test(client ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[client]") add_test(server ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[server]") add_test(NAME common WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[common]") -if(HTTP_CLIENT AND HTTP_SERVER) +if (HTTP_CLIENT AND HTTP_SERVER) add_test(NAME connector_http WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[connector_http]") -endif() +endif () -if(REDIS_CLIENT AND REDIS_SERVER) +if (REDIS_CLIENT AND REDIS_SERVER) add_test(NAME connector_redis WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[connector_redis]") -endif() +endif () if (UNIX_DOMAIN_SOCKET_CLIENT AND UNIX_DOMAIN_SOCKET_SERVER) add_test(NAME connector_unixdomainsocket WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[connector_unixdomainsocket]") -endif() +endif () if (FILE_DESCRIPTOR_CLIENT AND FILE_DESCRIPTOR_SERVER) add_test(NAME connector_filedescriptor WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[connector_filedescriptor]") -endif() +endif () if (TCP_SOCKET_CLIENT AND TCP_SOCKET_SERVER) add_test(NAME connector_tcpsocket WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[connector_tcpsocket]") -endif() +endif () -if(COMPILE_STUBGEN) +if (COMPILE_STUBGEN) add_test(NAME stubgen WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[stubgenerator]") -endif() +endif () -if(HTTP_CLIENT AND HTTP_SERVER AND COMPILE_STUBGEN) +if (HTTP_CLIENT AND HTTP_SERVER AND COMPILE_STUBGEN) add_test(NAME integration WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[integration]") -endif() +endif () diff --git a/src/test/checkexception.h b/src/test/checkexception.h index 77a7b1a2..c8e31430 100644 --- a/src/test/checkexception.h +++ b/src/test/checkexception.h @@ -10,6 +10,16 @@ #ifndef CHECKEXCEPTION_H #define CHECKEXCEPTION_H -#define CHECK_EXCEPTION_TYPE(throwCode, exceptionType, expression) {bool thrown = false; try {throwCode;} catch(exceptionType &ex) { CHECK(expression(ex)); thrown = true; } CHECK(thrown);} +#define CHECK_EXCEPTION_TYPE(throwCode, exceptionType, expression) \ + { \ + bool thrown = false; \ + try { \ + throwCode; \ + } catch (exceptionType & ex) { \ + CHECK(expression(ex)); \ + thrown = true; \ + } \ + CHECK(thrown); \ + } #endif // CHECKEXCEPTION_H diff --git a/src/test/mockclientconnectionhandler.cpp b/src/test/mockclientconnectionhandler.cpp index 13b20df7..76a27aee 100644 --- a/src/test/mockclientconnectionhandler.cpp +++ b/src/test/mockclientconnectionhandler.cpp @@ -14,11 +14,9 @@ using namespace std; using namespace jsonrpc; -MockClientConnectionHandler::MockClientConnectionHandler() - : response(""), request(""), timeout(0) {} +MockClientConnectionHandler::MockClientConnectionHandler() : response(""), request(""), timeout(0) {} -void MockClientConnectionHandler::HandleRequest(const std::string &request, - std::string &retValue) { +void MockClientConnectionHandler::HandleRequest(const std::string &request, std::string &retValue) { std::this_thread::sleep_for(std::chrono::microseconds(timeout * 1000)); this->request = request; diff --git a/src/test/mockclientconnectionhandler.h b/src/test/mockclientconnectionhandler.h index 1badece9..9da22e9d 100644 --- a/src/test/mockclientconnectionhandler.h +++ b/src/test/mockclientconnectionhandler.h @@ -13,20 +13,17 @@ #include #include -namespace jsonrpc -{ - class MockClientConnectionHandler : public IClientConnectionHandler - { - public: - MockClientConnectionHandler(); +namespace jsonrpc { + class MockClientConnectionHandler : public IClientConnectionHandler { + public: + MockClientConnectionHandler(); - virtual void HandleRequest(const std::string& request, std::string& retValue); + virtual void HandleRequest(const std::string &request, std::string &retValue); - std::string response; - std::string request; - long timeout; - }; + std::string response; + std::string request; + long timeout; + }; - -} +} // namespace jsonrpc #endif // JSONRPC_CPP_MOCKCLIENTCONNECTIONHANDLER_H diff --git a/src/test/mockclientconnector.cpp b/src/test/mockclientconnector.cpp index a037056c..8b61d6a5 100644 --- a/src/test/mockclientconnector.cpp +++ b/src/test/mockclientconnector.cpp @@ -25,12 +25,9 @@ Json::Value MockClientConnector::GetJsonRequest() { return Json::nullValue; } -void MockClientConnector::SetResponse(const std::string &response) { - this->response = response; -} +void MockClientConnector::SetResponse(const std::string &response) { this->response = response; } -void MockClientConnector::SendRPCMessage(const string &message, - string &result) { +void MockClientConnector::SendRPCMessage(const string &message, string &result) { request = message; result = this->response; } diff --git a/src/test/mockclientconnector.h b/src/test/mockclientconnector.h index a706d7ef..e9cbecf3 100644 --- a/src/test/mockclientconnector.h +++ b/src/test/mockclientconnector.h @@ -14,21 +14,20 @@ namespace jsonrpc { - class MockClientConnector : public IClientConnector - { - public: - MockClientConnector(); + class MockClientConnector : public IClientConnector { + public: + MockClientConnector(); - void SetResponse(const std::string &response); + void SetResponse(const std::string &response); - std::string GetRequest(); - Json::Value GetJsonRequest(); - virtual void SendRPCMessage(const std::string& message, std::string& result) ; + std::string GetRequest(); + Json::Value GetJsonRequest(); + virtual void SendRPCMessage(const std::string &message, std::string &result); - private: - std::string response; - std::string request; - }; + private: + std::string response; + std::string request; + }; } // namespace jsonrpc diff --git a/src/test/mockserverconnector.h b/src/test/mockserverconnector.h index 18f8f44a..d1c5db5e 100644 --- a/src/test/mockserverconnector.h +++ b/src/test/mockserverconnector.h @@ -15,23 +15,23 @@ namespace jsonrpc { -class MockServerConnector : public AbstractServerConnector { -public: - MockServerConnector(); + class MockServerConnector : public AbstractServerConnector { + public: + MockServerConnector(); - virtual bool StartListening(); - virtual bool StopListening(); + virtual bool StartListening(); + virtual bool StopListening(); - bool SetRequest(const std::string &request); - Json::Value GetJsonRequest(); + bool SetRequest(const std::string &request); + Json::Value GetJsonRequest(); - std::string GetResponse(); - Json::Value GetJsonResponse(); + std::string GetResponse(); + Json::Value GetJsonResponse(); -private: - std::string request; - std::string response; -}; + private: + std::string request; + std::string response; + }; } // namespace jsonrpc diff --git a/src/test/spec.json b/src/test/spec.json index 2eaa32e4..2ae5163c 100644 --- a/src/test/spec.json +++ b/src/test/spec.json @@ -1,51 +1,51 @@ [ - { - "name": "sayHello", - "params": { - "name": "Peter" - }, - "returns": "Hello Peter" + { + "name": "sayHello", + "params": { + "name": "Peter" }, - { - "name": "notifyServer" - }, - { - "name": "addNumbers", - "params": [ - 3, - 4 - ], - "returns": 7 - }, - { - "name": "addNumbers2", - "params": [ - 3.2, - 4.1 - ], - "returns": 7.5 - }, - { - "name": "isEqual", - "params": [ - "string1", - "string2" - ], - "returns": false - }, - { - "name": "buildObject", - "params": [ - "peter", - 1990 - ], - "returns": { - "name": "peter", - "year": 1990 - } - }, - { - "name" : "methodWithoutParameters", - "returns": "String" + "returns": "Hello Peter" + }, + { + "name": "notifyServer" + }, + { + "name": "addNumbers", + "params": [ + 3, + 4 + ], + "returns": 7 + }, + { + "name": "addNumbers2", + "params": [ + 3.2, + 4.1 + ], + "returns": 7.5 + }, + { + "name": "isEqual", + "params": [ + "string1", + "string2" + ], + "returns": false + }, + { + "name": "buildObject", + "params": [ + "peter", + 1990 + ], + "returns": { + "name": "peter", + "year": 1990 } + }, + { + "name": "methodWithoutParameters", + "returns": "String" + } ] diff --git a/src/test/test_client.cpp b/src/test/test_client.cpp index 6817ad59..b3599502 100644 --- a/src/test/test_client.cpp +++ b/src/test/test_client.cpp @@ -18,34 +18,27 @@ using namespace jsonrpc; using namespace std; namespace testclient { -bool check_exception1(JsonRpcException const &ex) { - return ex.GetCode() == Errors::ERROR_RPC_JSON_PARSE_ERROR; -} + bool check_exception1(JsonRpcException const &ex) { return ex.GetCode() == Errors::ERROR_RPC_JSON_PARSE_ERROR; } -bool check_exception2(JsonRpcException const &ex) { - return ex.GetCode() == Errors::ERROR_CLIENT_INVALID_RESPONSE; -} + bool check_exception2(JsonRpcException const &ex) { return ex.GetCode() == Errors::ERROR_CLIENT_INVALID_RESPONSE; } -bool check_exception3(JsonRpcException const &ex) { - return ex.GetCode() == Errors::ERROR_RPC_INVALID_REQUEST && - ex.GetData().size() == 2; -} + bool check_exception3(JsonRpcException const &ex) { return ex.GetCode() == Errors::ERROR_RPC_INVALID_REQUEST && ex.GetData().size() == 2; } -struct F { - MockClientConnector c; - Client client; - Json::Value params; + struct F { + MockClientConnector c; + Client client; + Json::Value params; - F() : client(c, JSONRPC_CLIENT_V2) {} -}; + F() : client(c, JSONRPC_CLIENT_V2) {} + }; -struct F1 { - MockClientConnector c; - Client client; - Json::Value params; + struct F1 { + MockClientConnector c; + Client client; + Json::Value params; - F1() : client(c, JSONRPC_CLIENT_V1) {} -}; + F1() : client(c, JSONRPC_CLIENT_V1) {} + }; } // namespace testclient using namespace testclient; @@ -87,48 +80,35 @@ TEST_CASE_METHOD(F, "test_client_v2_errorresponse", TEST_MODULE) { c.SetResponse("{\"jsonrpc\":\"2.0\", \"error\": {\"code\": -32600, " "\"message\": \"Invalid Request\", \"data\": [1,2]}, \"id\": " "null}"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception3); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception3); } TEST_CASE_METHOD(F, "test_client_v2_invalidjson", TEST_MODULE) { c.SetResponse("{\"method\":234"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception1); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception1); } TEST_CASE_METHOD(F, "test_client_v2_invalidresponse", TEST_MODULE) { c.SetResponse("{\"jsonrpc\":\"2.0\", \"id\": 1, \"resulto\": 23}"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"jsonrpc\":\"2.0\", \"id2\": 1, \"result\": 23}"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"jsonrpc\":\"1.0\", \"id\": 1, \"result\": 23}"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"id\": 1, \"result\": 23}"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception2); - c.SetResponse( - "{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23, \"error\": {}}"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); + c.SetResponse("{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23, \"error\": {}}"); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"jsonrpc\":\"2.0\", \"id\": 1, \"error\": {}}"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"jsonrpc\":\"2.0\", \"result\": 23}"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{}"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("[]"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("23"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); } TEST_CASE_METHOD(F, "test_client_v2_batchcall_success", TEST_MODULE) { @@ -180,16 +160,13 @@ TEST_CASE_METHOD(F, "test_client_v2_batchcall_error", TEST_MODULE) { CHECK(response.getErrorMessage(3) == ""); c.SetResponse("{}"); - CHECK_EXCEPTION_TYPE(client.CallProcedures(bc), JsonRpcException, - check_exception2); + CHECK_EXCEPTION_TYPE(client.CallProcedures(bc), JsonRpcException, check_exception2); c.SetResponse("[1,2,3]"); - CHECK_EXCEPTION_TYPE(client.CallProcedures(bc), JsonRpcException, - check_exception2); + CHECK_EXCEPTION_TYPE(client.CallProcedures(bc), JsonRpcException, check_exception2); c.SetResponse("[[],[],[]]"); - CHECK_EXCEPTION_TYPE(client.CallProcedures(bc), JsonRpcException, - check_exception2); + CHECK_EXCEPTION_TYPE(client.CallProcedures(bc), JsonRpcException, check_exception2); } TEST_CASE_METHOD(F1, "test_client_v1_method_success", TEST_MODULE) { @@ -223,41 +200,30 @@ TEST_CASE_METHOD(F1, "test_client_v1_notification_success", TEST_MODULE) { TEST_CASE_METHOD(F1, "test_client_v1_errorresponse", TEST_MODULE) { c.SetResponse("{\"result\": null, \"error\": {\"code\": -32600, \"message\": " "\"Invalid Request\", \"data\": [1,2]}, \"id\": null}"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception3); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception3); c.SetResponse("{\"result\": null, \"error\": {\"code\": -32600, \"message\": " "\"Invalid Request\", \"data\": [1,2]}, \"id\": null}"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception3); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception3); } TEST_CASE_METHOD(F1, "test_client_v1_invalidresponse", TEST_MODULE) { c.SetResponse("{\"id\": 1, \"resulto\": 23, \"error\": null}"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"id\": 1, \"result\": 23}"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"id\": 1, \"error\": null}"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"id\": 1}"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"id\": 1, \"result\": 23, \"error\": {}}"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{\"id\": 1, \"result\": null, \"error\": {}}"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{}"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("[]"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("23"); - CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), - JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); } diff --git a/src/test/test_common.cpp b/src/test/test_common.cpp index d2637631..0d4920e6 100644 --- a/src/test/test_common.cpp +++ b/src/test/test_common.cpp @@ -20,20 +20,15 @@ using namespace jsonrpc; using namespace std; namespace testcommon { -bool check_exception1(JsonRpcException const &ex) { - return ex.GetCode() == Errors::ERROR_RPC_JSON_PARSE_ERROR; -} + bool check_exception1(JsonRpcException const &ex) { return ex.GetCode() == Errors::ERROR_RPC_JSON_PARSE_ERROR; } -bool check_exception2(JsonRpcException const &ex) { - return ex.GetCode() == Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX; -} + bool check_exception2(JsonRpcException const &ex) { return ex.GetCode() == Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX; } } // namespace testcommon using namespace testcommon; TEST_CASE("test_procedure_parametervalidation", TEST_MODULE) { - Procedure proc1("someprocedure", PARAMS_BY_NAME, JSON_BOOLEAN, "name", - JSON_STRING, "ssnr", JSON_INTEGER, NULL); + Procedure proc1("someprocedure", PARAMS_BY_NAME, JSON_BOOLEAN, "name", JSON_STRING, "ssnr", JSON_INTEGER, NULL); // Expected to pass validation Json::Value param1; @@ -53,10 +48,8 @@ TEST_CASE("test_procedure_parametervalidation", TEST_MODULE) { param3.append("Peter"); CHECK(proc1.ValidateNamedParameters(param3) == false); - Procedure proc2("someprocedure", PARAMS_BY_NAME, JSON_BOOLEAN, "bool", - JSON_BOOLEAN, "object", JSON_OBJECT, "array", JSON_ARRAY, - "real", JSON_REAL, "int", JSON_INTEGER, "numeric", - JSON_NUMERIC, NULL); + Procedure proc2("someprocedure", PARAMS_BY_NAME, JSON_BOOLEAN, "bool", JSON_BOOLEAN, "object", JSON_OBJECT, "array", JSON_ARRAY, "real", JSON_REAL, "int", + JSON_INTEGER, "numeric", JSON_NUMERIC, NULL); Json::Value param4; Json::Value array; array.append(0); @@ -103,8 +96,7 @@ TEST_CASE("test_exception", TEST_MODULE) { CHECK(ex.GetCode() == -32003); JsonRpcException ex2(Errors::ERROR_CLIENT_CONNECTOR, "addInfo"); - CHECK(string(ex2.what()) == - "Exception -32003 : Client connector error: addInfo"); + CHECK(string(ex2.what()) == "Exception -32003 : Client connector error: addInfo"); JsonRpcException ex3("addInfo"); CHECK(string(ex3.what()) == "addInfo"); @@ -114,44 +106,27 @@ TEST_CASE("test_exception", TEST_MODULE) { Json::Value data; data.append(13); data.append(41); - JsonRpcException ex4(Errors::ERROR_RPC_INTERNAL_ERROR, "internal error", - data); + JsonRpcException ex4(Errors::ERROR_RPC_INTERNAL_ERROR, "internal error", data); CHECK(ex4.GetData().size() == 2); CHECK(ex4.GetData()[0].asInt() == 13); CHECK(ex4.GetData()[1].asInt() == 41); } TEST_CASE("test_specificationparser_errors", TEST_MODULE) { - CHECK_EXCEPTION_TYPE( - SpecificationParser::GetProceduresFromFile("testspec1.json"), - JsonRpcException, check_exception1); - CHECK_EXCEPTION_TYPE( - SpecificationParser::GetProceduresFromFile("testspec2.json"), - JsonRpcException, check_exception2); - CHECK_EXCEPTION_TYPE( - SpecificationParser::GetProceduresFromFile("testspec3.json"), - JsonRpcException, check_exception2); - CHECK_EXCEPTION_TYPE( - SpecificationParser::GetProceduresFromFile("testspec4.json"), - JsonRpcException, check_exception2); - CHECK_EXCEPTION_TYPE(SpecificationParser::GetProceduresFromString("{}"), - JsonRpcException, check_exception2); - - CHECK_EXCEPTION_TYPE(SpecificationParser::GetProceduresFromString( - "[{\"name\":\"proc1\"},{\"name\":\"proc1\"}]"), - JsonRpcException, check_exception2); - CHECK_EXCEPTION_TYPE( - SpecificationParser::GetProceduresFromString( - "[{\"name\":\"proc1\", \"params\": {\"param1\": null}}]"), - JsonRpcException, check_exception2); - CHECK_EXCEPTION_TYPE(SpecificationParser::GetProceduresFromString( - "[{\"name\":\"proc1\", \"params\": 23}]"), - JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(SpecificationParser::GetProceduresFromFile("testspec1.json"), JsonRpcException, check_exception1); + CHECK_EXCEPTION_TYPE(SpecificationParser::GetProceduresFromFile("testspec2.json"), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(SpecificationParser::GetProceduresFromFile("testspec3.json"), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(SpecificationParser::GetProceduresFromFile("testspec4.json"), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(SpecificationParser::GetProceduresFromString("{}"), JsonRpcException, check_exception2); + + CHECK_EXCEPTION_TYPE(SpecificationParser::GetProceduresFromString("[{\"name\":\"proc1\"},{\"name\":\"proc1\"}]"), JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(SpecificationParser::GetProceduresFromString("[{\"name\":\"proc1\", \"params\": {\"param1\": null}}]"), JsonRpcException, + check_exception2); + CHECK_EXCEPTION_TYPE(SpecificationParser::GetProceduresFromString("[{\"name\":\"proc1\", \"params\": 23}]"), JsonRpcException, check_exception2); } TEST_CASE("test_specificationparser_success", TEST_MODULE) { - std::vector procs = - SpecificationParser::GetProceduresFromFile("testspec5.json"); + std::vector procs = SpecificationParser::GetProceduresFromFile("testspec5.json"); REQUIRE(procs.size() == 4); CHECK(procs[0].GetProcedureName() == "testmethod"); @@ -176,21 +151,13 @@ TEST_CASE("test_specificationparser_success", TEST_MODULE) { TEST_CASE("test_specificationwriter", TEST_MODULE) { vector procedures; - procedures.push_back(Procedure("testmethod1", PARAMS_BY_NAME, JSON_INTEGER, - "param1", JSON_INTEGER, "param2", JSON_REAL, - NULL)); - procedures.push_back(Procedure("testmethod2", PARAMS_BY_POSITION, - JSON_INTEGER, "param1", JSON_OBJECT, "param2", - JSON_ARRAY, NULL)); + procedures.push_back(Procedure("testmethod1", PARAMS_BY_NAME, JSON_INTEGER, "param1", JSON_INTEGER, "param2", JSON_REAL, NULL)); + procedures.push_back(Procedure("testmethod2", PARAMS_BY_POSITION, JSON_INTEGER, "param1", JSON_OBJECT, "param2", JSON_ARRAY, NULL)); - procedures.push_back(Procedure("testnotification1", PARAMS_BY_NAME, "param1", - JSON_BOOLEAN, "param2", JSON_STRING, NULL)); - procedures.push_back(Procedure("testnotification2", PARAMS_BY_POSITION, - "param1", JSON_INTEGER, "param2", JSON_STRING, - NULL)); + procedures.push_back(Procedure("testnotification1", PARAMS_BY_NAME, "param1", JSON_BOOLEAN, "param2", JSON_STRING, NULL)); + procedures.push_back(Procedure("testnotification2", PARAMS_BY_POSITION, "param1", JSON_INTEGER, "param2", JSON_STRING, NULL)); - procedures.push_back( - Procedure("testnotification3", PARAMS_BY_POSITION, NULL)); + procedures.push_back(Procedure("testnotification3", PARAMS_BY_POSITION, NULL)); Json::Value result = SpecificationWriter::toJsonValue(procedures); @@ -225,6 +192,5 @@ TEST_CASE("test_specificationwriter", TEST_MODULE) { CHECK(result[1]["returns"].isIntegral() == true); CHECK(SpecificationWriter::toFile("testspec.json", procedures) == true); - CHECK(SpecificationWriter::toFile("/a/b/c/testspec.json", procedures) == - false); + CHECK(SpecificationWriter::toFile("/a/b/c/testspec.json", procedures) == false); } diff --git a/src/test/test_connector_filedescriptor.cpp b/src/test/test_connector_filedescriptor.cpp index d3d77af5..186d7a1a 100644 --- a/src/test/test_connector_filedescriptor.cpp +++ b/src/test/test_connector_filedescriptor.cpp @@ -24,36 +24,34 @@ using namespace std; #define TEST_MODULE "[connector_filedescriptor]" namespace testfiledescriptorserver { -struct F { - FileDescriptorServer *server; - FileDescriptorClient *client; - MockClientConnectionHandler handler; - - F() { - pipe(c2sfd); - pipe(s2cfd); - server = new FileDescriptorServer(c2sfd[0], s2cfd[1]); - client = new FileDescriptorClient(s2cfd[0], c2sfd[1]); - server->SetHandler(&handler); - REQUIRE(server->StartListening()); - } - ~F() { - server->StopListening(); - delete server; - delete client; - close(c2sfd[0]); - close(c2sfd[1]); - close(s2cfd[0]); - close(s2cfd[1]); - } - - int c2sfd[2]; // Client to server fd - int s2cfd[2]; // Server to client fd -}; - -bool check_exception1(JsonRpcException const &ex) { - return ex.GetCode() == Errors::ERROR_CLIENT_CONNECTOR; -} + struct F { + FileDescriptorServer *server; + FileDescriptorClient *client; + MockClientConnectionHandler handler; + + F() { + pipe(c2sfd); + pipe(s2cfd); + server = new FileDescriptorServer(c2sfd[0], s2cfd[1]); + client = new FileDescriptorClient(s2cfd[0], c2sfd[1]); + server->SetHandler(&handler); + REQUIRE(server->StartListening()); + } + ~F() { + server->StopListening(); + delete server; + delete client; + close(c2sfd[0]); + close(c2sfd[1]); + close(s2cfd[0]); + close(s2cfd[1]); + } + + int c2sfd[2]; // Client to server fd + int s2cfd[2]; // Server to client fd + }; + + bool check_exception1(JsonRpcException const &ex) { return ex.GetCode() == Errors::ERROR_CLIENT_CONNECTOR; } } // namespace testfiledescriptorserver using namespace testfiledescriptorserver; @@ -124,8 +122,7 @@ TEST_CASE("test_filedescriptor_server_multiplestart", TEST_MODULE) { close(fds[1]); } -TEST_CASE("test_filedescriptor_server_input_fd_invalid_while_listening", - TEST_MODULE) { +TEST_CASE("test_filedescriptor_server_input_fd_invalid_while_listening", TEST_MODULE) { int c2sfd[2]; pipe(c2sfd); int s2cfd[2]; @@ -178,8 +175,7 @@ TEST_CASE("test_filedescriptor_server_output_fd_invalid", TEST_MODULE) { TEST_CASE("test_filedescriptor_client_output_fd_invalid", TEST_MODULE) { FileDescriptorClient client(2, 6); string result; - CHECK_EXCEPTION_TYPE(client.SendRPCMessage("foobar", result), - JsonRpcException, check_exception1); + CHECK_EXCEPTION_TYPE(client.SendRPCMessage("foobar", result), JsonRpcException, check_exception1); } TEST_CASE("test_filedescriptor_client_input_fd_invalid", TEST_MODULE) { @@ -193,8 +189,7 @@ TEST_CASE("test_filedescriptor_client_input_fd_invalid", TEST_MODULE) { // crashed. close(s2cfd[0]); string result; - CHECK_EXCEPTION_TYPE(client.SendRPCMessage("foobar", result), - JsonRpcException, check_exception1); + CHECK_EXCEPTION_TYPE(client.SendRPCMessage("foobar", result), JsonRpcException, check_exception1); close(c2sfd[1]); close(s2cfd[1]); close(c2sfd[0]); diff --git a/src/test/test_connector_http.cpp b/src/test/test_connector_http.cpp index 7e1df981..5d6a4fd7 100644 --- a/src/test/test_connector_http.cpp +++ b/src/test/test_connector_http.cpp @@ -31,28 +31,24 @@ using namespace std; #define TEST_MODULE "[connector_http]" namespace testhttpserver { -struct ServerFixture { - HttpServer server; - MockClientConnectionHandler handler; + struct ServerFixture { + HttpServer server; + MockClientConnectionHandler handler; - ServerFixture() : server(TEST_PORT) { server.SetHandler(&handler); } + ServerFixture() : server(TEST_PORT) { server.SetHandler(&handler); } - ~ServerFixture() { server.StopListening(); } -}; + ~ServerFixture() { server.StopListening(); } + }; -struct F : public ServerFixture { - HttpClient client; + struct F : public ServerFixture { + HttpClient client; - F() : client(CLIENT_URL) { server.StartListening(); } -}; + F() : client(CLIENT_URL) { server.StartListening(); } + }; -bool check_exception1(JsonRpcException const &ex) { - return ex.GetCode() == Errors::ERROR_CLIENT_CONNECTOR; -} + bool check_exception1(JsonRpcException const &ex) { return ex.GetCode() == Errors::ERROR_CLIENT_CONNECTOR; } -bool check_exception2(JsonRpcException const &ex) { - return ex.GetCode() == Errors::ERROR_RPC_INTERNAL_ERROR; -} + bool check_exception2(JsonRpcException const &ex) { return ex.GetCode() == Errors::ERROR_RPC_INTERNAL_ERROR; } } // namespace testhttpserver using namespace testhttpserver; @@ -68,8 +64,7 @@ TEST_CASE_METHOD(F, "test_http_success", TEST_MODULE) { TEST_CASE("test_http_client_error", TEST_MODULE) { HttpClient client("http://someinvalidurl/asdf"); string result; - CHECK_EXCEPTION_TYPE(client.SendRPCMessage("asdfasfwer", result), - JsonRpcException, check_exception1); + CHECK_EXCEPTION_TYPE(client.SendRPCMessage("asdfasfwer", result), JsonRpcException, check_exception1); } #ifndef __APPLE__ @@ -98,8 +93,7 @@ TEST_CASE_METHOD(ServerFixture, "test_http_client_bind_address", TEST_MODULE) { CHECK(result == "exampleresponse"); HttpClient client2(ALTERNATE_CLIENT_URL); - CHECK_EXCEPTION_TYPE(client2.SendRPCMessage("examplerequest", result), - JsonRpcException, check_exception1); + CHECK_EXCEPTION_TYPE(client2.SendRPCMessage("examplerequest", result), JsonRpcException, check_exception1); } #ifndef WIN32 @@ -118,16 +112,14 @@ TEST_CASE_METHOD(F, "test_http_client_timeout", TEST_MODULE) { handler.timeout = 20; client.SetTimeout(10); string result; - CHECK_EXCEPTION_TYPE(client.SendRPCMessage("Test", result), JsonRpcException, - check_exception1); + CHECK_EXCEPTION_TYPE(client.SendRPCMessage("Test", result), JsonRpcException, check_exception1); handler.timeout = 0; client.SetTimeout(10000); handler.response = "asdf"; client.SendRPCMessage("", result); CHECK(result == "asdf"); server.StopListening(); - CHECK_EXCEPTION_TYPE(client.SendRPCMessage("Test", result), JsonRpcException, - check_exception1); + CHECK_EXCEPTION_TYPE(client.SendRPCMessage("Test", result), JsonRpcException, check_exception1); } TEST_CASE("test_http_client_headers", TEST_MODULE) { @@ -201,8 +193,7 @@ TEST_CASE("test_http_server_endpoints", TEST_MODULE) { client2.SendRPCMessage("test", response); CHECK(response == "response2"); - CHECK_EXCEPTION_TYPE(client3.SendRPCMessage("test", response), - JsonRpcException, check_exception2); + CHECK_EXCEPTION_TYPE(client3.SendRPCMessage("test", response), JsonRpcException, check_exception2); client3.SetUrl("http://localhost:8383/handler2"); client3.SendRPCMessage("test", response); diff --git a/src/test/test_connector_redis.cpp b/src/test/test_connector_redis.cpp index 9a24ef14..e52c8fcd 100644 --- a/src/test/test_connector_redis.cpp +++ b/src/test/test_connector_redis.cpp @@ -29,44 +29,38 @@ using namespace std; #define TEST_MODULE "[connector_redis]" namespace testredisserver { -/////////////////////////////////////////////////////////////////////////// -// Prepare redis fixture -// -// This fixture shall: -// 1. Start up a redis-server in the backgroun -// 2. Create a standard RedisServer connection which can be used -// 3. Create a standard RedisClient connection which can be used -// 4. Create a hiredis connection which can also be used -// -struct F { - TestRedisServer redis_server; - redisContext *con; - RedisServer server; - RedisClient client; - MockClientConnectionHandler handler; - - F() - : redis_server(), server(TEST_HOST, TEST_PORT, TEST_QUEUE), - client(TEST_HOST, TEST_PORT, TEST_QUEUE) { - con = redisConnect(TEST_HOST, TEST_PORT); - server.SetHandler(&handler); - server.StartListening(); - client.SetTimeout(1); - } - ~F() { - redisFree(con); - server.StopListening(); - redis_server.Stop(); - } -}; - -bool check_exception1(JsonRpcException const &ex) { - return ex.GetCode() == Errors::ERROR_CLIENT_CONNECTOR; -} - -bool check_exception2(JsonRpcException const &ex) { - return ex.GetCode() == Errors::ERROR_RPC_INTERNAL_ERROR; -} + /////////////////////////////////////////////////////////////////////////// + // Prepare redis fixture + // + // This fixture shall: + // 1. Start up a redis-server in the backgroun + // 2. Create a standard RedisServer connection which can be used + // 3. Create a standard RedisClient connection which can be used + // 4. Create a hiredis connection which can also be used + // + struct F { + TestRedisServer redis_server; + redisContext *con; + RedisServer server; + RedisClient client; + MockClientConnectionHandler handler; + + F() : redis_server(), server(TEST_HOST, TEST_PORT, TEST_QUEUE), client(TEST_HOST, TEST_PORT, TEST_QUEUE) { + con = redisConnect(TEST_HOST, TEST_PORT); + server.SetHandler(&handler); + server.StartListening(); + client.SetTimeout(1); + } + ~F() { + redisFree(con); + server.StopListening(); + redis_server.Stop(); + } + }; + + bool check_exception1(JsonRpcException const &ex) { return ex.GetCode() == Errors::ERROR_CLIENT_CONNECTOR; } + + bool check_exception2(JsonRpcException const &ex) { return ex.GetCode() == Errors::ERROR_RPC_INTERNAL_ERROR; } } // namespace testredisserver using namespace testredisserver; @@ -95,8 +89,7 @@ TEST_CASE_METHOD(F, "test_redis_multiple", TEST_MODULE) { } TEST_CASE("test_redis_client_error", TEST_MODULE) { - CHECK_EXCEPTION_TYPE(RedisClient client(TEST_HOST, TEST_PORT + 1, TEST_QUEUE), - JsonRpcException, check_exception1); + CHECK_EXCEPTION_TYPE(RedisClient client(TEST_HOST, TEST_PORT + 1, TEST_QUEUE), JsonRpcException, check_exception1); } #ifdef __APPLE__ @@ -120,8 +113,7 @@ TEST_CASE_METHOD(F, "test_redis_client_ret_queue", TEST_MODULE) { CHECK(retqueue == TEST_QUEUE "_" RAND_SECOND); // Check behaviour when queue already exists - reply = (redisReply *)redisCommand(con, "LPUSH %s %s", - TEST_QUEUE "_" RAND_FIRST, "test"); + reply = (redisReply *)redisCommand(con, "LPUSH %s %s", TEST_QUEUE "_" RAND_FIRST, "test"); freeReplyObject(reply); srand(0); @@ -130,8 +122,7 @@ TEST_CASE_METHOD(F, "test_redis_client_ret_queue", TEST_MODULE) { // Check for a failure with the redis context redis_server.Stop(); - CHECK_EXCEPTION_TYPE(GetReturnQueue(con, TEST_QUEUE, retqueue), - JsonRpcException, check_exception1); + CHECK_EXCEPTION_TYPE(GetReturnQueue(con, TEST_QUEUE, retqueue), JsonRpcException, check_exception1); } TEST_CASE_METHOD(F, "test_redis_client_set_queue", TEST_MODULE) { @@ -168,15 +159,13 @@ TEST_CASE_METHOD(F, "test_redis_server_bad_request", TEST_MODULE) { redisReply *reply; - reply = (redisReply *)redisCommand(con, "LPUSH %s %s", queue.c_str(), - req1.c_str()); + reply = (redisReply *)redisCommand(con, "LPUSH %s %s", queue.c_str(), req1.c_str()); CHECK(handler.request == ""); freeReplyObject(reply); reply = (redisReply *)redisCommand(con, "DEL %s", queue.c_str()); freeReplyObject(reply); - reply = - (redisReply *)redisCommand(con, "SET %s %s", queue.c_str(), req1.c_str()); + reply = (redisReply *)redisCommand(con, "SET %s %s", queue.c_str(), req1.c_str()); CHECK(handler.request == ""); freeReplyObject(reply); reply = (redisReply *)redisCommand(con, "DEL %s", queue.c_str()); @@ -188,8 +177,7 @@ TEST_CASE_METHOD(F, "test_redis_client_timeout", TEST_MODULE) { client2.SetTimeout(1); string result; - CHECK_EXCEPTION_TYPE(client2.SendRPCMessage("examplerequest", result), - JsonRpcException, check_exception1); + CHECK_EXCEPTION_TYPE(client2.SendRPCMessage("examplerequest", result), JsonRpcException, check_exception1); } TEST_CASE_METHOD(F, "test_redis_server_longrequest", TEST_MODULE) { diff --git a/src/test/test_connector_tcpsocket.cpp b/src/test/test_connector_tcpsocket.cpp index a5260b81..65beafef 100644 --- a/src/test/test_connector_tcpsocket.cpp +++ b/src/test/test_connector_tcpsocket.cpp @@ -28,21 +28,19 @@ using namespace std; #define PORT 50012 namespace testtcpsocketserver { -struct F { - TcpSocketServer server; - TcpSocketClient client; - MockClientConnectionHandler handler; - - F() : server(IP, PORT), client(IP, PORT) { - server.SetHandler(&handler); - REQUIRE(server.StartListening()); - } - ~F() { server.StopListening(); } -}; - -bool check_exception1(JsonRpcException const &ex) { - return ex.GetCode() == Errors::ERROR_CLIENT_CONNECTOR; -} + struct F { + TcpSocketServer server; + TcpSocketClient client; + MockClientConnectionHandler handler; + + F() : server(IP, PORT), client(IP, PORT) { + server.SetHandler(&handler); + REQUIRE(server.StartListening()); + } + ~F() { server.StopListening(); } + }; + + bool check_exception1(JsonRpcException const &ex) { return ex.GetCode() == Errors::ERROR_CLIENT_CONNECTOR; } } // namespace testtcpsocketserver using namespace testtcpsocketserver; @@ -79,8 +77,7 @@ TEST_CASE("test_tcpsocket_client_invalid", TEST_MODULE) { // recompile tests and run tests // again. string result; - CHECK_EXCEPTION_TYPE(client.SendRPCMessage("foobar", result), - JsonRpcException, check_exception1); + CHECK_EXCEPTION_TYPE(client.SendRPCMessage("foobar", result), JsonRpcException, check_exception1); } #endif diff --git a/src/test/test_connector_unixdomainsocket.cpp b/src/test/test_connector_unixdomainsocket.cpp index 3621bf73..65bbec28 100644 --- a/src/test/test_connector_unixdomainsocket.cpp +++ b/src/test/test_connector_unixdomainsocket.cpp @@ -22,23 +22,21 @@ using namespace std; #define TEST_MODULE "[connector_unixdomainsocket]" namespace testunixdomainsocketserver { -struct F { - string filename; - UnixDomainSocketServer server; - UnixDomainSocketClient client; - MockClientConnectionHandler handler; - - F() : filename("/tmp/somedomainsocket"), server(filename), client(filename) { - remove(filename.c_str()); - server.SetHandler(&handler); - REQUIRE(server.StartListening()); - } - ~F() { server.StopListening(); } -}; - -bool check_exception1(JsonRpcException const &ex) { - return ex.GetCode() == Errors::ERROR_CLIENT_CONNECTOR; -} + struct F { + string filename; + UnixDomainSocketServer server; + UnixDomainSocketClient client; + MockClientConnectionHandler handler; + + F() : filename("/tmp/somedomainsocket"), server(filename), client(filename) { + remove(filename.c_str()); + server.SetHandler(&handler); + REQUIRE(server.StartListening()); + } + ~F() { server.StopListening(); } + }; + + bool check_exception1(JsonRpcException const &ex) { return ex.GetCode() == Errors::ERROR_CLIENT_CONNECTOR; } } // namespace testunixdomainsocketserver using namespace testunixdomainsocketserver; @@ -73,8 +71,7 @@ TEST_CASE("test_unixdomainsocket_server_multiplestart", TEST_MODULE) { TEST_CASE("test_unixdomainsocket_client_invalid", TEST_MODULE) { UnixDomainSocketClient client("tmp/someinvalidpath"); string result; - CHECK_EXCEPTION_TYPE(client.SendRPCMessage("foobar", result), - JsonRpcException, check_exception1); + CHECK_EXCEPTION_TYPE(client.SendRPCMessage("foobar", result), JsonRpcException, check_exception1); } #endif diff --git a/src/test/test_integration.cpp b/src/test/test_integration.cpp index 3085af2d..91be4900 100644 --- a/src/test/test_integration.cpp +++ b/src/test/test_integration.cpp @@ -44,23 +44,16 @@ std::string rand_alnum_str(std::string::size_type sz) { class StubServer : public AbstractStubServer { public: - StubServer(AbstractServerConnector &connector) - : AbstractStubServer(connector) {} + StubServer(AbstractServerConnector &connector) : AbstractStubServer(connector) {} virtual void notifyServer() {} - virtual std::string sayHello(const std::string &name) { - return string("Hello ") + name; - } + virtual std::string sayHello(const std::string &name) { return string("Hello ") + name; } virtual int addNumbers(int param1, int param2) { return param1 + param2; } - virtual double addNumbers2(double param1, double param2) { - return param1 + param2; - } + virtual double addNumbers2(double param1, double param2) { return param1 + param2; } - virtual bool isEqual(const std::string &str1, const std::string &str2) { - return str1 == str2; - } + virtual bool isEqual(const std::string &str1, const std::string &str2) { return str1 == str2; } virtual Json::Value buildObject(const std::string &name, int age) { Json::Value result; @@ -71,9 +64,7 @@ class StubServer : public AbstractStubServer { virtual std::string methodWithoutParameters() { return "foo"; } - virtual Json::Value calculate(const Json::Value &args) { - return Json::Value(args); - } + virtual Json::Value calculate(const Json::Value &args) { return Json::Value(args); } }; #ifdef HTTP_TESTING diff --git a/src/test/test_server.cpp b/src/test/test_server.cpp index c50f391c..cb993839 100644 --- a/src/test/test_server.cpp +++ b/src/test/test_server.cpp @@ -17,19 +17,19 @@ using namespace jsonrpc; using namespace std; namespace testserver { -struct F { - MockServerConnector c; - TestServer server; + struct F { + MockServerConnector c; + TestServer server; - F() : server(c) {} -}; + F() : server(c) {} + }; -struct F1 { - MockServerConnector c; - TestServer server; + struct F1 { + MockServerConnector c; + TestServer server; - F1() : server(c, JSONRPC_SERVER_V1) {} -}; + F1() : server(c, JSONRPC_SERVER_V1) {} + }; } // namespace testserver using namespace testserver; @@ -48,8 +48,7 @@ TEST_CASE_METHOD(F, "test_server_v2_method_success", TEST_MODULE) { CHECK(c.GetJsonResponse()["jsonrpc"].asString() == "2.0"); CHECK(c.GetJsonResponse().isMember("error") == false); - c.SetRequest( - "{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sub\",\"params\":[5,7]}"); + c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sub\",\"params\":[5,7]}"); CHECK(c.GetJsonResponse()["result"].asInt() == -2); CHECK(c.GetJsonResponse()["id"].asInt() == 1); CHECK(c.GetJsonResponse()["jsonrpc"].asString() == "2.0"); @@ -109,8 +108,7 @@ TEST_CASE_METHOD(F, "test_server_v2_invalidrequest", TEST_MODULE) { CHECK(c.GetJsonResponse().isMember("result") == false); // no method name - c.SetRequest( - "{\"jsonrpc\":\"2.0\", \"id\": 1,\"params\":{\"name\":\"Peter\"}}"); + c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1,\"params\":{\"name\":\"Peter\"}}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32600); CHECK(c.GetJsonResponse().isMember("result") == false); @@ -179,8 +177,7 @@ TEST_CASE_METHOD(F, "test_server_v2_method_error", TEST_MODULE) { CHECK(c.GetJsonResponse().isMember("result") == false); // userspace exception - c.SetRequest( - "{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"exceptionMethod\"}"); + c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"exceptionMethod\"}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32099); CHECK(c.GetJsonResponse()["error"]["message"] == "User exception"); CHECK(c.GetJsonResponse()["error"]["data"][0] == 33); @@ -385,31 +382,14 @@ TEST_CASE("test_server_abstractserver", TEST_MODULE) { MockServerConnector c; TestServer server(c, JSONRPC_SERVER_V1V2); - CHECK(server.bindAndAddNotification(Procedure("testMethod", PARAMS_BY_NAME, - JSON_STRING, "name", - JSON_STRING, NULL), - &TestServer::initCounter) == false); - CHECK(server.bindAndAddMethod(Procedure("initCounter", PARAMS_BY_NAME, - "value", JSON_INTEGER, NULL), - &TestServer::sayHello) == false); - - CHECK( - server.bindAndAddMethod(Procedure("testMethod", PARAMS_BY_NAME, - JSON_STRING, "name", JSON_STRING, NULL), - &TestServer::sayHello) == true); - CHECK( - server.bindAndAddMethod(Procedure("testMethod", PARAMS_BY_NAME, - JSON_STRING, "name", JSON_STRING, NULL), - &TestServer::sayHello) == false); - - CHECK(server.bindAndAddNotification(Procedure("testNotification", - PARAMS_BY_NAME, "value", - JSON_INTEGER, NULL), - &TestServer::initCounter) == true); - CHECK(server.bindAndAddNotification(Procedure("testNotification", - PARAMS_BY_NAME, "value", - JSON_INTEGER, NULL), - &TestServer::initCounter) == false); + CHECK(server.bindAndAddNotification(Procedure("testMethod", PARAMS_BY_NAME, JSON_STRING, "name", JSON_STRING, NULL), &TestServer::initCounter) == false); + CHECK(server.bindAndAddMethod(Procedure("initCounter", PARAMS_BY_NAME, "value", JSON_INTEGER, NULL), &TestServer::sayHello) == false); + + CHECK(server.bindAndAddMethod(Procedure("testMethod", PARAMS_BY_NAME, JSON_STRING, "name", JSON_STRING, NULL), &TestServer::sayHello) == true); + CHECK(server.bindAndAddMethod(Procedure("testMethod", PARAMS_BY_NAME, JSON_STRING, "name", JSON_STRING, NULL), &TestServer::sayHello) == false); + + CHECK(server.bindAndAddNotification(Procedure("testNotification", PARAMS_BY_NAME, "value", JSON_INTEGER, NULL), &TestServer::initCounter) == true); + CHECK(server.bindAndAddNotification(Procedure("testNotification", PARAMS_BY_NAME, "value", JSON_INTEGER, NULL), &TestServer::initCounter) == false); CHECK(server.StartListening() == true); CHECK(server.StopListening() == true); diff --git a/src/test/test_stubgenerator.cpp b/src/test/test_stubgenerator.cpp index b9b8ae8b..04e08818 100644 --- a/src/test/test_stubgenerator.cpp +++ b/src/test/test_stubgenerator.cpp @@ -24,21 +24,21 @@ using namespace jsonrpc; using namespace std; namespace teststubgen { -struct F { - FILE *stdout; - FILE *stderr; - vector stubgens; - vector procedures; - F() { - stdout = fopen("stdout.txt", "w"); - stderr = fopen("stderr.txt", "w"); - } - - ~F() { - fclose(stdout); - fclose(stderr); - } -}; + struct F { + FILE *stdout; + FILE *stderr; + vector stubgens; + vector procedures; + F() { + stdout = fopen("stdout.txt", "w"); + stderr = fopen("stderr.txt", "w"); + } + + ~F() { + fclose(stdout); + fclose(stderr); + } + }; } // namespace teststubgen using namespace teststubgen; @@ -47,58 +47,42 @@ using namespace teststubgen; TEST_CASE("test stubgen cppclient", TEST_MODULE) { stringstream stream; - vector procedures = - SpecificationParser::GetProceduresFromFile("testspec6.json"); - CPPClientStubGenerator stubgen("ns1::ns2::TestStubClient", procedures, - stream); + vector procedures = SpecificationParser::GetProceduresFromFile("testspec6.json"); + CPPClientStubGenerator stubgen("ns1::ns2::TestStubClient", procedures, stream); stubgen.generateStub(); string result = stream.str(); - CHECK(result.find("#ifndef JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBCLIENT_H_") != - string::npos); - CHECK(result.find("#define JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBCLIENT_H_") != - string::npos); + CHECK(result.find("#ifndef JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBCLIENT_H_") != string::npos); + CHECK(result.find("#define JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBCLIENT_H_") != string::npos); CHECK(result.find("namespace ns1") != string::npos); CHECK(result.find("namespace ns2") != string::npos); - CHECK(result.find("class TestStubClient : public jsonrpc::Client") != - string::npos); - CHECK(result.find("std::string test_method(const std::string& name) ") != - string::npos); - CHECK(result.find("void test_notification(const std::string& name) ") != - string::npos); + CHECK(result.find("class TestStubClient : public jsonrpc::Client") != string::npos); + CHECK(result.find("std::string test_method(const std::string& name) ") != string::npos); + CHECK(result.find("void test_notification(const std::string& name) ") != string::npos); CHECK(result.find("double test_method2(const Json::Value& object, const " "Json::Value& values) ") != string::npos); CHECK(result.find("void test_notification2(const Json::Value& object, const " "Json::Value& values) ") != string::npos); - CHECK(result.find("#endif //JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBCLIENT_H_") != - string::npos); + CHECK(result.find("#endif //JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBCLIENT_H_") != string::npos); CHECK(CPPHelper::class2Filename("ns1::ns2::TestClass") == "testclass.h"); } TEST_CASE("test stubgen cppserver", TEST_MODULE) { stringstream stream; - vector procedures = - SpecificationParser::GetProceduresFromFile("testspec6.json"); - CPPServerStubGenerator stubgen("ns1::ns2::TestStubServer", procedures, - stream); + vector procedures = SpecificationParser::GetProceduresFromFile("testspec6.json"); + CPPServerStubGenerator stubgen("ns1::ns2::TestStubServer", procedures, stream); stubgen.generateStub(); string result = stream.str(); - CHECK(result.find("#ifndef JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBSERVER_H_") != - string::npos); - CHECK(result.find("#define JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBSERVER_H_") != - string::npos); + CHECK(result.find("#ifndef JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBSERVER_H_") != string::npos); + CHECK(result.find("#define JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBSERVER_H_") != string::npos); CHECK(result.find("namespace ns1") != string::npos); CHECK(result.find("namespace ns2") != string::npos); CHECK(result.find("class TestStubServer : public " "jsonrpc::AbstractServer") != string::npos); - CHECK(result.find( - "virtual std::string test_method(const std::string& name) = 0;") != - string::npos); - CHECK(result.find( - "virtual void test_notification(const std::string& name) = 0;") != - string::npos); + CHECK(result.find("virtual std::string test_method(const std::string& name) = 0;") != string::npos); + CHECK(result.find("virtual void test_notification(const std::string& name) = 0;") != string::npos); CHECK(result.find("virtual double test_method2(const Json::Value& object, " "const Json::Value& values) = 0;") != string::npos); CHECK(result.find("virtual void test_notification2(const Json::Value& " @@ -106,8 +90,7 @@ TEST_CASE("test stubgen cppserver", TEST_MODULE) { CHECK(result.find("this->bindAndAddMethod(jsonrpc::Procedure(\"test.method\"," " jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_STRING, " "\"name\",jsonrpc::JSON_STRING, NULL), " - "&ns1::ns2::TestStubServer::test_methodI);") != - string::npos); + "&ns1::ns2::TestStubServer::test_methodI);") != string::npos); CHECK(result.find("inline virtual void test_notificationI(" "const Json::Value &request)") != string::npos); CHECK(result.find("inline virtual void test_methodI(" @@ -118,14 +101,12 @@ TEST_CASE("test stubgen cppserver", TEST_MODULE) { "Json::Value &response)") != string::npos); CHECK(result.find("inline virtual void testmethod6I(" "const Json::Value &/*request*/)") != string::npos); - CHECK(result.find("#endif //JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBSERVER_H_") != - string::npos); + CHECK(result.find("#endif //JSONRPC_CPP_STUB_NS1_NS2_TESTSTUBSERVER_H_") != string::npos); } TEST_CASE("test_stubgen_jsclient", TEST_MODULE) { stringstream stream; - vector procedures = - SpecificationParser::GetProceduresFromFile("testspec6.json"); + vector procedures = SpecificationParser::GetProceduresFromFile("testspec6.json"); JSClientStubGenerator stubgen("TestStubClient", procedures, stream); stubgen.generateStub(); string result = stream.str(); @@ -134,8 +115,7 @@ TEST_CASE("test_stubgen_jsclient", TEST_MODULE) { CHECK(result.find("TestStubClient.prototype.test_method = function(name, " "callbackSuccess, callbackError)") != string::npos); CHECK(result.find("TestStubClient.prototype.test_notification = " - "function(name, callbackSuccess, callbackError)") != - string::npos); + "function(name, callbackSuccess, callbackError)") != string::npos); CHECK(result.find("TestStubClient.prototype.test_method2 = function(object, " "values, callbackSuccess, callbackError)") != string::npos); CHECK(result.find("TestStubClient.prototype.test_notification2 = " @@ -147,24 +127,20 @@ TEST_CASE("test_stubgen_jsclient", TEST_MODULE) { TEST_CASE("test_stubgen_pyclient", TEST_MODULE) { stringstream stream; - vector procedures = - SpecificationParser::GetProceduresFromFile("testspec6.json"); + vector procedures = SpecificationParser::GetProceduresFromFile("testspec6.json"); PythonClientStubGenerator stubgen("TestStubClient", procedures, stream); stubgen.generateStub(); string result = stream.str(); CHECK(result.find("from jsonrpc_pyclient import client") != string::npos); CHECK(result.find("class TestStubClient(client.Client):") != string::npos); - CHECK(result.find("def __init__(self, connector, version='2.0'):") != - string::npos); + CHECK(result.find("def __init__(self, connector, version='2.0'):") != string::npos); CHECK(result.find("def test_method(self, name):") != string::npos); CHECK(result.find("def test_notification(self, name):") != string::npos); CHECK(result.find("def test_method2(self, object, values):") != string::npos); - CHECK(result.find("def test_notification2(self, object, values):") != - string::npos); + CHECK(result.find("def test_notification2(self, object, values):") != string::npos); - CHECK(PythonClientStubGenerator::class2Filename("TestClass") == - "testclass.py"); + CHECK(PythonClientStubGenerator::class2Filename("TestClass") == "testclass.py"); } TEST_CASE("test_stubgen_indentation", TEST_MODULE) { @@ -185,8 +161,7 @@ TEST_CASE("test_stubgen_indentation", TEST_MODULE) { TEST_CASE_METHOD(F, "test_stubgen_factory_help", TEST_MODULE) { const char *argv[2] = {"jsonrpcstub", "-h"}; - CHECK(StubGeneratorFactory::createStubGenerators( - 2, (char **)argv, procedures, stubgens, stdout, stderr) == true); + CHECK(StubGeneratorFactory::createStubGenerators(2, (char **)argv, procedures, stubgens, stdout, stderr) == true); CHECK(stubgens.empty() == true); CHECK(procedures.empty() == true); } @@ -194,8 +169,7 @@ TEST_CASE_METHOD(F, "test_stubgen_factory_help", TEST_MODULE) { TEST_CASE_METHOD(F, "test_stubgen_factory_version", TEST_MODULE) { const char *argv[2] = {"jsonrpcstub", "--version"}; - CHECK(StubGeneratorFactory::createStubGenerators( - 2, (char **)argv, procedures, stubgens, stdout, stderr) == true); + CHECK(StubGeneratorFactory::createStubGenerators(2, (char **)argv, procedures, stubgens, stdout, stderr) == true); CHECK(stubgens.empty() == true); CHECK(procedures.empty() == true); } @@ -203,8 +177,7 @@ TEST_CASE_METHOD(F, "test_stubgen_factory_version", TEST_MODULE) { TEST_CASE_METHOD(F, "test_stubgen_factory_error", TEST_MODULE) { const char *argv[2] = {"jsonrpcstub", "--cpp-client=TestClient"}; - CHECK(StubGeneratorFactory::createStubGenerators( - 2, (char **)argv, procedures, stubgens, stdout, stderr) == false); + CHECK(StubGeneratorFactory::createStubGenerators(2, (char **)argv, procedures, stubgens, stdout, stderr) == false); CHECK(stubgens.empty() == true); CHECK(procedures.empty() == true); @@ -212,20 +185,15 @@ TEST_CASE_METHOD(F, "test_stubgen_factory_error", TEST_MODULE) { vector procedures2; const char *argv2[2] = {"jsonrpcstub", "--cpxp-client=TestClient"}; - CHECK(StubGeneratorFactory::createStubGenerators(2, (char **)argv2, - procedures2, stubgens2, - stdout, stderr) == false); + CHECK(StubGeneratorFactory::createStubGenerators(2, (char **)argv2, procedures2, stubgens2, stdout, stderr) == false); CHECK(stubgens2.empty() == true); CHECK(procedures2.empty() == true); vector stubgens3; vector procedures3; - const char *argv3[3] = {"jsonrpcstub", "testspec1.json", - "--cpp-client=TestClient"}; + const char *argv3[3] = {"jsonrpcstub", "testspec1.json", "--cpp-client=TestClient"}; - CHECK(StubGeneratorFactory::createStubGenerators(3, (char **)argv3, - procedures3, stubgens3, - stdout, stderr) == false); + CHECK(StubGeneratorFactory::createStubGenerators(3, (char **)argv3, procedures3, stubgens3, stdout, stderr) == false); CHECK(stubgens3.empty() == true); CHECK(procedures3.empty() == true); } @@ -233,12 +201,9 @@ TEST_CASE_METHOD(F, "test_stubgen_factory_error", TEST_MODULE) { TEST_CASE_METHOD(F, "test_stubgen_factory_success", TEST_MODULE) { vector stubgens; vector procedures; - const char *argv[5] = {"jsonrpcstub", "testspec6.json", - "--js-client=TestClient", "--cpp-client=TestClient", - "--cpp-server=TestServer"}; + const char *argv[5] = {"jsonrpcstub", "testspec6.json", "--js-client=TestClient", "--cpp-client=TestClient", "--cpp-server=TestServer"}; - CHECK(StubGeneratorFactory::createStubGenerators( - 5, (char **)argv, procedures, stubgens, stdout, stderr) == true); + CHECK(StubGeneratorFactory::createStubGenerators(5, (char **)argv, procedures, stubgens, stdout, stderr) == true); CHECK(stubgens.size() == 3); CHECK(procedures.size() == 8); @@ -258,8 +223,7 @@ TEST_CASE_METHOD(F, "test_stubgen_factory_fileoverride", TEST_MODULE) { "--js-client-file=client.js", "-v"}; - CHECK(StubGeneratorFactory::createStubGenerators( - 9, (char **)argv, procedures, stubgens, stdout, stderr) == true); + CHECK(StubGeneratorFactory::createStubGenerators(9, (char **)argv, procedures, stubgens, stdout, stderr) == true); CHECK(stubgens.size() == 3); CHECK(procedures.size() == 8); StubGeneratorFactory::deleteStubGenerators(stubgens); diff --git a/src/test/testhttpserver.cpp b/src/test/testhttpserver.cpp index f14e521c..9c64db4f 100644 --- a/src/test/testhttpserver.cpp +++ b/src/test/testhttpserver.cpp @@ -14,9 +14,7 @@ using namespace jsonrpc; TestHttpServer::TestHttpServer(int port) : port(port) {} bool TestHttpServer::StartListening() { - this->daemon = - MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, this->port, NULL, NULL, - TestHttpServer::callback, this, MHD_OPTION_END); + this->daemon = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, this->port, NULL, NULL, TestHttpServer::callback, this, MHD_OPTION_END); return (this->daemon != NULL); } @@ -31,9 +29,7 @@ bool TestHttpServer::SendResponse(const std::string &response, void *addInfo) { return true; } -void TestHttpServer::SetResponse(const std::string &response) { - this->response = response; -} +void TestHttpServer::SetResponse(const std::string &response) { this->response = response; } std::string TestHttpServer::GetHeader(const std::string &key) { if (this->headers.find(key) != this->headers.end()) @@ -41,11 +37,8 @@ std::string TestHttpServer::GetHeader(const std::string &key) { return ""; } -TestHttpServer::MicroHttpdResult TestHttpServer::callback( - void *cls, MHD_Connection *connection, - const char *url, const char *method, - const char *version, const char *upload_data, - size_t *upload_data_size, void **con_cls) { +TestHttpServer::MicroHttpdResult TestHttpServer::callback(void *cls, MHD_Connection *connection, const char *url, const char *method, const char *version, + const char *upload_data, size_t *upload_data_size, void **con_cls) { (void)upload_data; (void)upload_data_size; (void)url; @@ -56,11 +49,8 @@ TestHttpServer::MicroHttpdResult TestHttpServer::callback( *con_cls = cls; _this->headers.clear(); } else { - MHD_get_connection_values(connection, MHD_HEADER_KIND, header_iterator, - cls); - struct MHD_Response *result = MHD_create_response_from_buffer( - _this->response.size(), (void *)_this->response.c_str(), - MHD_RESPMEM_MUST_COPY); + MHD_get_connection_values(connection, MHD_HEADER_KIND, header_iterator, cls); + struct MHD_Response *result = MHD_create_response_from_buffer(_this->response.size(), (void *)_this->response.c_str(), MHD_RESPMEM_MUST_COPY); MHD_add_response_header(result, "Content-Type", "application/json"); MHD_add_response_header(result, "Access-Control-Allow-Origin", "*"); MHD_queue_response(connection, MHD_HTTP_OK, result); @@ -70,9 +60,7 @@ TestHttpServer::MicroHttpdResult TestHttpServer::callback( return MHD_YES; } -TestHttpServer::MicroHttpdResult TestHttpServer::header_iterator( - void *cls, MHD_ValueKind kind, - const char *key, const char *value) { +TestHttpServer::MicroHttpdResult TestHttpServer::header_iterator(void *cls, MHD_ValueKind kind, const char *key, const char *value) { (void)kind; TestHttpServer *_this = static_cast(cls); _this->headers[key] = value; diff --git a/src/test/testhttpserver.h b/src/test/testhttpserver.h index 8bf5dbd7..95a82a7b 100644 --- a/src/test/testhttpserver.h +++ b/src/test/testhttpserver.h @@ -16,36 +16,35 @@ namespace jsonrpc { - class TestHttpServer : public AbstractServerConnector - { - public: - TestHttpServer(int port); + class TestHttpServer : public AbstractServerConnector { + public: + TestHttpServer(int port); - virtual bool StartListening(); - virtual bool StopListening(); + virtual bool StartListening(); + virtual bool StopListening(); - bool virtual SendResponse(const std::string& response, - void* addInfo = NULL); + bool virtual SendResponse(const std::string &response, void *addInfo = NULL); - void SetResponse(const std::string &response); - std::string GetHeader(const std::string &key); + void SetResponse(const std::string &response); + std::string GetHeader(const std::string &key); - private: + private: #if MHD_VERSION >= 0x00097002 - typedef MHD_Result MicroHttpdResult; + typedef MHD_Result MicroHttpdResult; #else - typedef int MicroHttpdResult; + typedef int MicroHttpdResult; #endif - int port; - MHD_Daemon* daemon; - std::map headers; - std::string response; + int port; + MHD_Daemon *daemon; + std::map headers; + std::string response; - static MicroHttpdResult callback(void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **con_cls); + static MicroHttpdResult callback(void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, + const char *upload_data, size_t *upload_data_size, void **con_cls); - static MicroHttpdResult header_iterator (void *cls, enum MHD_ValueKind kind, const char *key, const char *value); - }; + static MicroHttpdResult header_iterator(void *cls, enum MHD_ValueKind kind, const char *key, const char *value); + }; } // namespace jsonrpc diff --git a/src/test/testredisserver.cpp b/src/test/testredisserver.cpp index f70398d8..90bec1e9 100644 --- a/src/test/testredisserver.cpp +++ b/src/test/testredisserver.cpp @@ -23,10 +23,7 @@ using namespace jsonrpc; #define REDIS_MAXLINES 255 #define REDIS_KEY "accept connections" -TestRedisServer::TestRedisServer() - : pid(0), maxlines(REDIS_MAXLINES), key(REDIS_KEY) { - this->Start(); -} +TestRedisServer::TestRedisServer() : pid(0), maxlines(REDIS_MAXLINES), key(REDIS_KEY) { this->Start(); } TestRedisServer::~TestRedisServer() { this->Stop(); } diff --git a/src/test/testredisserver.h b/src/test/testredisserver.h index b45c72bb..1ca7a8fa 100644 --- a/src/test/testredisserver.h +++ b/src/test/testredisserver.h @@ -15,68 +15,62 @@ namespace jsonrpc { + /** + * This class is used to spawn a redis-server in the background and is + * used to aid in running unit tests. + */ + class TestRedisServer { + public: + TestRedisServer(); + ~TestRedisServer(); + /** - * This class is used to spawn a redis-server in the background and is - * used to aid in running unit tests. + * This method is used to spawn a redis-server in the background. + * @return true on success, false for failure. */ - class TestRedisServer - { - public: - TestRedisServer(); - ~TestRedisServer(); - - /** - * This method is used to spawn a redis-server in the background. - * @return true on success, false for failure. - */ - bool Start(); - - - /** - * This method will kill the redis server when we are done with it. - * @return true on success, false for failure. - */ - bool Stop(); - - private: + bool Start(); - /** - * This is a helper method for Start. This should be called - * by the child process and will setup the pipes for communication and - * start the redis server. - * @param pipefd The pipe that will be used for communication. - */ - void StartProcess(int pipefd[2]); - - - /** - * This is a helper method for Start. This method is used to - * block until the redis-server has finished starting up. - * Uses key - Scan for this string to signal success. - * Uses maxlines - Scan this many lines before giving up. - * @param pipefd The pipe that will be used for communication. - * @return true on success, false for failure. - */ - bool WaitProcess(int pipefd[2]); + /** + * This method will kill the redis server when we are done with it. + * @return true on success, false for failure. + */ + bool Stop(); - private: + private: + /** + * This is a helper method for Start. This should be called + * by the child process and will setup the pipes for communication and + * start the redis server. + * @param pipefd The pipe that will be used for communication. + */ + void StartProcess(int pipefd[2]); - /** - * @brief The pid of the background redis-server. - */ - pid_t pid; + /** + * This is a helper method for Start. This method is used to + * block until the redis-server has finished starting up. + * Uses key - Scan for this string to signal success. + * Uses maxlines - Scan this many lines before giving up. + * @param pipefd The pipe that will be used for communication. + * @return true on success, false for failure. + */ + bool WaitProcess(int pipefd[2]); + private: + /** + * @brief The pid of the background redis-server. + */ + pid_t pid; - /** - * @brief The maximum number of lines to search for the key. - */ - unsigned int maxlines; + /** + * @brief The maximum number of lines to search for the key. + */ + unsigned int maxlines; - /** - * @brief The key string to indicate the server is ready - */ - std::string key; - }; + /** + * @brief The key string to indicate the server is ready + */ + std::string key; + }; } // namespace jsonrpc diff --git a/src/test/testserver.cpp b/src/test/testserver.cpp index 06248cc3..ec564641 100644 --- a/src/test/testserver.cpp +++ b/src/test/testserver.cpp @@ -13,56 +13,30 @@ using namespace std; using namespace jsonrpc; -TestServer::TestServer(AbstractServerConnector &connector, serverVersion_t type) - : AbstractServer(connector, type), cnt(-1) { - this->bindAndAddMethod(Procedure("sayHello", PARAMS_BY_NAME, JSON_STRING, - "name", JSON_STRING, NULL), - &TestServer::sayHello); - this->bindAndAddMethod( - Procedure("getCounterValue", PARAMS_BY_NAME, JSON_INTEGER, NULL), - &TestServer::getCounterValue); - this->bindAndAddMethod(Procedure("add", PARAMS_BY_NAME, JSON_INTEGER, - "value1", JSON_INTEGER, "value2", - JSON_INTEGER, NULL), - &TestServer::add); - this->bindAndAddMethod(Procedure("sub", PARAMS_BY_POSITION, JSON_INTEGER, - "value1", JSON_INTEGER, "value2", - JSON_INTEGER, NULL), - &TestServer::sub); - this->bindAndAddMethod( - Procedure("exceptionMethod", PARAMS_BY_POSITION, JSON_INTEGER, NULL), - &TestServer::exceptionMethod); +TestServer::TestServer(AbstractServerConnector &connector, serverVersion_t type) : AbstractServer(connector, type), cnt(-1) { + this->bindAndAddMethod(Procedure("sayHello", PARAMS_BY_NAME, JSON_STRING, "name", JSON_STRING, NULL), &TestServer::sayHello); + this->bindAndAddMethod(Procedure("getCounterValue", PARAMS_BY_NAME, JSON_INTEGER, NULL), &TestServer::getCounterValue); + this->bindAndAddMethod(Procedure("add", PARAMS_BY_NAME, JSON_INTEGER, "value1", JSON_INTEGER, "value2", JSON_INTEGER, NULL), &TestServer::add); + this->bindAndAddMethod(Procedure("sub", PARAMS_BY_POSITION, JSON_INTEGER, "value1", JSON_INTEGER, "value2", JSON_INTEGER, NULL), &TestServer::sub); + this->bindAndAddMethod(Procedure("exceptionMethod", PARAMS_BY_POSITION, JSON_INTEGER, NULL), &TestServer::exceptionMethod); - this->bindAndAddNotification( - Procedure("initCounter", PARAMS_BY_NAME, "value", JSON_INTEGER, NULL), - &TestServer::initCounter); - this->bindAndAddNotification(Procedure("incrementCounter", PARAMS_BY_NAME, - "value", JSON_INTEGER, NULL), - &TestServer::incrementCounter); - this->bindAndAddNotification(Procedure("initZero", PARAMS_BY_POSITION, NULL), - &TestServer::initZero); + this->bindAndAddNotification(Procedure("initCounter", PARAMS_BY_NAME, "value", JSON_INTEGER, NULL), &TestServer::initCounter); + this->bindAndAddNotification(Procedure("incrementCounter", PARAMS_BY_NAME, "value", JSON_INTEGER, NULL), &TestServer::incrementCounter); + this->bindAndAddNotification(Procedure("initZero", PARAMS_BY_POSITION, NULL), &TestServer::initZero); } -void TestServer::sayHello(const Json::Value &request, Json::Value &response) { - response = "Hello: " + request["name"].asString() + "!"; -} +void TestServer::sayHello(const Json::Value &request, Json::Value &response) { response = "Hello: " + request["name"].asString() + "!"; } -void TestServer::getCounterValue(const Json::Value &request, - Json::Value &response) { +void TestServer::getCounterValue(const Json::Value &request, Json::Value &response) { (void)request; response = cnt; } -void TestServer::add(const Json::Value &request, Json::Value &response) { - response = request["value1"].asInt() + request["value2"].asInt(); -} +void TestServer::add(const Json::Value &request, Json::Value &response) { response = request["value1"].asInt() + request["value2"].asInt(); } -void TestServer::sub(const Json::Value &request, Json::Value &response) { - response = request[0].asInt() - request[1].asInt(); -} +void TestServer::sub(const Json::Value &request, Json::Value &response) { response = request[0].asInt() - request[1].asInt(); } -void TestServer::exceptionMethod(const Json::Value &request, - Json::Value &response) { +void TestServer::exceptionMethod(const Json::Value &request, Json::Value &response) { (void)request; (void)response; Json::Value data; @@ -70,13 +44,9 @@ void TestServer::exceptionMethod(const Json::Value &request, throw JsonRpcException(-32099, "User exception", data); } -void TestServer::initCounter(const Json::Value &request) { - cnt = request["value"].asInt(); -} +void TestServer::initCounter(const Json::Value &request) { cnt = request["value"].asInt(); } -void TestServer::incrementCounter(const Json::Value &request) { - cnt += request["value"].asInt(); -} +void TestServer::incrementCounter(const Json::Value &request) { cnt += request["value"].asInt(); } void TestServer::initZero(const Json::Value &request) { (void)request; @@ -85,14 +55,10 @@ void TestServer::initZero(const Json::Value &request) { int TestServer::getCnt() { return cnt; } -bool TestServer::bindAndAddMethod( - const Procedure &proc, - AbstractServer::methodPointer_t pointer) { +bool TestServer::bindAndAddMethod(const Procedure &proc, AbstractServer::methodPointer_t pointer) { return AbstractServer::bindAndAddMethod(proc, pointer); } -bool TestServer::bindAndAddNotification( - const Procedure &proc, - AbstractServer::notificationPointer_t pointer) { +bool TestServer::bindAndAddNotification(const Procedure &proc, AbstractServer::notificationPointer_t pointer) { return AbstractServer::bindAndAddNotification(proc, pointer); } diff --git a/src/test/testserver.h b/src/test/testserver.h index 4f1ed214..b803cfb8 100644 --- a/src/test/testserver.h +++ b/src/test/testserver.h @@ -10,36 +10,35 @@ #ifndef JSONRPC_CPP_SERVER_H #define JSONRPC_CPP_SERVER_H -#include #include +#include + +// Methods +namespace jsonrpc { + class TestServer : public jsonrpc::AbstractServer { + public: + TestServer(jsonrpc::AbstractServerConnector &connector, jsonrpc::serverVersion_t type = jsonrpc::JSONRPC_SERVER_V2); + + void sayHello(const Json::Value &request, Json::Value &response); + void getCounterValue(const Json::Value &request, Json::Value &response); + void add(const Json::Value &request, Json::Value &response); + void sub(const Json::Value &request, Json::Value &response); + + void exceptionMethod(const Json::Value &request, Json::Value &response); + + // Notifications + void initCounter(const Json::Value &request); + void incrementCounter(const Json::Value &request); + void initZero(const Json::Value &request); + + int getCnt(); + + virtual bool bindAndAddMethod(const Procedure &proc, methodPointer_t pointer); + virtual bool bindAndAddNotification(const Procedure &proc, notificationPointer_t pointer); -//Methods -namespace jsonrpc -{ - class TestServer : public jsonrpc::AbstractServer - { - public: - TestServer(jsonrpc::AbstractServerConnector &connector, jsonrpc::serverVersion_t type = jsonrpc::JSONRPC_SERVER_V2); - - void sayHello(const Json::Value& request, Json::Value& response); - void getCounterValue(const Json::Value& request, Json::Value& response); - void add(const Json::Value& request, Json::Value& response); - void sub(const Json::Value& request, Json::Value& response); - - void exceptionMethod(const Json::Value& request, Json::Value& response); - - //Notifications - void initCounter(const Json::Value& request); - void incrementCounter(const Json::Value& request); - void initZero(const Json::Value& request); - - int getCnt(); - - virtual bool bindAndAddMethod(const Procedure& proc, methodPointer_t pointer); - virtual bool bindAndAddNotification(const Procedure& proc, notificationPointer_t pointer); - private: - int cnt; - }; -} + private: + int cnt; + }; +} // namespace jsonrpc #endif // JSONRPC_CPP_SERVER_H diff --git a/src/test/testspec1.json b/src/test/testspec1.json index ba72b208..3c7a0758 100644 --- a/src/test/testspec1.json +++ b/src/test/testspec1.json @@ -1 +1,2 @@ -{[..w334 +{[ + ..w334 diff --git a/src/test/testspec2.json b/src/test/testspec2.json index 773f554c..4e40a584 100644 --- a/src/test/testspec2.json +++ b/src/test/testspec2.json @@ -1,8 +1,8 @@ [ - { - "params": { - "name": "Peter" - }, - "returns": "Hello Peter" - } + { + "params": { + "name": "Peter" + }, + "returns": "Hello Peter" + } ] diff --git a/src/test/testspec3.json b/src/test/testspec3.json index db91915b..96397e32 100644 --- a/src/test/testspec3.json +++ b/src/test/testspec3.json @@ -1,8 +1,9 @@ [ - [ - "foo", { - "name": "Peter" - }, - "Hello Peter" - ] + [ + "foo", + { + "name": "Peter" + }, + "Hello Peter" + ] ] diff --git a/src/test/testspec4.json b/src/test/testspec4.json index 2300a699..9663802b 100644 --- a/src/test/testspec4.json +++ b/src/test/testspec4.json @@ -1,9 +1,9 @@ [ - { - "name": "", - "params": { - "name": "Peter" - }, - "returns": "Hello Peter" - } + { + "name": "", + "params": { + "name": "Peter" + }, + "returns": "Hello Peter" + } ] diff --git a/src/test/testspec5.json b/src/test/testspec5.json index b6eb4e10..cfbd2902 100644 --- a/src/test/testspec5.json +++ b/src/test/testspec5.json @@ -1,20 +1,42 @@ [ - { - "method": "testmethod", - "params": {"name": "myname"}, - "returns": "somestring" + { + "method": "testmethod", + "params": { + "name": "myname" }, - { - "notification": "testnotification", - "params": {"name": "myname"} - }, - { - "name": "testmethod2", - "params": {"values": [1,2,3], "object": {"a": "b"}}, - "returns": 33.2 + "returns": "somestring" + }, + { + "notification": "testnotification", + "params": { + "name": "myname" + } + }, + { + "name": "testmethod2", + "params": { + "values": [ + 1, + 2, + 3 + ], + "object": { + "a": "b" + } }, - { - "name": "testnotification2", - "params": {"values": [1,2,3], "object": {"a": "b"}} + "returns": 33.2 + }, + { + "name": "testnotification2", + "params": { + "values": [ + 1, + 2, + 3 + ], + "object": { + "a": "b" + } } + } ] diff --git a/src/test/testspec6.json b/src/test/testspec6.json index ab555059..4b50d9bc 100644 --- a/src/test/testspec6.json +++ b/src/test/testspec6.json @@ -1,37 +1,69 @@ [ - { - "method": "test.method", - "params": {"name": "myname"}, - "returns": "somestring" + { + "method": "test.method", + "params": { + "name": "myname" }, - { - "notification": "test.notification", - "params": {"name": "myname"} - }, - { - "name": "test.method2", - "params": {"values": [1,2,3], "object": {"a": "b"}}, - "returns": 33.2 - }, - { - "name": "test.notification2", - "params": {"values": [1,2,3], "object": {"a": "b"}} - }, - { - "name": "testmethod3", - "params": [[], {}, 32.2], - "returns": {} - }, - { - "name": "testmethod4", - "params": [[1], {}, 32.2], - "returns": [] - }, - { - "name": "testmethod5", - "returns": [] + "returns": "somestring" + }, + { + "notification": "test.notification", + "params": { + "name": "myname" + } + }, + { + "name": "test.method2", + "params": { + "values": [ + 1, + 2, + 3 + ], + "object": { + "a": "b" + } }, - { - "name": "testmethod6" + "returns": 33.2 + }, + { + "name": "test.notification2", + "params": { + "values": [ + 1, + 2, + 3 + ], + "object": { + "a": "b" + } } + }, + { + "name": "testmethod3", + "params": [ + [], + {}, + 32.2 + ], + "returns": {} + }, + { + "name": "testmethod4", + "params": [ + [ + 1 + ], + {}, + 32.2 + ], + "returns": [] + }, + { + "name": "testmethod5", + "returns": [] + }, + { + "name": "testmethod6" + } ]