pax_global_header00006660000000000000000000000064127525646740014534gustar00rootroot0000000000000052 comment=a5bc3de024b78f0f8cab28416e402871708dfa92 libjson-rpc-cpp-0.7.0/000077500000000000000000000000001275256467400145425ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/.gitignore000066400000000000000000000003461275256467400165350ustar00rootroot00000000000000# osx noise .DS_Store profile # xcode noise build/* *.mode1 *.mode1v3 *.mode2v3 *.perspective *.perspectivev3 *.pbxuser *.xcworkspace xcuserdata # svn & cvs .svn CVS reports/* doc/html CMakeLists.txt.user* src/examples/gen/* *~ libjson-rpc-cpp-0.7.0/.travis.yml000066400000000000000000000030561275256467400166570ustar00rootroot00000000000000language: cpp before_install: - sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y - sudo apt-get update -qq - sudo apt-get install -qq libcurl4-openssl-dev libjsoncpp-dev libargtable2-dev libgnutls-dev libgcrypt11-dev valgrind wget gcc-4.8 g++-4.8 - wget http://ftp.gnu.org/gnu/libmicrohttpd/libmicrohttpd-0.9.44.tar.gz - tar -xvf libmicrohttpd-0.9.44.tar.gz - cd libmicrohttpd-0.9.44 - ./configure && make - sudo make install && sudo ldconfig - cd .. && sudo rm -rf libmicrohttpd-0.9.44 - sudo pip install cpp-coveralls - sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y - sudo apt-get update -qq - if [ "$CXX" = "g++" ]; then sudo apt-get install -qq g++-4.8; fi - if [ "$CXX" = "g++" ]; then export CXX="g++-4.8" CC="gcc-4.8"; fi install: - if [ "$CXX" = "g++" ]; then export CXX="g++-4.8" CC="gcc-4.8"; fi env: - HTTP_SERVER=YES HTTP_CLIENT=YES COMPILE_STUBGEN=YES compiler: - gcc script: - mkdir -p build && cd build - cmake -DCMAKE_BUILD_TYPE=Debug -DHTTP_CLIENT=${HTTP_CLIENT} -DHTTP_SERVER=${HTTP_SERVER} -DCOMPILE_STUBGEN=${COMPILE_STUBGEN} .. - make - make test - sudo make install && sudo ldconfig - g++ ../src/examples/simpleclient.cpp -ljsonrpccpp-client -ljsoncpp -ljsonrpccpp-common -lcurl -o sampleclient - g++ ../src/examples/simpleserver.cpp -ljsonrpccpp-server -ljsoncpp -ljsonrpccpp-common -lmicrohttpd -o sampleserver - sudo make uninstall after_success: - cd .. - coveralls -e src/test -e src/examples -e cmake -e /usr/include -e build/CMakeFiles -E '.*\.h' -E 'libmicrohttpd.*' libjson-rpc-cpp-0.7.0/AUTHORS.md000066400000000000000000000036511275256467400162160ustar00rootroot00000000000000Peter Spiess-Knafl + core library + cmake build system + stubgenerator *Notes about this list:* I try to update this list regularly, but sometimes I just forget. If I happen to oversee someones contributions, please raise an issue for that and sorry in advance. For an always up to date genarated list, see at the [GitHub contributors list](https://github.com/cinemast/libjson-rpc-cpp/graphs/contributors). Feature contributions (chronological order) =========================================== Joegen Baclor + automake/autoconf support + RPM packaging Bertrand Cachet + adapted build file for opt out of HTTP connectors + various bugfixes and support Marc Trudel + extended HTTP client connector Yuriy Syrovetskiy + added user supplied error blocks Veselin Rachev + added HTTP OPTIONS request support Marek Kotewicz + msvc support Alexandre Poirot + added client and server connectors that use Unix Domain Sockets + adapted build file to generate pkg-config file for this lib. + added client and server connectors that use Tcp Sockets on Linux and Windows (uses native socket and thread API on each OS) Bugfixes (chronological order) ============================== Emilien Kenler + bugfixes in HTTP client connector kaidokert + bugfixes in parameter handling Nozomu Kaneko + bugfixes in batch requests caktoux + bugfixes in build system Julien Jorge + bugfixes in batch requests Pascal Heijnsdijk + Htttp Client timeout bugfix and memory leak. Kasper Laudrup + Code reviews Erik Lundin + bugfix in cpp-server stubgen + bugfix for gcc 4.7 compatibility Michał Górny + bugfixes in the build system libjson-rpc-cpp-0.7.0/CHANGELOG.md000066400000000000000000000111001275256467400163440ustar00rootroot00000000000000Changes in v0.7.0 ----------------- - Change: Requiring C++11 support (gcc >= 4.8) - Fix: armhf compatibility - Fix: Invalid client id field handling (removed int only check) - Fix: Security issues in unixdomainsocket connectors - Fix: Missing CURL include directive - Fix: Parallel build which failed due to failing CATCH dependency - Fix: Handling 64-bit ids - Fix: Invalid parameter check - Fix: Invalid pointer handling in HTTP-Server - NEW: HttpServer can now be configured to listen localhost only - NEW: TCP Server + Client connectors Changes in v0.6.0 ----------------- - NEW: pkg-config files for all shared libraries - NEW: UNIX Socket client + server connector - NEW: multiarch support - Change: unit testing framework to catch - Change: allow disabling shared library build - Change: split out shared/static library for stubgenerator Changes in v0.5.0 ----------------- - Added `--version` option to jsonrpcstub. - Added msvc support. - Added data field support for JsonRpcException. - Added contributions guide: https://github.com/cinemast/libjson-rpc-cpp#contributions - HttpClient uses Http Keep-Alive, which improves performance drastically. - Added multiarch support. - Fixed building tests with examples disabled. - Made static library build optional (via `BUILD_STATIC_LIBS`). - Fixed unnecessary rebuilds of stubs on each `make` call. Changes in v0.4.2 ----------------- - Fix of spelling mistakes. - Use CMAKE versioning in manpage. - Improving include scheme of jsoncpp. - Bugfix in HttpServer with Threading option in SSL startup. Changes in v0.4.1 ----------------- - Added coverity scan support - [Added API compatibility report](http://upstream.rosalinux.ru/versions/libjson-rpc-cpp.html) - Improved manpage - Extended Stubgenerator for protocol switches (JSON-RPC 1.0 & 2.0) Changes in v0.4 --------------- - Memory leak fixes - Switched Http Server to libmicrohttpd - Added full WIN32 build support - Improved test coverage (100% line coverage) - Added JavaScript client stub support - Removed TCP Client/Server implementation due to security and codestyle problems. - Finally removed dirty pointer stuff in bindAndAddX() methods. - Using call by value in generated stubs for primitive data types. Changes in v0.3.2 ----------------- - Bugfixes - Additional testcases for client + server -> higher testcoverage - JSON-RPC 1 Client + Server support - Refactorings in server for JSON-RPC 1 support - Hiding irrelevant API headers from installation - Renamed AbstractClientConnector to IClientConnector (please regenearte your client stubs after upgrading) - Reactivated dev/testcoverage.sh to measure testcoverage. Changes in v0.3.1 ----------------- - Bugfixes - Changed SOVERSION - Added experimental Javascript client to stubgenerator - Adapted HTTP Server to enable CORS. Changes in v0.3 --------------- - Split up server and client into separate libraries - Lot's of refactorings in the build system and stubgenerator. - Added namespace/package support for generated stub classes. - libjson-cpp is no longer directly embedded. - Simplified spec format: a procedure specification without `return` field is a notification. - Introduced a boost-test based unit testing suite, which makes testing more flexible. - Added CMake options to enable/disable Stubgenerator, Examples, Connectors and Testsuite. - Removed Autotools support (because of all the changes in this release). - Bugfix: renamed .so files to avoid collisions with makerbot's libjsonrpc. - Bugfix: Invalid Batchcalls in Client and Server caused runtime exceptions. Changes in v0.2.1 ----------------- - Added support for positional parameters. (see at [example specification](https://github.com/cinemast/libjson-rpc-cpp/blob/master/src/example/spec.json) how to declare them) Changes in v0.2 --------------- - Minor bugfixes. - Refactored architecture. - stub generator for client and server. - removed mandatory configuration files (making it more compatible for embedded use cases). - Introduced SpecificationWriter to generate Specifications from RPC-Server definitions. - Introduced SpecificationParser to parse a Specification file and generate Methods for the RPC-Server. - Updated JsonCPP library - Update Mongoose library - Enable SSL Support (provided by mongoose) - Introduced automated testing after build phase (using `make test`) - Embedding dependent libraries (to avoid naming conflicts) Known issues ------------- - Under Ubuntu 12.04 SSL support is not enabled in the libmicrohttpd-dev package that is provided by ubuntu. Look at the [.travis.yml](https://github.com/cinemast/libjson-rpc-cpp/blob/develop/.travis.yml) file to see how I cope with this. libjson-rpc-cpp-0.7.0/CMakeLists.txt000066400000000000000000000075421275256467400173120ustar00rootroot00000000000000cmake_minimum_required(VERSION 2.8) project(libjson-rpc-cpp) # list command no longer ignores empty elements cmake_policy(SET CMP0007 NEW) cmake_policy(SET CMP0012 NEW) if (${CMAKE_MAJOR_VERSION} GREATER 2) # old policy do not use MACOSX_RPATH cmake_policy(SET CMP0042 OLD) endif() set(MAJOR_VERSION 0) set(MINOR_VERSION 7) set(PATCH_VERSION 0) set(SO_VERSION 0) set(BUILD_SHARED_LIBS YES CACHE BOOL "Build shared libraries") set(BUILD_STATIC_LIBS NO CACHE BOOL "Build static libraries") set(LIB_SUFFIX "" CACHE STRING "Suffix for library directory (32/64)") if (NOT BUILD_SHARED_LIBS AND NOT BUILD_STATIC_LIBS) message(FATAL_ERROR "Both BUILD_SHARED_LIBS and BUILD_STATIC_LIBS are disabled") endif() # defaults for modules that can be enabled/disabled if(UNIX) set(UNIX_DOMAIN_SOCKET_SERVER YES CACHE BOOL "Include Unix Domain Socket server") set(UNIX_DOMAIN_SOCKET_CLIENT YES CACHE BOOL "Include Unix Domain Socket client") endif(UNIX) set(TCP_SOCKET_SERVER NO CACHE BOOL "Include Tcp Socket server") set(TCP_SOCKET_CLIENT NO CACHE BOOL "Include Tcp Socket client") set(HTTP_SERVER YES CACHE BOOL "Include HTTP server using libmicrohttpd") set(HTTP_CLIENT YES CACHE BOOL "Include HTTP client support using curl") set(COMPILE_TESTS YES CACHE BOOL "Compile test framework") set(COMPILE_STUBGEN YES CACHE BOOL "Compile the stubgenerator") set(COMPILE_EXAMPLES YES CACHE BOOL "Compile example programs") # print actual settings if(UNIX) message(STATUS "UNIX_DOMAIN_SOCKET_SERVER: ${UNIX_DOMAIN_SOCKET_SERVER}") message(STATUS "UNIX_DOMAIN_SOCKET_CLIENT: ${UNIX_DOMAIN_SOCKET_CLIENT}") endif(UNIX) message(STATUS "TCP_SOCKET_SERVER: ${TCP_SOCKET_SERVER}") message(STATUS "TCP_SOCKET_CLIENT: ${TCP_SOCKET_CLIENT}") message(STATUS "HTTP_SERVER: ${HTTP_SERVER}") message(STATUS "HTTP_CLIENT: ${HTTP_CLIENT}") if(UNIX) message(STATUS "UNIXDOMAINSOCKET_SERVER: ${UNIX_DOMAIN_SOCKET_SERVER}") message(STATUS "UNIXDOMAINSOCKET_CLIENT: ${UNIX_DOMAIN_SOCKET_CLIENT}") endif(UNIX) message(STATUS "COMPILE_TESTS: ${COMPILE_TESTS}") message(STATUS "COMPILE_STUBGEN: ${COMPILE_STUBGEN}") message(STATUS "COMPILE_EXAMPLES: ${COMPILE_EXAMPLES}") # setup directory where we should look for cmake files set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake/") # setup compiler settings && dependencies include(CMakeCompilerSettings) include(CMakeDependencies) # setup output directories set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin") set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") if (WIN32) set(CMAKE_INSTALL_PREFIX ${PROJECT_BINARY_DIR}/dist) endif() # setup global include_directories (for backwards compatibility) include_directories("${CMAKE_BINARY_DIR}/gen/") include_directories("${CMAKE_BINARY_DIR}/gen/jsonrpccpp/common") # the core framework add_subdirectory(src/jsonrpccpp) #the stubgenerator if (COMPILE_STUBGEN) add_subdirectory(src/stubgenerator) endif () # setup examples if (COMPILE_EXAMPLES) add_subdirectory(src/examples) endif() # setup test suite if (COMPILE_TESTS) enable_testing(true) add_subdirectory(src/test) endif() # create documentation if (DOXYGEN_FOUND) file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/doc) message(STATUS "Found doxygen: ${DOXYGEN_EXECUTABLE}") configure_file("${PROJECT_SOURCE_DIR}/doc/doxyfile.in" "${CMAKE_BINARY_DIR}/Doxyfile" @ONLY) add_custom_target(doc ${DOXYGEN_EXECUTABLE} ${CMAKE_BINARY_DIR}/Doxyfile WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/doc COMMENT "Generating API documentation") endif(DOXYGEN_FOUND) # setup uninstall target configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/cmake/cmake_uninstall.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" IMMEDIATE @ONLY ) add_custom_target( uninstall COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake ) # packaging stuff include(CMakePackaging) libjson-rpc-cpp-0.7.0/LICENSE.txt000066400000000000000000000020661275256467400163710ustar00rootroot00000000000000Copyright (C) 2011-2014 Peter Spiess-Knafl Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. libjson-rpc-cpp-0.7.0/README.md000066400000000000000000000245361275256467400160330ustar00rootroot00000000000000[![Build Status](https://travis-ci.org/cinemast/libjson-rpc-cpp.png?branch=master)](https://travis-ci.org/cinemast/libjson-rpc-cpp) [![Coverage Status](https://coveralls.io/repos/cinemast/libjson-rpc-cpp/badge.png?branch=develop)](https://coveralls.io/r/cinemast/libjson-rpc-cpp?branch=develop) [![Coverity Status](https://scan.coverity.com/projects/3169/badge.svg?flat=1)](https://scan.coverity.com/projects/3169) libjson-rpc-cpp =============== This framework provides cross platform JSON-RPC (remote procedure call) support for C++. It is fully JSON-RPC [2.0 & 1.0 compatible](http://www.jsonrpc.org/specification). ![libjson-rpc-cpp logo](https://github.com/cinemast/libjson-rpc-cpp/blob/master/dev/artwork/logo.png?raw=true) **5 good reasons for using libjson-rpc-cpp in your next RPC project** - Full JSON-RPC 2.0 & 1.0 Client and Server Support. - jsonrpcstub - a tool that generates stub-classes for your JSON-RPC client AND server applications. - Ready to use HTTP + TCP server and client to provide simple interfaces for your JSON-RPC application. - Cross platform build support and [precompiled binaries for WIN32](http://spiessknafl.at/libjson-rpc-cpp). - Super liberal [MIT-License](http://en.wikipedia.org/wiki/MIT_License). **Other good reasons to use libjson-rpc-cpp** - Easy to use [cmake](http://www.cmake.org) cross platform build system. - Clean and simple architecture, which makes it easy to extend. - Tested under MacOS X (10.9), GNU/Linux (Debian 8 64-bit), Windows 7 (MinGW32) and Raspbian Wheezy (armhf). - Automated testing using `make test`. - Useful Examples provided. e.g. XBMC Remote using json-rpc client part and stub generator. - The stubgenerator currently supports C++ and JavaScript. Overview ========= ![libjson-rpc-cpp logo](https://github.com/cinemast/libjson-rpc-cpp/blob/develop/dev/artwork/overview.png?raw=true) Install the framework ===================== **Debian (stretch) and Ubuntu (15.10 or later)** ```sh sudo apt-get install libjsonrpccpp-dev libjsonrpccpp-tools ``` **Arch Linux** For Arch Linux there is a [PKGBUILD provided in the AUR](https://aur.archlinux.org/packages/libjson-rpc-cpp/). ```sh sudo aura -A libjson-rpc-cpp ``` **Gentoo Linux** ```sh sudo emerge dev-cpp/libjson-rpc-cpp ``` **Mac OS X** For OS X a [Brew](http://brew.sh) package is available: ```sh brew install libjson-rpc-cpp ``` **Windows** There is a ready to use compiled package [here](http://spiessknafl.at/libjson-rpc-cpp). Just download execute the installer EXE. Build from source ================= Install the dependencies ------------------------ - [libcurl](http://curl.haxx.se/) - [libmicrohttpd](http://www.gnu.org/software/libmicrohttpd/) - [libjsoncpp](https://github.com/open-source-parsers/jsoncpp) - [libargtable](http://argtable.sourceforge.net/) - [cmake](http://www.cmake.org/) **UNIX** For Debian and Arch GNU/Linux based systems, all dependencies are available via the package manager. For OS X all dependencies are available in [Brew](http://brew.sh) **Windows** - Download the precompiled dependencies form [here](https://spiessknafl.at/libjson-rpc-cpp/libjson-rpc-cpp_win32-deps.zip). - Extract it into the cloned repository, so that there is a `win32-deps` folder in the root project directory. Build ----- ```sh git clone git://github.com/cinemast/libjson-rpc-cpp.git mkdir -p libjson-rpc-cpp/build cd libjson-rpc-cpp/build cmake .. && make sudo make install sudo ldconfig #only required for linux ``` That's it! If you are not happy with it, simply uninstall it from your system using (inside the build the directory): ```sh sudo make uninstall ``` **Build options:** Default configuration should be fine for most systems, but here are available compilation flags: - `-DCOMPILE_TESTS=NO` disables unit test suite. - `-DCOMPILE_STUBGEN=NO` disables building the stubgenerator. - `-DCOMPILE_EXAMPLES=NO` disables examples. - `-DHTTP_SERVER=NO` disable the libmicrohttpd webserver. - `-DHTTP_CLIENT=NO` disable the curl client. - `-DUNIX_DOMAIN_SOCKET_SERVER=NO` disable the unix domain socket server connector. - `-DUNIX_DOMAIN_SOCKET_CLIENT=NO` disable the unix domain socket client connector. - `-DTCP_SOCKET_SERVER=NO` disable the tcp socket server connector. - `-DTCP_SOCKET_CLIENT=NO` disable the tcp socket client connector. Using the framework =================== This example will show the most simple way to create a rpc server and client. If you only need the server, ignore step 4. If you only need the client, ignore step 3. You can find all resources of this sample in the `src/examples` directory of this repository. ### Step 1: Writing the specification file ### ```json [ { "name": "sayHello", "params": { "name": "Peter" }, "returns" : "Hello Peter" }, { "name" : "notifyServer" } ] ``` The type of a return value or parameter is defined by the literal assigned to it. In this example you can see how to specify methods and notifications. ### Step 2: Generate the stubs for client and server ### Call jsonrpcstub: ```sh jsonrpcstub spec.json --cpp-server=AbstractStubServer --cpp-client=StubClient ``` This generates a serverstub and a clientstub class. ### Step 3: implement the abstract server stub ### Extend the abstract server stub and implement all pure virtual (abstract) methods defined in `spec.json`. ```cpp #include "abstractstubserver.h" #include using namespace jsonrpc; using namespace std; class MyStubServer : public AbstractStubServer { public: MyStubServer(AbstractServerConnector &connector); virtual void notifyServer(); virtual std::string sayHello(const std::string& name); }; MyStubServer::MyStubServer(AbstractServerConnector &connector) : AbstractStubServer(connector) { } void MyStubServer::notifyServer() { cout << "Server got notified" << endl; } string MyStubServer::sayHello(const string &name) { return "Hello " + name; } int main() { HttpServer httpserver(8383); MyStubServer s(httpserver); s.StartListening(); getchar(); s.StopListening(); return 0; } ``` In the main function the concrete server is instantiated and started. That is all for the server. Any JSON-RPC 2.0 compliant client can now connect to your server. Compile the server with: ```sh g++ main.cpp -ljsoncpp -lmicrohttpd -ljsonrpccpp-common -ljsonrpccpp-server -o sampleserver ``` ### Step 4: Create the client application ```cpp #include #include "stubclient.h" #include using namespace jsonrpc; using namespace std; int main() { HttpClient httpclient("http://localhost:8383"); StubClient c(httpclient); try { cout << c.sayHello("Peter") << endl; c.notifyServer(); } catch (JsonRpcException e) { cerr << e.what() << endl; } } ``` Compile the client with: ```sh g++ main.cpp -ljsoncpp -lcurl -ljsonrpccpp-common -ljsonrpccpp-client -o sampleclient ``` References ========== - [NASA Ames Research Center](http://www.nasa.gov/centers/ames/home/): use it to obtain aircraft state information from an aircraft simulator. - [LaseShark 3D Printer](https://github.com/macpod/lasershark_3dp): used to control the firmware of the 3D printer. - [cpp-ethereum](https://github.com/ethereum/cpp-ethereum): a distributed computing framework. - [mage-sdk-cpp](https://github.com/mage/mage-sdk-cpp): a game engine. - [bitcodin](http://www.bitmovin.net): a scalable cloud based video transcoding platform. - [wgslib](http://wgslib.com/): A web geostatistics library. - [bitcoin-api-cpp](https://github.com/minium/bitcoin-api-cpp): a C++ interface to bitcoin. - [NIT DASH Content Server](http://www.nit.eu/offer/research-projects-products/334-http2dash): Dynamic Adaptive Streaming over HTTP server. If you use this library and find it useful, I would be very pleased if you let me know about it. Developer Information ===================== Contributions ------------- Contributions of any kind are always very welcome. Here are some suggestions: - Bugreports - Bugfixes - Extending documentation (especially doxygen) - Suggestion of new features - New features: - Adding new connectors. - Adding new languages to the stubgenerator. **Guidelines / Conventions** We do not want to prevent you from contributing by having too strict guidelines. If you have ideas for improvement, just do it your way, rather than doing it not at all. Anyway here is a list of how we would prefer your contributions: - Issues: - Use the issue tracker on github to report bugs or improvements. - Please avoid sending me mails directly, as this is not visible to others. - Please close issues on your own if you think a problem has been dealt with. - Code contributions: - Please raise a pull-request against the develop branch. - If you add features, please keep the test-coverage at 100% and document them (doxygen, manpage, etc.). - If you fix a bug, please refer the issue in the [commit message](https://help.github.com/articles/closing-issues-via-commit-messages/). - Please make sure that the travis-ci build passes (you will get notified if you raise a pull-request). - Add yourself to the AUTHORS.md. - Use 4 spaces instead of tabs. Mailing list ------------ [libjsonrpccpp-devel@lists.sourceforge.net](https://lists.sourceforge.net/lists/listinfo/libjsonrpccpp-devel) Roadmap for next release ------------------------ - Generate client stubs for other languages. - Extend doxygen documentation. Changelogs ---------- Changelogs can be found [here](https://github.com/cinemast/libjson-rpc-cpp/blob/master/CHANGELOG.md). API compatibility ----------------- We do our best to keep the API/ABI stable, to prevent problems when updating this framework. A compatiblity report can be found [here](http://upstream.rosalinux.ru/versions/libjson-rpc-cpp.html). License ------- This framework is licensed under [MIT](http://en.wikipedia.org/wiki/MIT_License). All of this libraries dependencies are licensed under MIT compatible licenses. Documentation ------------- The documentation for this library can be generated using doxygen. If it is installed on your system, you can simply type: ```sh cd build make doc ``` This generates the Latex and HTML documentation into `build/doc` Run the tests ------------- Simply run: ```sh make test ``` Testcoverage can be retrieved by invoking the [dev/testcoverage.sh script](https://github.com/cinemast/libjson-rpc-cpp/blob/master/dev/testcoverage.sh) inside the `dev` folder. libjson-rpc-cpp-0.7.0/cmake/000077500000000000000000000000001275256467400156225ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/cmake/CMakeCompilerSettings.cmake000066400000000000000000000014531275256467400230230ustar00rootroot00000000000000# Set necessary compile and link flags if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall -Wformat -Wno-format-extra-args -Wformat-security -Wformat-nonliteral -Wformat=2 -Wextra -Wnon-virtual-dtor -fprofile-arcs -ftest-coverage -fPIC -O0") elseif ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") # TODO figure clang stuff to enable test-coverage # Instrument Program flow should be set to Yes # http://stackoverflow.com/questions/7949781/undefined-symbols-for-architecture-i386-upgrading-project-to-ios-5 set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall -Wextra -Wnon-virtual-dtor -fPIC -O0") elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") # no msvc flags for now endif()libjson-rpc-cpp-0.7.0/cmake/CMakeDependencies.cmake000066400000000000000000000034041275256467400221140ustar00rootroot00000000000000# all dependencies that are not directly included in the libjson-rpc-cpp distribution are defined here! # default search directory for dependencies is ${CMAKE_SOURCE_DIR}/win32-deps (for backwards compatibility) # if your dependencies directory is different, please run cmake with CMAKE_PREFIX_PATH option eg: # # cmake -DCMAKE_PREFIX_PATH=path_to_your_dependencies . # set default dependencies search path set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} "${CMAKE_SOURCE_DIR}/win32-deps") # find JSONCPP # TODO: handle windows debug libraries! # TODO: fix FindJSONCPP file! find_package(Jsoncpp) message(STATUS "Jsoncpp header: ${JSONCPP_INCLUDE_DIRS}") message(STATUS "Jsoncpp lib : ${JSONCPP_LIBRARIES}") message(STATUS "Jsoncpp prefix: ${JSONCPP_INCLUDE_PREFIX}") # find Threads! find_package(Threads) message(STATUS "Threads: ${CMAKE_THREADS_LIBS_INIT}") # find Argtable if(${COMPILE_STUBGEN}) find_package(Argtable REQUIRED) message(STATUS "Argtable header: ${ARGTABLE_INCLUDE_DIRS}") message(STATUS "Argtable lib : ${ARGTABLE_LIBRARIES}") endif() if(${HTTP_CLIENT}) # find CURL find_package(CURL REQUIRED) message(STATUS "CURL header: ${CURL_INCLUDE_DIRS}") message(STATUS "CURL lib : ${CURL_LIBRARIES}") endif() if (${HTTP_SERVER}) # find libmicrohttpd find_package(MHD REQUIRED) message(STATUS "MHD header: ${MHD_INCLUDE_DIRS}") message(STATUS "MHD lib : ${MHD_LIBRARIES}") endif() # find doxygen find_package(Doxygen) if (${COMPILE_TESTS}) find_package(Catch) if(NOT CATCH_FOUND) message("Could not find catch, downloading it now") # Includes Catch in the project: add_subdirectory(${CMAKE_SOURCE_DIR}/src/catch) include_directories(${CATCH_INCLUDE_DIR} ${COMMON_INCLUDES}) else() INCLUDE_DIRECTORIES(${CATCH_INCLUDE_DIRS}) endif() endif() libjson-rpc-cpp-0.7.0/cmake/CMakePackaging.cmake000066400000000000000000000016541275256467400214170ustar00rootroot00000000000000include(InstallRequiredSystemLibraries) set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "libjson-rpc-cpp") set(CPACK_PACKAGE_VENDOR "Peter Spiess-Knafl ") set(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/README.md") set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE.txt") set(CPACK_PACKAGE_VERSION_MAJOR "${MAJOR_VERSION}") set(CPACK_PACKAGE_VERSION_MINOR "${MINOR_VERSION}") set(CPACK_PACKAGE_VERSION_PATCH "${PATCH_VERSION}") if (WIN32 AND NOT UNIX) set(CPACK_GENERATOR "NSIS") set(CPACK_NSIS_DISPLAY_NAME "${CPACK_PACKAGE_INSTALL_DIRECTORY} libjson-rpc-cpp") set(CPACK_NSIS_HELP_LINK "http://github.com/cinemast/libjson-rpc-cpp") set(CPACK_NSIS_URL_INFO_ABOUT "http://github.com/cinemast/libjson-rpc-cpp") set(CPACK_NSIS_CONTACT "Peter Spiess-Knafl ") set(CPACK_NSIS_MODIFY_PATH ON) endif(WIN32 AND NOT UNIX) include(CPack) libjson-rpc-cpp-0.7.0/cmake/FindArgtable.cmake000066400000000000000000000023521275256467400211500ustar00rootroot00000000000000# - Try to find ARGTABLE # Once done this will define # # ARGTABLE_FOUND - system has ARGTABLE # ARGTABLE_INCLUDE_DIRS - the ARGTABLE include directory # ARGTABLE_LIBRARIES - Link these to use ARGTABLE find_path ( ARGTABLE_INCLUDE_DIR NAMES argtable2.h DOC "argtable include dir" ) find_library ( ARGTABLE_LIBRARY NAMES argtable2 DOC "argtable library" ) set(ARGTABLE_INCLUDE_DIRS ${ARGTABLE_INCLUDE_DIR}) set(ARGTABLE_LIBRARIES ${ARGTABLE_LIBRARY}) # debug library on windows # same naming convention as in qt (appending debug library with d) # boost is using the same "hack" as us with "optimized" and "debug" if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") find_library( ARGTABLE_LIBRARY_DEBUG NAMES argtable2d DOC "argtable debug library" ) set(ARGTABLE_LIBRARIES optimized ${ARGTABLE_LIBRARIES} debug ${ARGTABLE_LIBRARY_DEBUG}) endif() # handle the QUIETLY and REQUIRED arguments and set JSONCPP_FOUND to TRUE # if all listed variables are TRUE, hide their existence from configuration view include(FindPackageHandleStandardArgs) find_package_handle_standard_args(argtable DEFAULT_MSG ARGTABLE_INCLUDE_DIR ARGTABLE_LIBRARY) mark_as_advanced (ARGTABLE_INCLUDE_DIR ARGTABLE_LIBRARY) libjson-rpc-cpp-0.7.0/cmake/FindCURL.cmake000066400000000000000000000025121275256467400201720ustar00rootroot00000000000000# Find CURL # # Find the curl includes and library # # if you nee to add a custom library search path, do it via via CMAKE_PREFIX_PATH # # This module defines # CURL_INCLUDE_DIRS, where to find header, etc. # CURL_LIBRARIES, the libraries needed to use curl. # CURL_FOUND, If false, do not try to use curl. # only look in default directories find_path( CURL_INCLUDE_DIR NAMES curl/curl.h DOC "curl include dir" ) find_library( CURL_LIBRARY # names from cmake's FindCURL NAMES curl curllib libcurl_imp curllib_static libcurl DOC "curl library" ) set(CURL_INCLUDE_DIRS ${CURL_INCLUDE_DIR}) set(CURL_LIBRARIES ${CURL_LIBRARY}) # debug library on windows # same naming convention as in qt (appending debug library with d) # boost is using the same "hack" as us with "optimized" and "debug" if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") find_library( CURL_LIBRARY_DEBUG NAMES curld libcurld DOC "curl debug library" ) set(CURL_LIBRARIES optimized ${CURL_LIBRARIES} debug ${CURL_LIBRARY_DEBUG}) endif() # handle the QUIETLY and REQUIRED arguments and set CURL_FOUND to TRUE # if all listed variables are TRUE, hide their existence from configuration view include(FindPackageHandleStandardArgs) find_package_handle_standard_args(CURL DEFAULT_MSG CURL_INCLUDE_DIR CURL_LIBRARY) mark_as_advanced (CURL_INCLUDE_DIR CURL_LIBRARY) libjson-rpc-cpp-0.7.0/cmake/FindCatch.cmake000066400000000000000000000004211275256467400204440ustar00rootroot00000000000000find_path( CATCH_INCLUDE_DIR NAMES catch.hpp DOC "catch include dir" ) set(CATCH_INCLUDE_DIRS ${CATCH_INCLUDE_DIR}) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(catch DEFAULT_MSG CATCH_INCLUDE_DIR) mark_as_advanced (CATCH_INCLUDE_DIR) libjson-rpc-cpp-0.7.0/cmake/FindJsoncpp.cmake000066400000000000000000000032311275256467400210400ustar00rootroot00000000000000# Find jsoncpp # # Find the jsoncpp includes and library # # if you nee to add a custom library search path, do it via via CMAKE_PREFIX_PATH # # This module defines # JSONCPP_INCLUDE_DIRS, where to find header, etc. # JSONCPP_LIBRARIES, the libraries needed to use jsoncpp. # JSONCPP_FOUND, If false, do not try to use jsoncpp. # JSONCPP_INCLUDE_PREFIX, include prefix for jsoncpp # only look in default directories find_path( JSONCPP_INCLUDE_DIR NAMES jsoncpp/json/json.h json/json.h DOC "jsoncpp include dir" ) find_library( JSONCPP_LIBRARY NAMES jsoncpp DOC "jsoncpp library" ) set(JSONCPP_INCLUDE_DIRS ${JSONCPP_INCLUDE_DIR}) set(JSONCPP_LIBRARIES ${JSONCPP_LIBRARY}) # debug library on windows # same naming convention as in qt (appending debug library with d) # boost is using the same "hack" as us with "optimized" and "debug" if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") find_library( JSONCPP_LIBRARY_DEBUG NAMES jsoncppd DOC "jsoncpp debug library" ) set(JSONCPP_LIBRARIES optimized ${JSONCPP_LIBRARIES} debug ${JSONCPP_LIBRARY_DEBUG}) endif() # find JSONCPP_INCLUDE_PREFIX find_path( JSONCPP_INCLUDE_PREFIX NAMES json.h PATH_SUFFIXES jsoncpp/json json ) if (${JSONCPP_INCLUDE_PREFIX} MATCHES "jsoncpp") set(JSONCPP_INCLUDE_PREFIX "jsoncpp/json") else() set(JSONCPP_INCLUDE_PREFIX "json") endif() # handle the QUIETLY and REQUIRED arguments and set JSONCPP_FOUND to TRUE # if all listed variables are TRUE, hide their existence from configuration view include(FindPackageHandleStandardArgs) find_package_handle_standard_args(jsoncpp DEFAULT_MSG JSONCPP_INCLUDE_DIR JSONCPP_LIBRARY) mark_as_advanced (JSONCPP_INCLUDE_DIR JSONCPP_LIBRARY) libjson-rpc-cpp-0.7.0/cmake/FindMHD.cmake000077500000000000000000000021051275256467400200360ustar00rootroot00000000000000# - Try to find MHD # Once done this will define # # MHD_FOUND - system has MHD # MHD_INCLUDE_DIRS - the MHD include directory # MHD_LIBRARY - Link these to use MHD find_path( MHD_INCLUDE_DIR NAMES microhttpd.h DOC "microhttpd include dir" ) find_library( MHD_LIBRARY NAMES microhttpd microhttpd-10 libmicrohttpd libmicrohttpd-dll DOC "microhttpd library" ) set(MHD_INCLUDE_DIRS ${MHD_INCLUDE_DIR}) set(MHD_LIBRARIES ${MHD_LIBRARY}) # debug library on windows # same naming convention as in qt (appending debug library with d) # boost is using the same "hack" as us with "optimized" and "debug" # official MHD project actually uses _d suffix if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") find_library( MHD_LIBRARY_DEBUG NAMES microhttpd_d microhttpd-10_d libmicrohttpd_d libmicrohttpd-dll_d DOC "mhd debug library" ) set(MHD_LIBRARIES optimized ${MHD_LIBRARIES} debug ${MHD_LIBRARY_DEBUG}) endif() include(FindPackageHandleStandardArgs) find_package_handle_standard_args(mhd DEFAULT_MSG MHD_INCLUDE_DIR MHD_LIBRARY) mark_as_advanced(MHD_INCLUDE_DIR MHD_LIBRARY) libjson-rpc-cpp-0.7.0/cmake/FindSocket.cmake000066400000000000000000000010151275256467400206520ustar00rootroot00000000000000# - This module determines the socket library of the system. # The following variables are set # Socket_LIBRARIES - the socket library # Socket_FOUND if (${CMAKE_SYSTEM} MATCHES "Windows") if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") set(Socket_LIBRARIES ws2_32) else() set(Socket_LIBRARIES wsock32 ws2_32) endif() set(Socket_FOUND 1) elseif(${CMAKE_SYSTEM} MATCHES "INtime") set(Socket_LIBRARIES netlib) set(Socket_FOUND 1) else() set(Socket_LIBRARIES) set(Socket_FOUND 1) endif() libjson-rpc-cpp-0.7.0/cmake/FindThreads.cmake000066400000000000000000000141451275256467400210240ustar00rootroot00000000000000# - This module determines the thread library of the system. # The following variables are set # CMAKE_THREAD_LIBS_INIT - the thread library # CMAKE_USE_SPROC_INIT - are we using sproc? # CMAKE_USE_WIN32_THREADS_INIT - using WIN32 threads? # CMAKE_USE_PTHREADS_INIT - are we using pthreads # CMAKE_HP_PTHREADS_INIT - are we using hp pthreads # For systems with multiple thread libraries, caller can set # CMAKE_THREAD_PREFER_PTHREAD #============================================================================= # Copyright 2002-2009 Kitware, Inc. # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distribute this file outside of CMake, substitute the full # License text for the above reference.) include (CheckIncludeFiles) include (CheckLibraryExists) include (CheckSymbolExists) set(Threads_FOUND FALSE) # Do we have sproc? if(${CMAKE_SYSTEM} MATCHES IRIX AND NOT CMAKE_THREAD_PREFER_PTHREAD) CHECK_INCLUDE_FILES("sys/types.h;sys/prctl.h" CMAKE_HAVE_SPROC_H) endif() if(CMAKE_HAVE_SPROC_H AND NOT CMAKE_THREAD_PREFER_PTHREAD) # We have sproc set(CMAKE_USE_SPROC_INIT 1) else() # Do we have pthreads? CHECK_INCLUDE_FILES("pthread.h" CMAKE_HAVE_PTHREAD_H) if(CMAKE_HAVE_PTHREAD_H) # # We have pthread.h # Let's check for the library now. # set(CMAKE_HAVE_THREADS_LIBRARY) if(NOT THREADS_HAVE_PTHREAD_ARG) # Check if pthread functions are in normal C library CHECK_SYMBOL_EXISTS(pthread_create pthread.h CMAKE_HAVE_LIBC_CREATE) if(CMAKE_HAVE_LIBC_CREATE) set(CMAKE_THREAD_LIBS_INIT "") set(CMAKE_HAVE_THREADS_LIBRARY 1) set(Threads_FOUND TRUE) endif() if(NOT CMAKE_HAVE_THREADS_LIBRARY) # Do we have -lpthreads CHECK_LIBRARY_EXISTS(pthreads pthread_create "" CMAKE_HAVE_PTHREADS_CREATE) if(CMAKE_HAVE_PTHREADS_CREATE) set(CMAKE_THREAD_LIBS_INIT "-lpthreads") set(CMAKE_HAVE_THREADS_LIBRARY 1) set(Threads_FOUND TRUE) endif() # Ok, how about -lpthread CHECK_LIBRARY_EXISTS(pthread pthread_create "" CMAKE_HAVE_PTHREAD_CREATE) if(CMAKE_HAVE_PTHREAD_CREATE) set(CMAKE_THREAD_LIBS_INIT "-lpthread") set(CMAKE_HAVE_THREADS_LIBRARY 1) set(Threads_FOUND TRUE) endif() if(${CMAKE_SYSTEM} MATCHES "SunOS.*") # On sun also check for -lthread CHECK_LIBRARY_EXISTS(thread thr_create "" CMAKE_HAVE_THR_CREATE) if(CMAKE_HAVE_THR_CREATE) set(CMAKE_THREAD_LIBS_INIT "-lthread") set(CMAKE_HAVE_THREADS_LIBRARY 1) set(Threads_FOUND TRUE) endif() endif() endif() endif() if(NOT CMAKE_HAVE_THREADS_LIBRARY) # If we did not found -lpthread, -lpthread, or -lthread, look for -pthread if("THREADS_HAVE_PTHREAD_ARG" MATCHES "^THREADS_HAVE_PTHREAD_ARG") message(STATUS "Check if compiler accepts -pthread") try_run(THREADS_PTHREAD_ARG THREADS_HAVE_PTHREAD_ARG ${CMAKE_BINARY_DIR} ${CMAKE_ROOT}/Modules/CheckForPthreads.c CMAKE_FLAGS -DLINK_LIBRARIES:STRING=-pthread COMPILE_OUTPUT_VARIABLE OUTPUT) if(THREADS_HAVE_PTHREAD_ARG) if(THREADS_PTHREAD_ARG STREQUAL "2") set(Threads_FOUND TRUE) message(STATUS "Check if compiler accepts -pthread - yes") else() message(STATUS "Check if compiler accepts -pthread - no") file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log "Determining if compiler accepts -pthread returned ${THREADS_PTHREAD_ARG} instead of 2. The compiler had the following output:\n${OUTPUT}\n\n") endif() else() message(STATUS "Check if compiler accepts -pthread - no") file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log "Determining if compiler accepts -pthread failed with the following output:\n${OUTPUT}\n\n") endif() endif() if(THREADS_HAVE_PTHREAD_ARG) set(Threads_FOUND TRUE) set(CMAKE_THREAD_LIBS_INIT "-pthread") endif() endif() endif() endif() if(CMAKE_THREAD_LIBS_INIT OR CMAKE_HAVE_LIBC_CREATE) set(CMAKE_USE_PTHREADS_INIT 1) set(Threads_FOUND TRUE) endif() if(${CMAKE_SYSTEM} MATCHES "Windows") set(CMAKE_USE_WIN32_THREADS_INIT 1) set(Threads_FOUND TRUE) endif() if(CMAKE_USE_PTHREADS_INIT) if(${CMAKE_SYSTEM} MATCHES "HP-UX-*") # Use libcma if it exists and can be used. It provides more # symbols than the plain pthread library. CMA threads # have actually been deprecated: # http://docs.hp.com/en/B3920-90091/ch12s03.html#d0e11395 # http://docs.hp.com/en/947/d8.html # but we need to maintain compatibility here. # The CMAKE_HP_PTHREADS setting actually indicates whether CMA threads # are available. CHECK_LIBRARY_EXISTS(cma pthread_attr_create "" CMAKE_HAVE_HP_CMA) if(CMAKE_HAVE_HP_CMA) set(CMAKE_THREAD_LIBS_INIT "-lcma") set(CMAKE_HP_PTHREADS_INIT 1) set(Threads_FOUND TRUE) endif() set(CMAKE_USE_PTHREADS_INIT 1) endif() if(${CMAKE_SYSTEM} MATCHES "OSF1-V*") set(CMAKE_USE_PTHREADS_INIT 0) set(CMAKE_THREAD_LIBS_INIT ) endif() if(${CMAKE_SYSTEM} MATCHES "CYGWIN_NT*") set(CMAKE_USE_PTHREADS_INIT 1) set(Threads_FOUND TRUE) set(CMAKE_THREAD_LIBS_INIT ) set(CMAKE_USE_WIN32_THREADS_INIT 0) endif() endif() if(${CMAKE_SYSTEM} MATCHES "INtime") set(Threads_FOUND TRUE) set(CMAKE_THREAD_LIBS_INIT "iwin32") endif() include(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(Threads DEFAULT_MSG Threads_FOUND) libjson-rpc-cpp-0.7.0/cmake/cmake_uninstall.cmake.in000066400000000000000000000017111275256467400224020ustar00rootroot00000000000000 cmake_policy(SET CMP0007 NEW) if (NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") message(FATAL_ERROR "Cannot find install manifest: \"@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt\"") endif(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") file(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files) string(REGEX REPLACE "\n" ";" files "${files}") list(REVERSE files) foreach (file ${files}) message(STATUS "Uninstalling \"$ENV{DESTDIR}${file}\"") if (EXISTS "$ENV{DESTDIR}${file}") execute_process( COMMAND @CMAKE_COMMAND@ -E remove "$ENV{DESTDIR}${file}" OUTPUT_VARIABLE rm_out RESULT_VARIABLE rm_retval ) if (NOT ${rm_retval} EQUAL 0) message(FATAL_ERROR "Problem when removing \"$ENV{DESTDIR}${file}\"") endif (NOT ${rm_retval} EQUAL 0) else (EXISTS "$ENV{DESTDIR}${file}") message(STATUS "File \"$ENV{DESTDIR}${file}\" does not exist.") endif (EXISTS "$ENV{DESTDIR}${file}") endforeach(file) libjson-rpc-cpp-0.7.0/cmake/cross-mingw32-linux.cmake000066400000000000000000000021411275256467400223740ustar00rootroot00000000000000# the name of the target operating system set(CMAKE_SYSTEM_NAME Windows) # Choose an appropriate compiler prefix # for classical mingw32 # see http://www.mingw.org/ #set(COMPILER_PREFIX "i586-mingw32msvc") # for 32 or 64 bits mingw-w64 # see http://mingw-w64.sourceforge.net/ set(COMPILER_PREFIX "i586-mingw32msvc") #set(COMPILER_PREFIX "x86_64-w64-mingw32" # which compilers to use for C and C++ find_program(CMAKE_RC_COMPILER NAMES ${COMPILER_PREFIX}-windres) #SET(CMAKE_RC_COMPILER ${COMPILER_PREFIX}-windres) find_program(CMAKE_C_COMPILER NAMES ${COMPILER_PREFIX}-gcc) #SET(CMAKE_C_COMPILER ${COMPILER_PREFIX}-gcc) find_program(CMAKE_CXX_COMPILER NAMES ${COMPILER_PREFIX}-g++) #SET(CMAKE_CXX_COMPILER ${COMPILER_PREFIX}-g++) # here is the target environment located set(CMAKE_FIND_ROOT_PATH /usr/${COMPILER_PREFIX}) # adjust the default behaviour of the FIND_XXX() commands: # search headers and libraries in the target environment, search # programs in the host environment set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) libjson-rpc-cpp-0.7.0/cmake/libjsonrpccpp-client.pc.cmake000066400000000000000000000004041275256467400233470ustar00rootroot00000000000000Name: libjsonrpccpp-client Description: A C++ client implementation of json-rpc. Version: ${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_VERSION} Libs: -L${FULL_PATH_LIBDIR} -ljsoncpp -ljsonrpccpp-common -ljsonrpccpp-client -lcurl Cflags: -I${FULL_PATH_INCLUDEDIR} libjson-rpc-cpp-0.7.0/cmake/libjsonrpccpp-common.pc.cmake000066400000000000000000000003211275256467400233570ustar00rootroot00000000000000Name: libjsonrpccpp-common Description: Common libraries for libjson-rpc-cpp Version: ${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_VERSION} Libs: -L${FULL_PATH_LIBDIR} -ljsoncpp Cflags: -I${FULL_PATH_INCLUDEDIR} libjson-rpc-cpp-0.7.0/cmake/libjsonrpccpp-server.pc.cmake000066400000000000000000000004121275256467400233760ustar00rootroot00000000000000Name: libjsonrpccpp-server Description: A C++ server implementation of json-rpc. Version: ${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_VERSION} Libs: -L${FULL_PATH_LIBDIR} -ljsoncpp -ljsonrpccpp-common -ljsonrpccpp-server -lmicrohttpd Cflags: -I${FULL_PATH_INCLUDEDIR} libjson-rpc-cpp-0.7.0/cmake/libjsonrpccpp-stub.pc.cmake000066400000000000000000000003761275256467400230560ustar00rootroot00000000000000Name: libjsonrpccpp-stub Description: library for stub-generation of libjson-rpc-cpp servers/clients. Version: ${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_VERSION} Libs: -L${FULL_PATH_LIBDIR} -ljsoncpp -ljsonrpccpp-common Cflags: -I${FULL_PATH_INCLUDEDIR} libjson-rpc-cpp-0.7.0/dev/000077500000000000000000000000001275256467400153205ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/dev/artwork/000077500000000000000000000000001275256467400170115ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/dev/artwork/logo.png000066400000000000000000000372531275256467400204710ustar00rootroot00000000000000PNG  IHDRxsBIT|d pHYs2#2#tEXtSoftwarewww.inkscape.org< IDATxux[ bv;04T 4mruYamV+, [)mi09dL-flj%_-ɲ}>ϓ'W7=/`,B0 %H@s XϹ?s̲,7b%-ɅD4 ,RhE0C'<X0@-˲֞\"a  '7@ zL+T,Qa<(L*1f&)TWSN*-`Pf}f`ffcmCe6{B@#T,  0|]Q`GX3xR  |Sl=̶s18/`Y# .ՃSIׂ@6_?^Aᷯ(gYmRaE0 ]JӤX%ASH4 [m?q*0<+5K) 0\8@YI8"c P>  ڋAC:͚W@[,b{'0@$ǂ@N_F_B @$k%c%qO*a#{t,VzP0,J^DؐwO2 8XKH M|".,H ue5p˲\ ptv5bd@H> # V\m<Ì=!`׮AO8~p @(r= M"@  M"x@ _u/pB{υ+]x~> )nBy,D )En 1hB QBH)t "03Zٝ/˒c)8g HpE;pi)oYK` s@/.c"ۃ," !,ȳ=s}=7 "LDj $/A3 RwR:'^p6$ H:qn>w&c/Ol)b->v.p3|8P: ]#uh, 8YD_AhsEAU~9=PBg//eB1Fyɹ@x@p!W :RaF^_+rO81 `bmhϝ5&G)CsR\ǯ'{w`K6S#qD x5bpuBL,2ɞ (ط|1Z`ozd[wOHUDRKxK+fzisuB ǂ9_N 8L C2>٫-1A҈@F{zv1ie}oG  x4~wcEMzuQ^^,uo1Hve܃'-fWR`@ :H8\#^_][vR*7=uh°!וֹsTAmtәPL,[w5c A/d"^3zj꾥9) hٙW??ϝooק)Un 43"G$65?޶H#@B &Ky]~$&NZ; tufɑKU /Űd7G{@ جQjgEU|c|ƿ_[.|4wUxRg f5jm?oD@$ Yh&wQ_.'W(ǽcs$ҳ wYmNAVpr?x|eŖr۶㍮#Um@$98lՓs2) ZnK+_wx(vT!p >~KGeuEU *Dj_7m'Ík.eȰqmV7=gfSB2=>;{T:lp4QRO  G 9^crp㪚`Q($|b3W愋,X=U7|̜kuz[.ј\QTIx??7/'ԮB+<$pFǴG~k69Q(0WVorsFjqԄHH3\%`K xo]UYOGGo-YOhL/?{" Ι08U2 Oomӯ _Dm>JBr Hu"9n+cs%_n-MgnCʈքM]^haDEFOjΟ/\#3Fd>Zn LzgqY< 5"`7mYfX8)d$6x=C_~Qv؝l7P+Xnn!i H2$۷lKTH>I8$- jÛ j19€gɑ֙'Li$l8s"2y$ncS4TN.eE ]'5-6fp8n}uSc a~y¶j[k2:g)#J B +&>aAsbe<| km/~;Ysh8$UxϼS aa4YJWS,kr|ތLOo,Xn=ĊIwų_T_lFUc旿;fwEؠK&X4@Rޒg $T|=-οX @ 0mxd×ey Sƅē.rH} w1~"\|n Ț3xo^.F{]WS|جhdbI7^?(M)I|ea-G)a3#&3ItutW"#L2T6Y4w^."yi=1;'Mޏ/H";^IxP=`:d%)\ִ1$SsRUA=ŁdکEYʨֲQsZlhmnYV) ȄĠ,8C/ʐdxO4N‘z9=޹Xk1hf "&' gȌl 4˾պDoHȟ~WJ6HZMͩ !q(O8.>p2i\aq HwpPl=!}o]Y1O0V.;N49?c]{m䷶#Azo\Bӣ&EmmZ1ybJ#~JZqh Lx`At~M/yƞ__uÞ~ ¥F%ntpѦ@&盛 ~YO[Ga®S%K%Ӌeц>XUg^6}$ aifq\b" R|iْ>s k6vi}\+b.2W SӼyŷwhtL̬2M<%̤tq< ?崉 ZםS̶u?pekëj6a wDJx (%cT3Gd&G3HFÛ?+ı'Euߑpyk[75&'ldy2>|ֶbk;^:fDs!irl^a6=g͞S:9Zmm0y|PٙzOjD᜜;6Wr[~k[0)_*޽gZ{vI/n0ıy*lNŔG -ukqP.jGq)ޙFDt n/ [,L}vsvJrsϧb@, SK甪>oFfݧ:ym'{iJqTV5[J=YgJ\49V79Z60ޫk{51Hzelp}D apQFc臿?(̎+0EYE-]p僝-Z{ٌd.D |6!!a'w(knSZmE* [Fy?{f^T=rEQ ^_|ug iB#럙 bYχtaO0V[!HzwW9J\Y}u6#SfȔxHF]z{>\]?wFR#H]|Z5~Rl+5uBaMwF)_\JQx;!k[l3_h 7QY?\Q+̡[S| Gj#Ua*AQ$]?Z`kz3T.ܔm%.uW50X1XKz_IU@fu?qt(4aɥi%ib$z'4J*CnE)4A,3 ;AԷESXڴk xdpV˄[wMM_uo@ˁ>G[7qS2o/jmE $plRiZt./csb;$[ɋ&Z`݁&6x㱰eV7>!@?ٷV7OzhUm )B>fgYSTwQ1|X6DT[l^aWuڕ@/&?d[~|KGf-/Qˢ34]y#UW=TꊴG{wԓkTZx qDu$~0we|ܼ'I*MVa_. b HrRJSUtSVktaLvm{2! L9o\YgTGaOGtc׏>hfisG}gŰj*Ĥ4e$ZuIDATbGYOomK.w]%pݶ{$IJzLO3S F5'b|Cxx(M x6cD$ ru?47qoc_Ur֜hoj{Cڥvgr" H"1-3>Cwcd@nhU{.4%> ò]>6j<*o70\|~HEP`V̟{Vk˄$1"W&nbF@01 4@b9P!Y-[5sJF9=p@qqC1-8Tst2.M}b\f:0M@M Aޱg+oV8\cus__d$ C1콟5^xF$. j&'fWj<\J($1sJ:8^b>k_C5'm1_7=ԲOO6>z#$C}* n vYk\7)]1ڢkk6{ H0  PI Ǧ)^oy}_i=@#۵ms{|;Os[F'pjO &HiVg҉c^=3JAO7Dl@"@bX2)3E}ŌRD;nMO7d@1 ^uhf7l Os Rx-ر ёu6'Z$IL/Q$G=&_t4;) 5mPek'sK:ctr&q[z H6DIB@z)$2RdB9T% `v>?ݐ,{QZsS^Z]̹ `b( űVx.FȄxE1ٹ,8- G[&;ʃ;>$IZsˏxG-4'Ik6=}>?x}FI q$ K1?U5[S i6{|o\ӲPKPg`m6$)DE$ OMLW>Lcu3vadݵhe&ji SJxH $Qr;Gj I\+瓩r>9$S*^ y]WYRї^g=֫34ò.o{edf_uSwz:C b9 (H $Qr\gsG-O  ^$Ot;Ϙ8bOO궜4$\hvŕˆ؂M3h0:$aTLDbőZ+ wIe$cu6-# [K"-WqȹapAH=}9gEkd^V!7fg_Muy*<6(mkKAw~5*>KKTMemO7H$əA D,J[x,W#,47_jv,k1'NO_9F*;h@;Hppѫ ӹy)}yMUW{,~ߣV?:^tWD H8 ɅxnUEx÷Oib^<@"42>gx @-V/bRx/7ORsnuz^[Wݖ{B nl?[PD )S$\ՇZl" DR@\v1Q?DUsZ*D (tbXL:ò[D@'RgAQVգ@"YA" `q" @ "H:" "N ߂";!r:tҋa':G x y=Ki(:c=_qE8=?,@(Dv7EKDH*B!)w?,7~^㧃z_m_XMH5B5B5nXSo09|q8| d@' " 5@ H:as(%$)BKOe:k 4펥IJm޸H8h,lcO >0[pu[\͂:KWΗE9du}T#G"Љ' qP"jҫ_6 UZ[z׺#=NښPΗhrbyۉflqM+I)4@i󉗙"*:@ep 13GD@z|gXV$xM 'H8`f.ylqi YdɩCRz DfCEg,ѣp|qWp8@ b l:ap3֝Oؓ 3^4+נ'L,R>{T_(N _ndVdFj)?Л>^onaǦn!q@ M^Yv`C3E$q۴,͍S2Շk,5Vׁ*Hm2!ɔ&)Ec921z#B7.*|p!À) x#LMo(׊\cxM(RJ')w^0v74Ͱ,($!P-qxPY3D`|5 I &(tE(evϵjiߚGjDT>)`.Y,.4Fͣq Ѩ  : 9"졚NxDO#Fq0CmA>ia+'@ ^: Y pew8? m &eA-'> \Fd }ߩ϶80B@t-2Wk?A;D28[wC`",냀%۸h_3P8Z5@$;V2!xn>wIJ?oH&pj׎j#ɊN pC멦y`Y ̃TVhZ Zwy|*o3/F04N,HXKKn%XtYhe_H|p7Fy00U "!@ zڋR2maϮ0 h^;Կp,u+9=bdYr,o"TH4 ;ٺ߃z# %kkf`tLDC =86 ZN4peeYc]X0 S@9@=8Ӕ\b E܂@ lC`8dw,N Pj@CE#0, a <%<%`0 Xmb=6=49PYh E"pD @.DbHH@!R hL.z,/ԾLPQ 3cR6=f"wQ #] vG  =Ϲ?s\MXcr(4IENDB`libjson-rpc-cpp-0.7.0/dev/artwork/logo.svg000066400000000000000000000105241275256467400204740ustar00rootroot00000000000000 image/svg+xml JSONRPCC++ lib libjson-rpc-cpp-0.7.0/dev/artwork/logo_small.png000066400000000000000000000112241275256467400216470ustar00rootroot00000000000000PNG  IHDR77F pHYs2#2#diTXtXML:com.adobe.xmp www.inkscape.org 4IDAThZ tTe߫zWRUI*dcB0"8B۶c;ڣڞQihmŖM0C K–@ TjK- +"p<9Kh4q:u{jc-5ca 5i2cr0VwBA7j/DQ:,o̐]0hG)Y%cӬnכQ0 1,e|NfmoiK$s8e2H氀 'K:$CFrs+ӥ{YP!!0r,T_gRB!"L_}" ;0F6gDRa 3Tϲ >+M+7n;o.hfBݳ? @fzux!@13RdBr p)LՂcmn_X8~GdiV}`U A tqo iu-]w_[AQ)`(:M?8)M>thcMW8 vFKFX<77{bzk|jwf~ӡ: (c x %wY7jn1Wo2iA3@2>=,B,J6򄸔O&tMb⥛ Oԁbw_ib[(w;RTg^9PwK[zA/FK'YR 뽫rт2÷&fM:umqoUcm]DΝ4T{aœT^ ]qI`YWfI7j"|]"m֢|›t͝]!AA8=|n˺.폦[tfu*Yihe^}4\hqSuJnRU=8S3n1'gXI[#|bdJUxGN7_6<[Fdd1r"8mt^+a9"p>.%'JD3RT2,NgT:C}+ǂ$JptBA Alo)%]'/1 0&#n/1=8(yC?ܸ%Yu]2̢zٿxÆP[J@|NsR?-c/v8 y3.: DYVqo8ёMMӳ?$%ˤ9lH2nAMk;|еLvxweh8&:Y|~ҥ9];|a{;lX g϶}{ww7nQC_V<$1nGWHqbbS69 3ThRSۍ?!ť-s.6*5ʒ[c̣kjڥohxWS`<} W bw$j9$)?+U-VX.5Ul?e <64$Klk/0z7Gd6W~;,ɏZ \\EC 瓢8ϳ93F21*ՠW3Z}c~,B= g7U:Lი{ˁMA EčH -xݎx(KcP.XRSȪ|;Α:s&I\MҤoK[MOva7^1g7$񦝌f?]oG\lk$(QeXoדJ[kH^)|Ӎ%4 z: epxO5*-3U%GE~CͮFo@"!3SJZNG};|TM4NOj዆#h# n,oq \FԪ_obЂF U^gPQCJ)OiԌ3hwVhw?읟Y<%HqY+踜{ IwζZ2[+,1p8wq*=zl_c'ĉ¤S LzT694?msiwh5Y#ҬF,$<*BHH$qМ#k2^U3 L WkzlW_I%'bఄsKIpT3%[xa3! # <{ECY<њ:5ߨK4Zv{%k#u;JVg5 b7oiD!$E}SpE >JGCi*7nqCZx,PRW= L'NyD$d!JpeLkE&x`Rrխʼnpq^]W*G\[!xU;yDݑD?sDnE\+vJSX^,w2呔ws䙐RQ(FOLߥ'u6Xݾ? ;"Ή,gqLdҵ>Z"BzYDC%錂Ǘ%{9qx(W)0)9Ll7eM3碫8tY=eOʹ(]듶?Q<\lZpnd!ٹ 8[j[3GIENDB`libjson-rpc-cpp-0.7.0/dev/artwork/overview.dia000066400000000000000000001425311275256467400213440ustar00rootroot00000000000000 #Letter# ## #libjsonrpccpp-client# ## #libjsonrpccpp-server# #sepc.json { add() }# #jsonrpcstub# #Client Connector# ## ## ## #Server Connector# ## ## ## #AbstractServerStub# ## ## #addInterface# ## ## ## #ClientStub# ## ## #add# ## ## ## #ServerApplication# ## ## #add# ## ## ## #Client Application# ## ## ## ## ## ## ## ## ## ## #Things you need to write# #Things that are generated# #Things provided by this framework# #RPC-Call# libjson-rpc-cpp-0.7.0/dev/artwork/overview.png000066400000000000000000001111331275256467400213650ustar00rootroot00000000000000PNG  IHDRk bsBITO pHYs IDATxwTW;.KMzQĂb`M슟hƘ XT*m?Ƭ.Mə]$I@/bٲetgٳl2@5BAtЂH,js*B}i㷎wDw-SS$aaP[Ġ;jW Ƥݓw^A5VE!zO=e,js B5?px) 6"jX!`UB- #BaaPUB,,j+*BBmVE!%`aPUB5k\cg5*vȑ#pbaUBi(@T^ GħaaaX!`UBiࢁu7W&~\BO@utKՖҝBU!y{ӝBU!B"B! ζF Q6_KH,ԳlH1@$#N9#Ym[@A؏Xow%*?|pjڈgUV[&rzߨkQ}tqcsKՖ>>ꦫ:]tɶS }B- NJBљG{M!röo3*GH`2oNĭzj)AAT{o'>V/|oIEerY+\yoeAZxnյ嫁VEV ̘Ԋ >&sOͥ⏎?gܘ cM㔴mo #doSMLrlm )4c&6SRRVrŕT|jjl9iM* hWB¼{iͥl}{PZK_Am꫊7ҋ+ʤ8I T3m=je*xM<;BFX!ZЎH zqŅZDP?ɩh_ZiIm((QANYo zD&JZJ*j+6,V!ZC_*r m?MT %5/*ѯ8$o=t^|3Iϒx=~jK`cmtӍ:iqv W)NJBEo}#l9q/;wm=c7c6af7l0qcyu.ffsU\1kF\^{y:!ԚaUj eH8 :;/tdР%$г焞RO!u k!_Ȕa6$ql4^^eEwVNJB5HYWy!*`Uj{B^BՀWB!*B*~eL}݉ :"jEn9^t'ꈰ*B"9&}L!AaU$… ltgс" !qaU$ݕ+W222lҥX}1"南zt'기*d\e.Y \r=;.,:- >DBVEuUQ  ;gg;{rosAuPxg>BU|W8D VEB^M^$ѝBª!Z dX!UBQU~ #-pu ̌ɬ,WW7V_ӝW=.p8afzxgmJFIQ;KK;PUQ#;eQfQQfQV^/}/^^oR TkR/*z|q:|CiQi@W~m$vxC!9q9B`J aike ɨ[ |oG7݈SW*&o5uZ矟IaIrZY9 |ButX5^rx{YXY8|DQfў{2eye~ooOz6zf]H`'ի'@}sn)b5-Z bSŅرYo߼gf6CyA2?>D%I4U̘L<7gȞҜReqV3O矓og˺28/pnԹB?X5体g^R}oﻭY7}{N詤D5FQFѠ%8**WTF\MW睛'՗sN1g&*UUW0PEO ccd82sn)ON?!I=q{z*ΰ᤽;kgf[z.9"~uFFteԆJgFjfiN<ݜvc*z*ͅ<]uCڥjK$ɇMY6Kdj5*jNV?^v.Yﲮx]ܓsMsΝw(iQ)O>~zÀ*eDh[R]{-"@]>6h5Mɶ6'흴kஷ6AFCͿ8[~%W# |!,H-h`bT>RISj9Вv&6\tA-nFsZJ !zE#"4ivLgQTW^\u[W*Ҫ/{h@MNuHC)#|% j=,U[Tm!{ ?%ݽw5kYhخqzԡ$ ]{;yIy>c҆iT-( BPGidoeU=eedoEWV!ZX8ut똗~sNBWP,,Zlf85z6zǑ$>OP,퓓x %;6b@A]Q ꠨XQ"El}ݧ5COH?nR#S6Fָ\Y,B@8(i+I+(/:􄄄d ,wX[Y Sb&`1I,"H$BR_U|j)7[e 066666644ӳ455Ҳ)UBgȲ!}fskMRq%])L--vO% 5+H똘gϞFGGDUPPSQTTTPTTPWSS*sJ\"̭>C$Y^P^UZU^X^Q\QY\Y[Z_V_VU\]R^P_^XXp&ٯ_?CCCkkkkk]7= "P+)j(~&D+WK_/+P%9EWRGQKQU_UX]YWAȫ˫=$´œyٱ<ޒ`9888::t $1Pjm>wYGUTF{NŇ-ovRHƫ}lwYY՟.+9"Y%*@EQ݉ :ѝBLc:ҝ jJKKwܹk׮rU1GɽMLG5A M51:(щGoSSS[reͼlSUU˛3[NU\ .6ĄD:={|UWnnڵk=J=JLIKe<'L֢, w߃W^aÆŋoڴI^^ "騲״"ݹ p~A7+);Ԫxzz$I0cG0JeW |XߏgϞGRFt'7A/  DBX@@ سgѱc{ru%]s[rumµkך?>VEVDYO"F/^޽gIIpuM?4]DaßnyS~ZZɓJw^"P+2k,-Aȁz !+?󽺱:I 5|^5#OL8 K[{ Ϋ@QFO<̙3EEEt'%]8eedo+kj.ONOO׳9g{ˉmo&}LV~/7"EdP-nBIQ[;%vS{nXXݹԥWE6mٳgiiM5|C5u|}󵝛]87_IBU9}4 Z2Y&~i.,˨k6mZk̒3rMM7]=;#:C|R}4DEsUNUoGW?[_k BlEэ_o5&kKss}{lF(ygmMj9В3 `+﯌+nY[RUT#\YBm﫪 ոf鰬Lj4au#u9qU0qD5C5eKjdOKKH`={$G$zʺʺ_uz㒞y]DCNEnTp,ddeddGۺ 7m_詨|>z6zaC|||$ӧOٳܹsUV}ג-[H]ȑ#%^^^m۶HƗ/_~}}$&VSS{qJJJ.] ߽{cǎ;v;vܸqW(>:*XN b `qo}V[!n*G\ʫg7i)[l$Qe+}'hhin #cKmSR7Q/J8۵" ӚMH/-*z>q4L5!l+_O>ܗ!R略ʒ>11Qj\⤶!ݻwR6:::F{% 33'55BW\I./52'H),:jZoT^iّ IDAT[(Rn: y&ҝm R*CJJJP^P^o9rĐeC^U_ujj l_'~٧^lw>oн#֎fcCm(}\$}܄\.Ճb1Y%ʵfkSIWI|܄ܺtw.Z,Xp>xzzΘ1C2ndd$ϟ/m_~C߽ͥ{dsRo  @2rH777WWWEEE==ܭϐeCf*s ך%])L-7-N13H|X*Jx``'PGH!tgZCCC99´R w,Y8;uݖp-w_vw ceiw֮aӨzunn`gq)>woSwgj.N?½uWƓUe˱ R Mmyڻ_Z}iipiͥF Q`eeբgi"7CCCCCÆ766666nx{33333h#|}}]nNƍ6p@j=F5\v~rWFI{&"ʆ+Ƶ)66"LS=uY䫯1H#ѯ_?Ӏ ˵kע54/nūu4uwD0K4V,=ܻeG\SXoEUE;E=1tPq-+}Wbr`:_|\DG֝e7cg]gl:j֠AZ,MDT@.Y[[KТ^FF淛~ۻo}$詌}|q|o~o_o)$z ]KC-NU~ԶPg?rǖc7ۗ5>}O=z$95 i\.喗7eԌΝ;7eMS5O;- m*-dW΋nE9hW^;v,U17kebj{ G}vw*8p@j8e,rʼsz_\$Buqqq~4߉tP֚K"hU4hۘ1ctttΨ.5?/e2Bc,{~:LMFmݛ7O|`1lXʳ PDk\6IӦM;~861,6BRVVsμy+? YEYB((:2HrD2ܻw%KΨpHh>yXb;v;:㼴vNJڢgΛ7D^M~8Lw2z~ugϞ߿V*BR?~ɓ'O>{,ݹ Ԝ*jRSSg͚um;qDӾҟhA_Q3gZuI3!Z;}}dDg$ʋO.8YQԽ{ǏŒ*B!VL81..nl6;AϏ?"EU/ #d}>}MLLN8ѭ[7S| q`tBՏf6l+H-8*UWU/0+/\Wcǎ3fH}h>+B+jOBy洴4`0.':+Ol~ee#(eqrr;wn;(|Bmɜ?󃃃K.EEGE3wv{Jo 4<~%ɩ'o  E7,\ƆVE!ڶ8ԩS/_~)ܲsVlGڌQQ;6&;.WѷQ رcM6~x6}aUB=PTT\` JJJ>J'h[hێ5iepYm*K*·%'G],,kᮮsΕmhbUB]QTTξ~kׂb::f_Y 羚aAo"I2MFƛw&=KIsuu5jСCm"B퓖֬Yf͚%>}zΝ;wܻw/3&33&3h(0ef {32R7Vo7"I2iR)i%PS(\.wС puuڵ+yACR=hAcX/ƺudVKxaaaϟ?󫨨d44Ա0б4l Eo3㲳c3c2羹CnffFWqy8q"ݙV"^QUQmL>vQQQ QQQɒmtt;k+*vRU3RSRR3Tk=ՒH(M-+ˎΎ..{]SR%A_}U~ |"^ ƒֶ7//oӦMXudB/^ KIIMHHW+(+$Qp9l96[sت*W+K*+K*ye򊢊ҜҲ̢쒊R=0LKKK[[[.]X[[3XZaUuL fffXx<^RRRbbb\\\JJJrrrJJJZZXlb dTj"EP $/T |JΙL>+65!Bbٝ;wܹk-,,+,,,))_^^^ZZZZZ*PV]֜ê!jjjjjj \ߙWVVx<'BaVVV߾}555=zbL&p8l6J4!jq2225 j?u񋦤PM8 !B"B! k{OB`rH:a.X@2>qHO>!oo.¥>TVVz(k޼y=BuN8aaaEDYYY=#V(Jx$@ ^WWWj{>/}AA<OjF/**ھQ+**/))ھ\=ɜ:u*k[\֦*;; Pxuccckkkbddddee\.UPPPTTTTTTUUUUUUWWz??B $m.F(KƙLd\ H-hX,jȨH|f+++Ky<ԂH-쪪%㲲J+(--$BCC6VE-"hHSVV.> !$P͛J8J[ #2rKX`) L`T!H<VG+_J,&y%PURTTTTT'y6&ٵkWCC=zۛtZ9BmUŅK! ڄirU#dU@^ Z"ᕑPU e9dyTiPU’HD޽u֫W.] 0$Fh7Zx%4Eqqݻw^+ @QP A^P2hB2'JsȢda2$gX#Fիͦ1YZ' j۷o_|ɓ'/דP#-AݜP5h55PC$Gf!_A^vɓ'+** aЗв!tю p29N:hРYfИG^^޾}>|XcWZZڲedddN: Xbĉ_xs .蹁ͤ&媢?|uX!p)))ǎ믿RS>cX$t={`t鏂 ѻdk2!@Dg͚5yd7$#B%%%咻sss`֭:{nڵw>|0uBٳgL)S&%YȰ*B!Ν;w#GB ݩх$#DAdr(+\ãUj^#??޽O< >ttt>|hjjZwu4޽w߾}y<+++/"UQee% UaU$5ԋnݺ<|pnذƦC7oޜ @0A an66U{dC ߸qcm+#\Cccc.4IOO3gLIIl=7YqqMJJ `UDFFѣ*(|޾}7߄pݦ3Cw^UUտ@$$bƌ{2B͂?HLHH5kŻ --CݻWSSj>%+ [jUDD6UQ[~%ggŋR |<ٳ'O2!z-\8JfC[ѽYEY[  Ɗ+lRۓjGrrûwm&ӧOڵ5kf6l=zrQQzb6.r u￿{(BShh_ ,v2Dj\d#ٳ>9F1q!C̟?_rXllʕ+'NcLWWСC#FHKK[rŋ骊𳹩w>~;wьoݺ$B͚5k 1si0zmhh(9v?|pm,,,ܹs}[[[%%ŋSs5ّ#GV^op4dPDw}@0l'2z@P) L}*##sQFѝBmU"G~jU 5NTTTTTIÆ l'O\XXx[[/!BtYzdİK"$4CG * oϟ??p@##f$=z3pmRpŋ&LޔdžlB7[?eehiOQ"Q:2j&&DK"w1aPTTӒB ~H7 6qСǏ'&&L8򼽽 tҞ1sڵsAêH."a?Yz>3Zƾ%S'{YsNg%5E?n׀ÃcIAiQCGsmVg1w 9ըS 'YcK'j2j9rzCc]6lpCX]EnUUU޽;WTT;:v޹]z{E2{Xӣ֌1w8&?SuU-,o8o}FŝT4z9FpdnU9+F;vV#L~img CRODW|PPP}𢊊Y UQ.]s]v@WRRRn΢ZbjUh)*{H-b.h'Y=7ޯi"[qINM+1oG&dW癘(RODĴK| 5*jfՇq5ñ;TYYB^Kt?rXqfeecnFps*zJ"( $WVS|xB;g{F%/DM%ut$''ӝBoV;vB<\uV"/^;TQQ/N^囷Dw6KC2 L4e`%^PUo'5$n_i%:KVɱC3#G09sc> 5 u3quX\.HR'vѓa2@DpqV{[}>wO=o&WU^fT<+_xR#yXD,!ԡ/YzWКxpu`- Ebl3saIwCuo &u~.lڴˋl>u g[#xZƊvL7ֶ۶m;TQ;sĉ]?>t\مbZ3MiW›ˡ,aݺutgP{ФgҝEkUQG`bbr֭A `|F?A{>Wuj\dQ۷qLf desdӻABB6yDw rtt puuz@迈1x臘.gdz0<|P^CjIMu*pٳe^ݔiFZUa2.Fq%YɎP"Z`YXf͞={D"O2{!̇ѝWBDo.JFFf˖-˗/5ZẋM6ћB#`ٻw1bČ3v1ݧ}pܨ"Y ___sssB=`X z/gȐ! - ^+ L|SE… ^’UBb0KMM%RD L=Ew"20pT˳PYԽ{eL IDATWǻӝBVE>>>BDP駟_gggVkD$3j>Z#ɤ{G'F !ww/^5jZ?Y"Z-.%loҠT aLӪ] %ܼMw_uԩL&y:EŚ0a„ rrrvqb"Nzz Aw-̉&_IɜPA& o}|^ VE IjU\%''+((xzzғ455wܹsΫWyL &ԉFhٴ I$ 7d;2>yT` 4yo!hтUѥgPXӿ3ڿFm; ρp5GwZk W?YQ=zѣt__k׮4xw&m΄)@EaH$BQ2̏K\.wcǎ1bi"X6l?h08K.<]`t ~7"!9D$kcaH5!!: ʪ>:3-9fU<»L ck=W\*`:0'o06]/ ``4tCx&:|'0i?0--yV'Yzp-ZhѢE$I޺u۷>|Irr2AG|hG![ԉP'5@^I,IB  ,(J&Kk"777wqqqvvׯ)="B}X,֏?͛7UQRy0Hx F~Oq xϷ|l3]ˀ뿾x߬G& V旂fx};su70 |x[(t35£p4䓪H0mCCC֊)Ij=D"$FҥKΝ;O>\[Qk%DAj>AKi?ۆ$\WрՉD?Cj=l6_S}yyytˏ3f̘1KPW^%$$'&&&$$P uϔ&l) 0X@T= HH y !Dzc0={477EjZ*0CdWp܃ _zx.s~܊J"aNz`'v$R 3H}]~Bp]jvR'kil `Uy■+[EY=XsD$uې'޿P[?<o޽͐L] I)))999 JKK I!|hIjjjZZZzzzzzz:::-.Qx `s?ٵHUC\ ~XV{x@NȑyaJau/0dR~zCA5jKd4T0o h E^n^+'[c!n.5zCc*RݬiڴiKll^˗+((Hj44}U Au7eeeUUU|>_ GdddX,r\.WNN׉@"22rѢEtgц͜9UEb2>.@L:ǽ=M WH/,(h8^_q$\|^ąrPJV?5 0~ ` bW :ud}̠!D%7@$怱& nj&\&PZ =Afu7#b̙ӦM;}dm󫪪nZOZ5JjZ0;I5|B*/@L>.AAه+A03Q!7,'p>f@(pP7w\6zGzT@ލ{Il1h&ƮDc4FMD%$ Eww\Vv}g;̝fnR܎EOWF"05ĝXl>㟫\WEx MWܡ2`D{)ݻhp5 qkgb?4Zo՘z;a VǢQ C|+[jMeBPUm{;::HR_uǎi\'QVEQV!_(xc?D@0>Rx3VXbŸ!te _g܌A䪿0mlg7FmV \$c;u]Hd ^2q%OuXM+>V}Tn5& #?<Fś6mڼYF!ׯc{X>5*qd6zL 0-VSrU? P'{>tD4sq['Á<:1ÍX&{"hۇ-]`c6fgUݖ`:PT9Y Y`B7Vn[Q՘-c`h.vSmF[޽;--M ! … ǓyyyVVVV&IOّ= ݀C^pAUX,fFIE4l)SLo>syIƎ;N|u*tTst5r1FQQQ;wH2!UE%~mR_;w.//,Ha !m֬YϷ׼boa dV @uJ֞Bd2J`k/{tĶ%B=+"BUVÆ oϟkwz!'-Fp>vE*&U=#\ YQGYRr/i^~Bя˗FI WpJ-iz`_DvM?&"G>=D^BяVZ?ykm0W_=b9`F`_un&-L݇xs/r.^Y0 "H'07Ma DsGXu5 &x,V=7amUwsx5 @A):.K@b"$ ![|cǤR)󖩍vG?mX3u._!C X(.C Qx0U~3T]mWͮZ鐕6w|s[G?"R,[N$-ZǓ:ILLEB5i$33,!cWԱcwy\fwUn755裏M|"PR06PٳƳg_b|<.6/|+. {Z\'2\Qe1l#r+`z?L'g .ț*¼Ų?f Y/,U+*--e]\\Z^fddkOr{͍D!۷o߾},3oTw{p>6Ŧ/{fV=}qO5=&"7b6CB1VD\~Q|va::,ť{zVW  i7B.9lr޼y\gg/^r@ xww'J!2c˧,`o/(}moߪP.ܹ)fUwW~E V{FiKkg@XݯBg:tСCЧm۶Ukde˖.8".-EHoI]t2d0b2kd P!Aa)̌*[=J+(uKL/4B!Do曊@0y߿G,᰷1xBQ J Zdx(4wаFoA>a_Ǖ>E53nTR9`zxh ~_|^JoƠ֦X1#9+"B(~~N^L@oX@w[ oWR,5,qk 3 E0 "D&'CS{ l [Z=10 6-[|𠦻BJa~~( `رW|X~zPܯH駟ָr)%+=(@{ntt4y~ ˖Uu}[ϟG^d '!;v,)>tHCwv\{B!\k޶w7Q4z0z\9S"x"ޤOQ\_Wi=}z`:Yyo! ^Quy>ʰVиe2zœ0Q@BQ7NH]OUs<Si;q]_x 'tƉPLUW%ѓ'wdH2D9 [0Uab޾n\/X :u\tYqBiᵒki!MڰХZ>K҇kaЂi9Sx$\*nȐdw5.rg͙EASnHv1)/jD!?Y-a5UkޯyҼv0|< IX-YNcVAAJg[V^ԏp"99@# Zu*Mq9jfxwcut̋P+(AUg`B77LUE7Jo 1bɷ / ) )+*c~DuO']*$tz 狪qbdq"Rii8)$Dy]m\)U%?kPɄGT.]( c6FMP㍐$N:YpI4bjS3iBE¥KBgf\,>3t=,"Eb'+S ykmiزI؟YŚQ$%%,_t׶x.-[L$^{U5<,h=3i ?#!pvVI86K Z*/'X`j)O㗫)¨~Zxi"_BVVY:QƔul>)1qx52n`[,Oj;il d ) a&oo^1F {͙D3a3@`711`//"HZd7-T(!qoQzC{7^r] i?~|KMz?,x&SfjH]8j>LU!\QD W\]]:cBWSo֟AB>'*b +"u̙ >Z!+NypŶp..Hx U> ]C!M̱>+K#&w_)]_K`eI;+"5S~ h,|{*RFiypf5Rs54*vE $ZƋx"gg俲?vqʱcBКo"tdɔ_}Z4ly:>x"I܄nf|3&0oLcT$[͕j)Ay lkuO[ 1IwV=4@ޭNԏp3V%,^@@uD@&OB֪H,cTQ< cϧug5'kV$ Pծ)py#ጆqn~κyYU{:E:a.gk$D'4^n%ʼn҂LIf$3Cʑm )UѨò| }kRECfZ4ӗ̐g tHK+[AA4PZ$t2ʃxf+5jB^qŸY=>m``P-@IIg}&+/'Wa\?%h]$`bPy* Yh6-_aZ'!ypjhX}l8Zj!:i"h$Nʒd9 dJ2P.+PtA9aɷyUT$-Bj3d$(~Ԅe9hp-).SRcccccb4ď۷a>񃪢WĹs; l%ŁIF,_* [=UBŋ_,걌 ;;oTD"پ}P(dOn ȃ4&>>LL Gyנ'ʼn|&$"DnnnZ`bOSoVDYD"_|-UE4F 53h9Nqj !3',u*͆3!B:^i RrtPm!&*&> Pc@Q^up8mFIեBkO!87O wcqBo^ܥUN:b<[nZ=߰VUH$D#j3r 0]OtUab>2>@q̛Bɸi4p7KJcS\j7Ч"=];,# DB K/p[[VRӛ`r~D ᔚޙ;Эz]q&TEw=uT@@@xx8s!C=zNN*_ ]V'VX9-_nWǠ5O&Iw ުI}Nyʲ7-ŠYV'E O~D|$hVCx^a3xHaa09:*]~+iӛ-FS?2v=10MT G^HB3vU7:^8+HU;V *޳VD" bXbG>|Nb_|!l:Ҁt 2xv]x_oL=~So-0vD6ٶ[BdQ^a؃C?X*)"V@&F05 QٿMoW_!W~-y>@wFu]#Ƈ{`I$U [ITm- 6޴prCaVCiǞ~ kNpiI8ViѢENN0<<<<<\1r,'o޼YUDUݸQ׀yr= D#'ٷ1XkMլ^B &dajhVoodPo ЛaF a\??oأv%Ň'gQꯜDGGK$___&АaׯH$-Bae9DU>}Z* T$m7+W0qC=P~9jv}3fѪYڍs2dX,>{," l!Q!)eCd 򇓕G鐀mx ōtScڬ ur% 7\Q}koL5hj GQF_|&'V6 @zRs1`Uv8zz١9/^|ƍĝ;w2Ξ=ӳcǎWС⧪H #Ǝ syU8GQ3>w4xVwg[Bg}]eomζpnE}1B:ev=1$Vmqu6H5kըJVdFS!%8G[ʒ%|:莕mB Vx BaJUKT2n>Ÿz7\\\>K.eddT^a;vl'PyN;GUO}?,N>v5"=cfƌɩK.W\:/B^Ⱦ ig)Dm%Ҁ,UU8D2446l?rڵaÆiUET^^~yGfZWDs\}NacF[u]%5huռm6mZy_1c,ZٳD _ uCUg=+3`j*KKW6úFU(TFڽ{w@@UE=un; ;X}jjFVNGw&,sޡGqR4"~QURtСzbgرc˖-[latȐ!C y)FTQgj3RTUE'nel_`b jDO;cj3LßU0$uUĬf&7}'-?$02;Df^-SbVgO3J\m ݩZ@Oy|zZVaEٞAtLX| Fy yßɞn#էƢdOCcy.+2;Z>?T-9*ndS/o{Q[jxyP+iEkMZ]Ăs;k|P ]_' ~;soU7>S\{ "Inȓܜ ѹQ3~koHNiG%Q:MLLN4(u777~6yZ͙X&55Vj ގ`k&2 Fn6F'4u[wsYkNHe2f)w[ ZHeoNx)Yz~9Y0cq5rL@Ѫbld_/{ckSцZXw6Fŵ섮6+Rs䗈φgy+NCRI5?BRR[LH,f۱QHğy!_c_p T>^v섕`?R/yzqLY _oP&f2샿Jߨ)߯oi,e$7.d<(N)X_(HeV&Bcz % A#af" wO>,3 ])eG95[\63~ua<16}~8+]Ue~S<hd&f"hqV=B\vQŸN:9Ul:F :ښ:IzqmB itl `lj٥Y ?ڦۧddnޖj:\tqBVibv#,JeojOg]2Ujn§~Gsvnf>jkkBfZ.`i8~A\ ])~.kOrߢMo7>^V& lL'{<tKeV&B>chQŝ=lr*^|GKBa i$[.KwV\cO GtI!UFsE4Fvܽ_&F!K"T\.a.Z9֛J"BNH$@`nSB8v7~H,060?YԝLڦہNV;u:,33svvv֭:n:s!BsA#B*"BaPUD!£Gu̘1ys%%Rר*bbb6nu 4"\ uI&",/ P $ O: R9rdڴi\gAJXXXv΢񢪨NB;;; =ЍM}vH&I UEf00: WyMn߾}N{T  4X|Ͼ^΂Dzldff6ens]F!PUTUOէjj'B-{WTj!3TGtڰB1M#ݰBM8CX\WL& M_p8B&7wjjan$T\[Mo@%Lo}wl" gP |OۚVxK{#zȦRhheL&tqbIvxͩ_KVծ5b[]LEg2g*,oz$@fV?ײkvB!AsEuB,'''UoӤW! q1Z2K}Ol==hiqyH]m]Ʉþ3MUjP+!o7Zk[uB:.q5Z8) %~#}},շv0gqk3h $Rq7:3wv8v3RGT3kwR>HWi+i]u`j(_~?@ a\'u= ~xcE׶抝w>̓i3#~o* ]CwɷvQӮ5joXxd{e~ 3Cm"AK/_FFo=g UEuѣG:Xp8:5,-|跻9j٬(I޸v_p8:-<5lFgI\WGgr&Wf2gnj_\{[T&yZ4sovNԴk?}]>-2YINQcOtW?vtal'7k !uvMR9+UV6w¼xuR***:|sN3T5|YGl s4:ц^IGNr*ۋ%]FF58[1l"3Qډv]1a?Ћ NmkoUh9ofفδԠB^&]wuO G2 MI TufHVv5ۄhX0~BsGK  IS|a^m E|CANaҙN- 6LhqV ϗRL]IVݚY;|?O};k'jڵO$^K/{cC![3˓s4?q=?fR{n6nUIV\(pGۧ`vf7IfwHyqU2QzJUe?+ԸLKEUQ}5 r/y|ק{ǹwqgu gcwri;l=;XuiVaŝYPuӚ$7=tO)[{&iq%am|4CY;QӮ0w\I/:}ᅠ#X *҈i !GIMR9tٰ5#J-NKCGq^Sla=T4n~Hw޳U +,9k/{oY|!n8?kNTbT&~9ax5B- }'Ҝ)~<^_$Dv44]ݤc-*x'M<΄er7I" MWM*(6ɷiNQSY;QJUe=G;aX|wS}] <QQjmB8GIZjZnX#RMv膆y,QUT' <==]\[^NrNs !@I㦦gY5TՉ͛j>RBBYN4d꭫FU,7O81xڴi]vHcDIajj:n8UE@=2r ѿgZwNUPZZ @V^$KWqJ^֨?V766uQH9hBUQ=gm΅Ϻ) Ȟ\eF|+d `3fL w.UEx ,:If$*"UN$- -"IdtB:{u.P)>:$#!B@U!B:Q^^MBGGpg輢:cs!BR\\|Yooo B!TB!0*"B*"BaPUD!PUD! +넑f͸NBіK*(QUT'NEBcc!Cp!B@U!B"B!"B!UEB!UEB! DiiiXXXTT׉B!JMM/ŭIDAT0`ɓN3t::]!7׉p!B!Bt[\ggΜu*/HMM::qqK-``uTGU?H*N3bX,s d2)Ѓڷou"GY0~/΂*"`jsGhćFY>Y_c+h|*JQ^u7<wKg),-\gA;u&&&]vm7BwN3TՉM^~,!ٓ,DWB!TB!0*"B*"BaPUD!PUD! Nw:Bٳ~ikw^a!7JIIڵqN3TՉ>}\'B7RSS͛״iӋ/省gٲeP3{iLu \YYYhh{N3TXQ{00cG hiU2>NG>m_OF'2KOHHO6o\XXzjrV zԩ|󍗗ך5k zT ȓ%r i*" ؚFn k߭_;t=u(/N2i`עN!Or;n߳?ՑL^ǏO>Yf}ii)^z :%_~Wޛ7o.))qoK[{WjܹqVՊd1%?" %K+{/?xPUD-~^\.f M>dM2vyz+SC_w![zW]?kS+SQLTX>?^O*-KCc.󑡐eOҶInc({ɷ ~K+3y+z?w?i{jDjܿҤI~~~{쩨^ZN~̙y5klΝvaiJ2,4tTdOa`kOwpILN4dT!L&JlT3A*?TE%&2=K*X?wMk٣ ۳`rlՃ{Z:Tޕ7gurzZNQ6_}`@KCX\w͛7&K)7Z#d~}һf'Ay%ۧ|Q,!ۤ QnQr!W<,-KQnhC=45팵cJ3~7.C˻?,2Ô2ۯ$֋bL}ϕgؚRL4aI9>?v2}/*- WU*zdGjDz?Sէ-ZBP _(65ׯߥK󉋋>} V\Yq6 yW,:gXo S>+(bw)zJYVF4wkQӮ*[yUS$^6 rjr`j-P/K!M܆r+;<4 xN,H*d<fl% xLYeLxLŗȊt(g"Y%***Xƛ2^;;;7gvUB-,eTҧ|}<>"vV|n<Bx85^ʓOW|af0w[zTOBv)QjQdrNGB$/!#m&06U L\8ڮ*+kνP*%%E/Wttĉ=<< VSڲRS=wkQUr$#_m` R$(l Fdώc)9 maό\ZI0x-K|]_Y=z ˒B%$Ͳ^iSRRVZs'x+ϛ7oӦME"Q#/*~~~٦|N}\: 2n*N3f}6;?+zG:JQ2YR=dL.ࣘͽ$f FQ,_IX>Hhg?%orqE8n8QjnYS;㨔"&)9:*RURvɃnS-O59hqÇTݑ[tX,H$mc5FGGGDDmgg7jԨNՔTϪaTȍʥ֞yRt}e+F&;n5|!.InN6x.]g+CBBΜ9Ӿ}{ycqq֭_;vyzzڵ+&&/055ղ~:}Wk#C!OڪgT_gS!Gϔh]\j_U+gTM팭MEaMU_9`· 7#KY^4щҐ[p7O;i+N<9Y-Fy,ee"d=ZժDZXh#ѥR5kQծ*[|NoNn9>( o1 T~_,K>nE<׮|<*NRl2G'yxxqJC@UQ=@UW!Hv ՔUS;"h̙ӧOOKK{iUիW92dMtZ%ҽgkNGc~˱6T#0Nh[Es7N/$<+V=DyPUD!I?: BFWB!TB!0*"B*"BaPUD!PUD! +I}SQanѓ! UE\m#$.eEsD#+!H!2%Ip sssCCCSy_%g>: B+"Ro.:nH6ɞ\ٱcԩSΥ011ܹ3Yгgbccah3w:Z0s:BXPUDitZhu5oM6֍k׹ pB!}B!B!AU!B@U!B"B!"B!UEB!UEB! !B!BTB!TB!0*"B*"BaPUD!PUD! B!\'@!Dg\YfYW@I.4(TBH#K $r! UERу,ȫ!>6lذaø΂ζ&B*"BazC# ,2p!4 TEϤO.s!`d29 / ٳ7YBHC龿GYIENDB`libjson-rpc-cpp-0.7.0/dev/ci.sh000077500000000000000000000033361275256467400162570ustar00rootroot00000000000000#!/bin/bash set -e build_configuration() { echo "Building configuration $1" mkdir -p build cd build cmake $1 .. make mkdir -p root make DESTDIR=root install cd .. } cleanup() { cd build make DESTDIR=root uninstall make clean rm -f sampleclient rm -f sampleserver cd .. rm -rf build } rm -rf reports mkdir -p reports build_configuration "-DCMAKE_BUILD_TYPE=Debug -DHTTP_SERVER=YES -DHTTP_CLIENT=YES -DCOMPILE_STUBGEN=YES -DCOMPILE_EXAMPLES=YES -DCOMPILE_TESTS=YES -DUNIX_DOMAIN_SOCKET_SERVER=YES -DUNIX_DOMAIN_SOCKET_CLIENT=YES" echo "Compiling examples" cd build g++ ../src/examples/simpleclient.cpp -Iroot/usr/local/include -Lroot/usr/local/lib -ljsonrpccpp-client -ljsoncpp -ljsonrpccpp-common -lcurl -o sampleclient g++ ../src/examples/simpleserver.cpp -Iroot/usr/local/include -Lroot/usr/local/lib -ljsonrpccpp-server -ljsoncpp -ljsonrpccpp-common -lmicrohttpd -o sampleserver test -f sampleclient test -f sampleserver echo "Generating valgrind report" valgrind --leak-check=full --xml=yes --xml-file=../reports/valgrind.xml ./bin/unit_testsuite --reporter=junit --out=../reports/tests.xml echo "Generating coverage report" gcovr -e "build" -e "src/test" -x -r .. > ../reports/coverage.xml gcovr -e "build" -e "src/test" -r .. --html --html-details -o ../reports/coverage.html echo "Generating cppcheck report" cppcheck -I ../src --enable=all --xml ../src --xml-version=2 2> ../reports/cppcheck.xml cd .. echo "Cleanup that mess" cleanup build_configuration "-DCMAKE_BUILD_TYPE=Debug -DHTTP_SERVER=NO -DHTTP_CLIENT=NO -DCOMPILE_STUBGEN=YES -DCOMPILE_EXAMPLES=YES -DCOMPILE_TESTS=YES -DUNIX_DOMAIN_SOCKET_SERVER=NO -DUNIX_DOMAIN_SOCKET_CLIENT=NO" cleanup echo "Integration successful" libjson-rpc-cpp-0.7.0/dev/codestyle/000077500000000000000000000000001275256467400173135ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/dev/codestyle/eclipse_codetemplates.xml000066400000000000000000000006261275256467400243760ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/dev/codestyle/eclipse_formatter.xml000066400000000000000000000422571275256467400235560ustar00rootroot00000000000000 libjson-rpc-cpp-0.7.0/dev/codestyle/license.txt000066400000000000000000000005671275256467400215060ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file %FILENAME% * @date %DATE% * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ libjson-rpc-cpp-0.7.0/dev/codestyle/qtcreator.xml000066400000000000000000000032141275256467400220410ustar00rootroot00000000000000 CodeStyleData false false true true true false true false true true false true false true false 4 true true 2 true 4 DisplayName bitmovin libjson-rpc-cpp-0.7.0/dev/createpackage.sh000077500000000000000000000005451275256467400204420ustar00rootroot00000000000000#!/bin/bash echo "Bundling for $1" mkdir -p ../dist/libjson-rpc-cpp mkdir -p ../dist/libjson-rpc-cpp/doc cd ../doc doxygen libjson-rpc-cpp.doxyfile mv html/* ../dist/libjson-rpc-cpp/doc #cmake -DCMAKE_INSTALL_PREFIX=../dist/libjson-rpc-cpp #make install #cd ../dist zip -r libjson-rpc-cpp-$1.zip libjson-rpc-cpp rm -r libjson-rpc-cpp cd ../dev libjson-rpc-cpp-0.7.0/dev/installdeps.sh000066400000000000000000000001661275256467400202010ustar00rootroot00000000000000#!/bin/bash sudo apt-get install libmicrohttpd-dev libjsoncpp-dev libcurl4-openssl-dev cmake cppcheck valgrind gcovr libjson-rpc-cpp-0.7.0/dev/testcoverage.sh000077500000000000000000000004771275256467400203620ustar00rootroot00000000000000#!/bin/bash cd ../build echo "Building debug build" cmake -DCMAKE_BUILD_TYPE=Debug .. make -j4 echo "Executing Test Suite" bin/unit_testsuite echo "Generate HTML report" mkdir -p reports gcovr -r .. -d -e "build" -e "src/test" --html --html-details -o reports/coverage.html xdg-open reports/coverage.html cd ../dev libjson-rpc-cpp-0.7.0/doc/000077500000000000000000000000001275256467400153075ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/doc/doxyfile.in000066400000000000000000000007611275256467400174660ustar00rootroot00000000000000DOXYFILE_ENCODING = UTF-8 PROJECT_NAME = libjson-rpc-cpp PROJECT_NUMBER = @MAJOR_VERSION@.@MINOR_VERSION@.@PATCH_VERSION@ PROJECT_LOGO = @CMAKE_SOURCE_DIR@/dev/artwork/logo_small.png PROJECT_BRIEF = FILE_PATTERNS = *.cpp *.h INPUT = @CMAKE_SOURCE_DIR@/README.md @CMAKE_SOURCE_DIR@/src/jsonrpccpp @CMAKE_SOURCE_DIR@/src/stubgenerator RECURSIVE = TRUE EXCLUDE_PATTERN = */test/* USE_MDFILE_AS_MAINPAGE = README.md OUTPUT_LANGUAGE = English GENERATE_TREEVIEW = YES BRIEF_MEMBER_DESC = YES libjson-rpc-cpp-0.7.0/doc/manpage.in000066400000000000000000000100511275256467400172440ustar00rootroot00000000000000.\" Manpage for jsonrpcstub. .\" Contact psk@autistici.org to correct errors or typos. .TH man 1 "7 April 2015" "@MAJOR_VERSION@.@MINOR_VERSION@.@PATCH_VERSION@" "jsonrpcstub man page" .SH NAME jsonrpcstub \- genearate stubs for the libjson\-rpc\-cpp framework. .SH SYNOPSIS .B jsonrpcstub specfile.json [\-\-cpp\-server=namespace::ClassName] [\-\-cpp\-server\-file=classqname.h] [\-\-cpp\-client=namespace::ClassName] [\-\-cpp\-client-file=classname.h] [\-\-js\-client=ClassName] [\-\-js-client-file=classname.js] [\-h] [\-v] [\-\-version] .PP .SH DESCRIPTION .PP jsonrpcstub is a tool to generate C++ and JavaScript classes from a procedure specification file. .SS SPECIFICATION SYNTAX .PP The specifictaion file is a JSON file containing all available JSON\-RPC methods and notifications with their corresponding parameters and return values contained in a top\-level JSON array. .PP .nf [ { "name": "method_with_positional_params", "params": [3,4], "returns": 7 }, { "name": "method_with_named_params", "params": {"param1": 3, "param2": 4}, "returns": 7 }, { "name": "notification_without_parmas" } ] .fi .PP The literal in each \fB"params"\fP and \fB"returns"\fP section defines the corresponding type. If the \fb"params"\fP contains an array, the parameters are accepted by position, if it contains an object, they are accepted by name. .SH OPTIONS .IP \-h Print usage information. .IP \-v Print verbose information during generation. .IP \-\-version Print version info and exit. .IP \-\-cpp\-server=ClassName Creates a Abstract Server class. Namespaces can be provided using the :: notation (e.g. ns1::ns2::Classname). .IP \-\-cpp\-server\-file=filename.h Defines the filename to use when generating the C++ Abstract Server class. If this is not provided, the lowercase classname is used. .IP \-\-cpp\-client=ClassName Creates a C++ client class. Namespaces can be provided using the :: notation (e.g. ns1::ns2::Classname). .IP \-\-cpp\-client\-file=filename.h Defines the filename to use when generating the C++ client class. If this is not provided, the lowercase classname is used. .IP \-\-js\-client=ClassName Creates a JavaScript client class. No namespaces are supported in this option. .IP \-\-js\-client-file=filename.js Defines the filename to use when generating the JavaScrip client class. .SH EXAMPLES .PP Generate C++ Stubs for Server and Client, the classes will be named AbstractStubServer and StubClient: .P P .B \& jsonrpcstub spec.json \-\-cpp\-server=AbstractStubServer \-\-cpp\-client=StubClient .B .PP Generate JavaScript Client class MyRpcClient into file someclient.js: .PP .B \& jsonrpcstub spec.json \-\-js\-client=MyRpcClient \-\-js\-client\-file=someclient.js .B .SH EXIT STATUS This command returns 0 if no error occurred. In any other case, it returns 1. .SH SEE ALSO https://github.com/cinemast/libjson\-rpc\-cpp .SH BUGS No known bugs. Please report found bugs as an issue on github or send me an email. .SH COPYRIGHT Copyright (C) 2011\-2015 Peter Spiess\-Knafl Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. .SH AUTHOR Peter Spiess\-Knafl (dev@spiessknafl.at) libjson-rpc-cpp-0.7.0/docker/000077500000000000000000000000001275256467400160115ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/docker/Dockerfile000066400000000000000000000025241275256467400200060ustar00rootroot00000000000000# THIS DOCKERFILE DOWNLOADS AND COMPILES CURL, LIBMICROHTTPD, JSONCPP, ARGTABLE AND LIBJSON-RPC-CPP FOR LINUX/DEBIAN # 2015, author: Péricles Lopes Machado (gogo40) # Based on Victor Laskin Dockerfile (http://vitiy.info/dockerfile-example-to-compile-libcurl-for-android-inside-docker-container/) FROM debian:sid MAINTAINER Péricles Lopes Machado # Create output directories # Directory to export generated files RUN mkdir /output # Directory with generated files RUN mkdir /build && mkdir /build/include # Install compilation tools RUN apt-get update RUN apt-get install -y \ wget \ build-essential \ cmake \ libjsoncpp-dev \ libargtable2-dev \ libcurl4-openssl-dev \ libmicrohttpd-dev \ git # Clone and build libjson-rpc-cpp RUN git clone https://github.com/cinemast/libjson-rpc-cpp.git RUN cd /libjson-rpc-cpp && \ cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_STATIC_LIBS=ON -DBUILD_SHARED_LIBS=ON \ /libjson-rpc-cpp RUN cd /libjson-rpc-cpp && \ make -j $(nproc) && \ make install # Copy to output generated files RUN cp -r /libjson-rpc-cpp/lib /build RUN cp -r /usr/local/include/jsonrpccpp /build/include/jsonrpccpp # To get the results run container with output folder # Example: docker run -v HOSTFOLDER:/output --rm=true IMAGENAME ENTRYPOINT cp -r /build/* /output libjson-rpc-cpp-0.7.0/docker/build_linux_debian_libs.sh000077500000000000000000000001731275256467400232020ustar00rootroot00000000000000#!/bin/bash docker build -t debian/libjson-rpc-cpp . docker run -v $PWD/output:/output --rm=true debian/libjson-rpc-cpp libjson-rpc-cpp-0.7.0/src/000077500000000000000000000000001275256467400153315ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/src/catch/000077500000000000000000000000001275256467400164135ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/src/catch/CMakeLists.txt000066400000000000000000000011311275256467400211470ustar00rootroot00000000000000cmake_minimum_required(VERSION 2.8) project(catch_builder CXX) include(ExternalProject) find_package(Git REQUIRED) ExternalProject_Add( catch PREFIX ${CMAKE_BINARY_DIR}/catch GIT_REPOSITORY https://github.com/philsquared/Catch.git TIMEOUT 10 UPDATE_COMMAND ${GIT_EXECUTABLE} pull CONFIGURE_COMMAND "" BUILD_COMMAND "" INSTALL_COMMAND "" LOG_DOWNLOAD ON ) # Expose required variable (CATCH_INCLUDE_DIR) to parent scope ExternalProject_Get_Property(catch source_dir) set(CATCH_INCLUDE_DIR ${source_dir}/include CACHE INTERNAL "Path to include folder for Catch") libjson-rpc-cpp-0.7.0/src/examples/000077500000000000000000000000001275256467400171475ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/src/examples/CMakeLists.txt000066400000000000000000000055051275256467400217140ustar00rootroot00000000000000file(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 ) 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 ) add_custom_target(common_stubs 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 ) include_directories(..) include_directories(${CMAKE_BINARY_DIR}) include_directories(${JSONCPP_INCLUDE_DIRS}) include_directories(${MHD_INCLUDE_DIRS}) 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 (UNIX_DOMAIN_SOCKET_SERVER AND UNIX_DOMAIN_SOCKET_CLIENT) 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 (TCP_SOCKET_SERVER AND TCP_SOCKET_CLIENT) if(HTTP_SERVER) add_executable(simpleserversample simpleserver.cpp) target_link_libraries(simpleserversample jsonrpcserver) endif() if(HTTP_CLIENT) add_executable(simpleclientsample simpleclient.cpp) target_link_libraries(simpleclientsample jsonrpcclient) endif() if (COMPILE_STUBGEN) 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() if(HTTP_SERVER) add_executable(stubserversample stubserver.cpp ${CMAKE_BINARY_DIR}/gen/abstractstubserver.h) target_link_libraries(stubserversample jsonrpcserver) endif() endif() libjson-rpc-cpp-0.7.0/src/examples/index.html000066400000000000000000000022231275256467400211430ustar00rootroot00000000000000 Title of the document libjson-rpc-cpp-0.7.0/src/examples/server.key000066400000000000000000000015671275256467400212000ustar00rootroot00000000000000-----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQD1dyyZredY6EMNBEdmOuMStw/bRfYhsT7wPv3JM++FDUxgittP AqERrH/DiE9XxI9UMEH8mYxGYtOAY6iWL16Q1z6c2/BpPoZBsq92jiiQyZsSCJBO DAmk3zG6FXInD94NDZK/0eyLNFO4rQFjg4OqH7zvY6kPTimJkTbOcsR58QIDAQAB AoGANAv44P0GuMtGrFPj78E8tJMsQYosDijO95Hjre3dM5EGSNIofjBIhr7UuFkG uc1rtqYk17KXE7WQswBulqmkmxc3UevHU/TFy+/DQKNOMChigqkLwSVDFLcVKJzH a1PisWne+Lu4EcgapIIlilzT5sAqIwmc3sFH8rmS7q3S9iECQQD+h71htmJDcT7u ck8PvjM1m+2qqpPomRZm7GBQfd9fG3I+T6dJeC/ik9l8hdn++wKxYZGi4EZ9h20P 2cd5nwOXAkEA9uII1ZRgXX/++sjdF9w6Fe/n4BBHmuMuofHwW0gjOgIHMpboSj7B mSXGMZ+1sDC/0kO58bdjAlMKpOzdsVd/twJAHL9kCmc5Dfj6bKAIgfSvf/yOiVoe voSb3SAReMXetrU44ATLFic28VZVmBTeHEhpc3NbqZO/ImprTQEB4KCvHQJBAJJq PRkFdR0ecsaiZ1TmO+CUteyRWxYFk7thc81++71ERKaBDuQxUbmUyHTXpfYHA0wc 9GLhAqv3OcHT5CpvnQMCQFTK9X6R9NbAoAs1eLh+ONvVwXdL1VvzSs29zvdT8oNS E3d6uNc9Iq0IUh7EDCBQFOdXmTw8+NWbtwW4iHcDNfo= -----END RSA PRIVATE KEY----- libjson-rpc-cpp-0.7.0/src/examples/server.pem000066400000000000000000000015531275256467400211640ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIICWDCCAcGgAwIBAgIJAOV3EU5rFx4NMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX aWRnaXRzIFB0eSBMdGQwHhcNMTQxMTEwMTQzNTU0WhcNMTUxMTEwMTQzNTU0WjBF MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50 ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB gQD1dyyZredY6EMNBEdmOuMStw/bRfYhsT7wPv3JM++FDUxgittPAqERrH/DiE9X xI9UMEH8mYxGYtOAY6iWL16Q1z6c2/BpPoZBsq92jiiQyZsSCJBODAmk3zG6FXIn D94NDZK/0eyLNFO4rQFjg4OqH7zvY6kPTimJkTbOcsR58QIDAQABo1AwTjAdBgNV HQ4EFgQUx500xprMAWKb7YRA0L/LcW7myBMwHwYDVR0jBBgwFoAUx500xprMAWKb 7YRA0L/LcW7myBMwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOBgQCPyWtk zOItY/N2sUxqI2yBMJndV3nSWO1UU14w8awM7pzgwM+Hsqw9dHdIzX0Z7yomABbX tok9QYmE7uNajgiZ/qY8QgBuVSSSdoO0vLvRgqVPcBCLos56brVq29yrIZsMmqQ0 QDlCb5ad9okD+cg5jtK3j/Q1lOgWbo+wwwjgJQ== -----END CERTIFICATE----- libjson-rpc-cpp-0.7.0/src/examples/simpleclient.cpp000066400000000000000000000011331275256467400223410ustar00rootroot00000000000000/** * @file simpleclient.cpp * @date 03.01.2013 * @author Peter Spiess-Knafl * @brief This is a simple client example. */ #include #include #include using namespace jsonrpc; using namespace std; int main() { HttpClient client("http://localhost:8383"); Client c(client); Json::Value params; params["name"] = "Peter"; try { cout << c.CallMethod("sayHello", params) << endl; } catch (JsonRpcException& e) { cerr << e.what() << endl; } } libjson-rpc-cpp-0.7.0/src/examples/simpleserver.cpp000066400000000000000000000034531275256467400224000ustar00rootroot00000000000000/** * @file main.cpp * @date 01.08.2011 * @author Peter Spiess-Knafl * @brief main.cpp */ #include #include #include #include #include #include using namespace jsonrpc; 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); } //method void sayHello(const Json::Value& request, Json::Value& response) { response = "Hello: " + request["name"].asString(); } //notification void notifyServer(const Json::Value& request) { (void)request; cout << "server received some Notification" << endl; } }; int main() { try { HttpServer server(8383); SampleServer serv(server); if (serv.StartListening()) { cout << "Server started successfully" << endl; getchar(); serv.StopListening(); } else { cout << "Error starting Server" << endl; } } catch (jsonrpc::JsonRpcException& e) { cerr << e.what() << endl; } //curl --data "{\"jsonrpc\":\"2.0\",\"method\":\"sayHello\",\"id\":1,\"params\":{\"name\":\"peter\"}}" localhost:8383 //curl --data "{\"jsonrpc\":\"2.0\",\"method\":\"notifyServer\", \"params\": null}" localhost:8383 } libjson-rpc-cpp-0.7.0/src/examples/spec.json000066400000000000000000000015331275256467400207760ustar00rootroot00000000000000[ { "name": "sayHello", "params": { "name": "Peter" }, "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" } ] libjson-rpc-cpp-0.7.0/src/examples/stubclient.cpp000066400000000000000000000030461275256467400220320ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file stubclient.cpp * @date 01.05.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include #include "gen/stubclient.h" #include using namespace jsonrpc; using namespace std; int main() { Json::Value a = 3; Json::Value b = "3"; std::map responses; responses[a] = b; responses[b] = "asölfj"; cout << responses[b] << endl; if (a == b) { cout << a.toStyledString() << " == " << b.toStyledString() << endl; } else { cout << a.toStyledString() << " != " << b.toStyledString() << endl; } HttpClient httpclient("http://localhost:8383"); //StubClient c(httpclient, JSONRPC_CLIENT_V1); //json-rpc 1.0 StubClient c(httpclient, JSONRPC_CLIENT_V2); //json-rpc 2.0 try { cout << c.sayHello("Peter Knafl") << endl; c.notifyServer(); cout << " 3 + 5 = " << c.addNumbers(3,5) << endl; cout << " 3.2 + 5.3 = " << c.addNumbers2(3.2,5.3) << endl; cout << "Compare: " << c.isEqual("Peter", "peter") << endl; cout << "Build object: " << c.buildObject("Peter", 1990) << endl; } catch (JsonRpcException& e) { cerr << e.what() << endl; } } libjson-rpc-cpp-0.7.0/src/examples/stubserver.cpp000066400000000000000000000042611275256467400220620ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file stubserver.cpp * @date 02.05.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include #include "gen/abstractstubserver.h" #include #include using namespace jsonrpc; using namespace std; class MyStubServer : public AbstractStubServer { public: MyStubServer(AbstractServerConnector &connector, serverVersion_t type); virtual void notifyServer(); virtual std::string sayHello(const std::string& name); virtual int addNumbers(int param1, int param2); virtual double addNumbers2(double param1, double param2); virtual bool isEqual(const std::string& str1, const std::string &str2); virtual Json::Value buildObject(const std::string &name, int age); virtual std::string methodWithoutParameters(); }; MyStubServer::MyStubServer(AbstractServerConnector &connector, serverVersion_t type) : AbstractStubServer(connector, type) { } void MyStubServer::notifyServer() { cout << "Server got notified" << endl; } string MyStubServer::sayHello(const string &name) { return "Hello " + name; } int MyStubServer::addNumbers(int param1, int 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; } Json::Value MyStubServer::buildObject(const string &name, int age) { Json::Value result; result["name"] = name; result["year"] = age; return result; } string MyStubServer::methodWithoutParameters() { return "Test"; } int main() { HttpServer httpserver(8383); MyStubServer s(httpserver, JSONRPC_SERVER_V1V2); //hybrid server (json-rpc 1.0 & 2.0) s.StartListening(); cout << "Hit enter to stop the server" << endl; getchar(); s.StopListening(); return 0; } libjson-rpc-cpp-0.7.0/src/examples/tcpsocketclient.cpp000066400000000000000000000017501275256467400230540ustar00rootroot00000000000000/** * @file tcpsocketclient.cpp * @date 17.07.2015 * @author Alexandre Poirot * @brief tcpsocketclient.cpp */ #include #include #include #include using namespace jsonrpc; using namespace std; int main(int argc, char** argv) { string host; unsigned int port; if(argc == 3) { host = string(argv[1]); port = atoi(argv[2]); } else { host = "127.0.0.1"; port = 6543; } cout << "Params are :" << endl; cout << "\t host: " << host << endl; cout << "\t port: " << port << endl; TcpSocketClient client(host, port); Client c(client); Json::Value params; params["name"] = "Peter"; try { cout << c.CallMethod("sayHello", params) << endl; } catch (JsonRpcException& e) { cerr << e.what() << endl; } } libjson-rpc-cpp-0.7.0/src/examples/tcpsocketserver.cpp000066400000000000000000000036321275256467400231050ustar00rootroot00000000000000/** * @file unixdomainsocketserver.cpp * @date 11.05.2015 * @author Alexandre Poirot * @brief unixdomainsocketserver.cpp */ #include #include #include #include #include #include using namespace jsonrpc; 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); } //method void sayHello(const Json::Value& request, Json::Value& response) { response = "Hello: " + request["name"].asString(); } //notification void notifyServer(const Json::Value& request) { (void)request; cout << "server received some Notification" << endl; } }; int main(int argc, char** argv) { try { string ip; unsigned int port; if(argc == 3) { ip = string(argv[1]); port = atoi(argv[2]); } else { ip = "127.0.0.1"; port = 6543; } cout << "Params are :" << endl; cout << "\t ip: " << ip << endl; cout << "\t port: " << port << endl; TcpSocketServer server(ip, port); SampleServer serv(server); if (serv.StartListening()) { cout << "Server started successfully" << endl; getchar(); serv.StopListening(); } else { cout << "Error starting Server" << endl; } } catch (jsonrpc::JsonRpcException& e) { cerr << e.what() << endl; } } libjson-rpc-cpp-0.7.0/src/examples/unixdomainsocketclient.cpp000066400000000000000000000011301275256467400244310ustar00rootroot00000000000000/** * @file unixdomainsocketclient.cpp * @date 11.05.2015 * @author Alexandre Poirot * @brief unixdomainsocketclient.cpp */ #include #include #include using namespace jsonrpc; using namespace std; int main() { UnixDomainSocketClient client("/tmp/unixdomainsocketexample"); Client c(client); Json::Value params; params["name"] = "Peter"; try { cout << c.CallMethod("sayHello", params) << endl; } catch (JsonRpcException& e) { cerr << e.what() << endl; } } libjson-rpc-cpp-0.7.0/src/examples/unixdomainsocketserver.cpp000066400000000000000000000025751275256467400244770ustar00rootroot00000000000000/** * @file unixdomainsocketserver.cpp * @date 11.05.2015 * @author Alexandre Poirot * @brief unixdomainsocketserver.cpp */ #include #include #include #include #include using namespace jsonrpc; 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); } //method void sayHello(const Json::Value& request, Json::Value& response) { response = "Hello: " + request["name"].asString(); } //notification void notifyServer(const Json::Value& request) { (void)request; cout << "server received some Notification" << endl; } }; int main() { try { UnixDomainSocketServer server("/tmp/unixdomainsocketexample"); SampleServer serv(server); if (serv.StartListening()) { cout << "Server started successfully" << endl; getchar(); serv.StopListening(); } else { cout << "Error starting Server" << endl; } } catch (jsonrpc::JsonRpcException& e) { cerr << e.what() << endl; } } libjson-rpc-cpp-0.7.0/src/examples/xbmc_remote.json000066400000000000000000000005761275256467400223560ustar00rootroot00000000000000[ { "name": "Input.Left", "returns": "string" }, { "name": "Input.Right", "returns": "string" }, { "name": "Input.Up", "returns": "string" }, { "name": "Input.Down", "returns": "string" }, { "name": "Input.Back", "returns": "string" }, { "name": "Input.Select", "returns": "string" } ] libjson-rpc-cpp-0.7.0/src/examples/xbmcremote.cpp000066400000000000000000000052301275256467400220200ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file xbmcremote.cpp * @date 03.06.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "gen/xbmcremote.h" #include #include #include #include #include #ifndef WIN32 #include #else #include #endif #include #include #include using namespace jsonrpc; using namespace std; //Taken from: http://stackoverflow.com/questions/2984307/c-key-pressed-in-linux-console int kbhit() { int ch; #ifndef WIN32 struct termios neu, alt; int fd = fileno(stdin); tcgetattr(fd, &alt); neu = alt; neu.c_lflag &= ~(ICANON|ECHO); tcsetattr(fd, TCSANOW, &neu); ch = getchar(); tcsetattr(fd, TCSANOW, &alt); #else while (!_kbhit()) { usleep(100000); } ch = _getch(); #endif return ch; } 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; return -1; } else { cout << "XBMC Remote control" << endl; cout << "\ta -> left" << endl; cout << "\td -> right" << endl; cout << "\tw -> up" << endl; cout << "\td -> down" << endl; cout << "\tEsc -> back" << endl; cout << "\tEnter -> select" << endl; cout << "\tx -> exit application" << endl; try { HttpClient httpclient(argv[1]); XbmcRemoteClient stub(httpclient); bool run = true; while (run) { int key = kbhit(); switch(key) { case 97: stub.Input_Left(); break; case 115: stub.Input_Down(); break; case 100: stub.Input_Right(); break; case 119: stub.Input_Up(); break; case 10: case 13: stub.Input_Select(); break; case 127: case 27: stub.Input_Back(); break; case 120: run = false; break; } } } catch(JsonRpcException& e) { cerr << e.what() << endl; } } return 0; } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/000077500000000000000000000000001275256467400175125ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/src/jsonrpccpp/CMakeLists.txt000066400000000000000000000215661275256467400222640ustar00rootroot00000000000000# setup common headers and sources file(GLOB jsonrpc_header *.h) file(GLOB jsonrpc_header_common common/*.h) 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/iprocedureinvokationhandler.h server/iclientconnectionhandler.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 ) 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(server_connector_source "") set(server_connector_header "") set(server_connector_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_libs ${CURL_LIBRARIES}) include_directories(${CURL_INCLUDE_DIRS}) 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_libs ${CMAKE_THREAD_LIBS_INIT} ${MHD_LIBRARIES}) 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() if (UNIX_DOMAIN_SOCKET_CLIENT) list(APPEND client_connector_header "client/connectors/unixdomainsocketclient.h") list(APPEND client_connector_source "client/connectors/unixdomainsocketclient.cpp") endif() # setup sources for tcp socket connectors if (TCP_SOCKET_SERVER) list(APPEND server_connector_header "server/connectors/tcpsocketserver.h") list(APPEND server_connector_source "server/connectors/tcpsocketserver.cpp") if (WIN32) 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) list(APPEND server_connector_header "server/connectors/linuxtcpsocketserver.h") list(APPEND server_connector_source "server/connectors/linuxtcpsocketserver.cpp") endif() list(APPEND server_connector_libs ${CMAKE_THREAD_LIBS_INIT}) endif() if (TCP_SOCKET_CLIENT) list(APPEND client_connector_header "client/connectors/tcpsocketclient.h") list(APPEND client_connector_source "client/connectors/tcpsocketclient.cpp") if (WIN32) 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) list(APPEND client_connector_header "client/connectors/linuxtcpsocketclient.h") list(APPEND client_connector_source "client/connectors/linuxtcpsocketclient.cpp") endif() list(APPEND client_connector_libs ${CMAKE_THREAD_LIBS_INIT}) endif() # configure a header file to pass some of the CMake settings to the source code # TODO: move it to custom build step? file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/gen/jsonrpccpp/common") configure_file("${PROJECT_SOURCE_DIR}/src/jsonrpccpp/version.h.in" "${CMAKE_BINARY_DIR}/gen/jsonrpccpp/version.h") configure_file("${PROJECT_SOURCE_DIR}/src/jsonrpccpp/common/jsonparser.h.in" "${CMAKE_BINARY_DIR}/gen/jsonrpccpp/common/jsonparser.h") install(FILES "${CMAKE_BINARY_DIR}/gen/jsonrpccpp/version.h" DESTINATION include/jsonrpccpp) install(FILES "${PROJECT_BINARY_DIR}/gen/jsonrpccpp/common/jsonparser.h" DESTINATION include/jsonrpccpp/common) # include required directories include_directories(..) include_directories(${JSONCPP_INCLUDE_DIRS}) 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_LIBRARIES}) set_target_properties(jsonrpccommon PROPERTIES OUTPUT_NAME jsonrpccpp-common) endif() # setup static common library if (BUILD_STATIC_LIBS OR MSVC) add_library(jsonrpccommonStatic STATIC ${jsonrpc_source_common} ${jsonrpc_header} ${jsonrpc_helper_source_common}) target_link_libraries(jsonrpccommonStatic ${JSONCPP_LIBRARIES}) set_target_properties(jsonrpccommonStatic PROPERTIES OUTPUT_NAME jsonrpccpp-common) if (NOT BUILD_SHARED_LIBS) add_library(jsonrpccommon ALIAS jsonrpccommonStatic) endif() endif() # setup shared client library if (BUILD_SHARED_LIBS) add_library(jsonrpcclient SHARED ${jsonrpc_source_client} ${jsonrpc_header} ${jsonrpc_header_client} ${client_connector_source}) add_dependencies(jsonrpcclient jsonrpccommon) target_link_libraries(jsonrpcclient jsonrpccommon ${client_connector_libs}) set_target_properties(jsonrpcclient PROPERTIES OUTPUT_NAME jsonrpccpp-client) endif() # setup static client library if (BUILD_STATIC_LIBS OR MSVC) add_library(jsonrpcclientStatic STATIC ${jsonrpc_source_client} ${jsonrpc_header} ${jsonrpc_header_client} ${client_connector_source}) target_link_libraries(jsonrpcclientStatic jsonrpccommonStatic ${client_connector_libs}) set_target_properties(jsonrpcclientStatic PROPERTIES OUTPUT_NAME jsonrpccpp-client) if (NOT BUILD_SHARED_LIBS) add_library(jsonrpcclient ALIAS jsonrpcclientStatic) endif() endif() # setup shared server library if (BUILD_SHARED_LIBS) add_library(jsonrpcserver SHARED ${jsonrpc_source_server} ${jsonrpc_header} ${jsonrpc_header_server} ${server_connector_source}) add_dependencies(jsonrpcserver jsonrpccommon) target_link_libraries(jsonrpcserver jsonrpccommon ${server_connector_libs}) set_target_properties(jsonrpcserver PROPERTIES OUTPUT_NAME jsonrpccpp-server) endif() # setup static server library if (BUILD_STATIC_LIBS OR MSVC) add_library(jsonrpcserverStatic STATIC ${jsonrpc_source_server} ${jsonrpc_header} ${jsonrpc_header_server} ${server_connector_source}) target_link_libraries(jsonrpcserverStatic jsonrpccommonStatic ${server_connector_libs}) set_target_properties(jsonrpcserverStatic PROPERTIES OUTPUT_NAME jsonrpccpp-server) if (NOT BUILD_SHARED_LIBS) add_library(jsonrpcserver ALIAS jsonrpcserverStatic) endif() endif() set(ALL_LIBS) if (BUILD_SHARED_LIBS OR NOT BUILD_STATIC_LIBS) list(APPEND ALL_LIBS jsonrpccommon jsonrpcclient jsonrpcserver) endif() if (BUILD_STATIC_LIBS OR MSVC) list(APPEND ALL_LIBS jsonrpccommonStatic jsonrpcclientStatic jsonrpcserverStatic) endif() # setup version set(VERSION_STRING ${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_VERSION}) set_target_properties( ${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) if (WIN32) 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} LIBRARY DESTINATION lib${LIB_SUFFIX}/${CMAKE_LIBRARY_PATH} ARCHIVE DESTINATION lib${LIB_SUFFIX}/${CMAKE_LIBRARY_PATH} RUNTIME DESTINATION bin ) #set pkg-config get_filename_component(FULL_PATH_INSTALL_PREFIX ${CMAKE_INSTALL_PREFIX} ABSOLUTE) set(FULL_PATH_INCLUDEDIR "${FULL_PATH_INSTALL_PREFIX}/include") set(FULL_PATH_LIBDIR "${FULL_PATH_INSTALL_PREFIX}/lib/${CMAKE_LIBRARY_PATH}") CONFIGURE_FILE(${PROJECT_SOURCE_DIR}/cmake/libjsonrpccpp-client.pc.cmake ${CMAKE_BINARY_DIR}/libjsonrpccpp-client.pc) CONFIGURE_FILE(${PROJECT_SOURCE_DIR}/cmake/libjsonrpccpp-server.pc.cmake ${CMAKE_BINARY_DIR}/libjsonrpccpp-server.pc) 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 "lib${LIB_SUFFIX}/${CMAKE_LIBRARY_PATH}/pkgconfig") libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client.h000066400000000000000000000005401275256467400211400ustar00rootroot00000000000000/** * @file json-rpc.h * @date 02.08.2011 * @author Peter Spiess-Knafl * @brief json-rpc.h * * This file is meant to include all necessary .h files of this framework. */ #ifndef JSONRPCCPP_CLIENT_H_ #define JSONRPCCPP_CLIENT_H_ #include #include #endif /* JSONRPCCPP_CLIENT_H_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/000077500000000000000000000000001275256467400207705ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/batchcall.cpp000066400000000000000000000025011275256467400234070ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file batchcall.cpp * @date 15.10.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "batchcall.h" #include "rpcprotocolclient.h" using namespace jsonrpc; using namespace std; BatchCall::BatchCall() : id(1) { } 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; call[RpcProtocolClient::KEY_PARAMETER] = params; if(!isNotification) { call[RpcProtocolClient::KEY_ID] = this->id++; } result.append(call); if (isNotification) return -1; return call[RpcProtocolClient::KEY_ID].asInt(); } string BatchCall::toString (bool fast) const { string result; if (fast) { Json::FastWriter writer; result = writer.write(this->result); } else { Json::StyledWriter writer; result = writer.write(this->result); } return result; } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/batchcall.h000066400000000000000000000021401275256467400230530ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file batchcall.h * @date 15.10.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_BATCHCALL_H #define JSONRPC_CPP_BATCHCALL_H #include 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; private: Json::Value result; int id; }; } #endif // JSONRPC_CPP_BATCHCALL_H libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/batchresponse.cpp000066400000000000000000000033671275256467400243450ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file batchresponse.cpp * @date 10/9/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "batchresponse.h" #include using namespace jsonrpc; using namespace std; BatchResponse::BatchResponse() { } void BatchResponse::addResponse(Json::Value &id, Json::Value response, bool isError) { if (isError) { errorResponses.push_back(id); } responses[id] = response; } Json::Value BatchResponse::getResult(Json::Value& id) { Json::Value result; getResult(id, result); return result; } Json::Value BatchResponse::getResult(int id) { Json::Value result; Json::Value i = id; getResult(i, result); return result; } void BatchResponse::getResult(Json::Value& id, Json::Value &result) { if (getErrorCode(id) == 0) result = responses[id]; else result = Json::nullValue; } int BatchResponse::getErrorCode(Json::Value& id) { 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()) { return responses[id]["message"].asString(); } return ""; } string BatchResponse::getErrorMessage(int id) { Json::Value i = id; return getErrorMessage(i); } bool BatchResponse::hasErrors() { return !errorResponses.empty(); } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/batchresponse.h000066400000000000000000000043361275256467400240070ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file batchresponse.h * @date 10/9/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_BATCHRESPONSE_H #define JSONRPC_BATCHRESPONSE_H #include #include namespace jsonrpc { /** * @brief The BatchResponse class provides a simple interface for handling batch responses. */ 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(Json::Value& id); Json::Value getResult(int id); void getResult(Json::Value& id, Json::Value &result); /** * @brief getErrorCode method checks if for a given id, an error occurred in the batch request. * @param id */ int getErrorCode(Json::Value& 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); std::string getErrorMessage(int id); bool hasErrors(); private: std::map responses; std::vector errorResponses; }; } // namespace jsonrpc #endif // JSONRPC_BATCHRESPONSE_H libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/client.cpp000066400000000000000000000053351275256467400227600ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file client.cpp * @date 03.01.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "client.h" #include "rpcprotocolclient.h" using namespace jsonrpc; Client::Client(IClientConnector &connector, clientVersion_t version) : connector(connector) { this->protocol = new RpcProtocolClient(version); } Client::~Client() { delete this->protocol; } void Client::CallMethod(const std::string &name, const Json::Value ¶meter, Json::Value& result) throw(JsonRpcException) { std::string request, response; protocol->BuildRequest(name, parameter, request, false); connector.SendRPCMessage(request, response); protocol->HandleResponse(response, result); } void Client::CallProcedures(const BatchCall &calls, BatchResponse &result) throw(JsonRpcException) { std::string request, response; request = calls.toString(); connector.SendRPCMessage(request, response); Json::Reader reader; Json::Value tmpresult; if (!reader.parse(response, tmpresult) || !tmpresult.isArray()) { throw JsonRpcException(Errors::ERROR_CLIENT_INVALID_RESPONSE, "Array expected."); } 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); result.addResponse(id, singleResult, false); } catch (JsonRpcException& ex) { Json::Value id = -1; if(tmpresult[i].isMember("id")) id = tmpresult[i]["id"]; result.addResponse(id, tmpresult[i]["error"], true); } } else throw JsonRpcException(Errors::ERROR_CLIENT_INVALID_RESPONSE, "Object in Array expected."); } } BatchResponse Client::CallProcedures(const BatchCall &calls) throw(JsonRpcException) { BatchResponse result; this->CallProcedures(calls, result); return result; } Json::Value Client::CallMethod(const std::string& name, const Json::Value& parameter) throw(JsonRpcException) { Json::Value result; this->CallMethod(name, parameter, result); return result; } void Client::CallNotification(const std::string& name, const Json::Value& parameter) throw(JsonRpcException) { std::string request, response; protocol->BuildRequest(name, parameter, request, true); connector.SendRPCMessage(request, response); } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/client.h000066400000000000000000000032171275256467400224220ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file client.h * @date 03.01.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_CLIENT_H_ #define JSONRPC_CPP_CLIENT_H_ #include "iclientconnector.h" #include "batchcall.h" #include "batchresponse.h" #include #include #include namespace jsonrpc { class RpcProtocolClient; typedef enum {JSONRPC_CLIENT_V1, JSONRPC_CLIENT_V2} clientVersion_t; class Client { public: Client(IClientConnector &connector, clientVersion_t version = JSONRPC_CLIENT_V2); virtual ~Client(); void CallMethod (const std::string &name, const Json::Value ¶meter, Json::Value& result) throw (JsonRpcException); Json::Value CallMethod (const std::string &name, const Json::Value ¶meter) throw (JsonRpcException); void CallProcedures (const BatchCall &calls, BatchResponse &response) throw (JsonRpcException); BatchResponse CallProcedures (const BatchCall &calls) throw (JsonRpcException); void CallNotification (const std::string& name, const Json::Value& parameter) throw (JsonRpcException); private: IClientConnector &connector; RpcProtocolClient *protocol; }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_CLIENT_H_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/connectors/000077500000000000000000000000001275256467400231455ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/connectors/httpclient.cpp000066400000000000000000000067641275256467400260440ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file httpclient.cpp * @date 02.01.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "httpclient.h" #include #include #include #include #include using namespace jsonrpc; class curl_initializer { public: curl_initializer() {curl_global_init(CURL_GLOBAL_ALL);} ~curl_initializer() {curl_global_cleanup();} }; // See here: http://curl.haxx.se/libcurl/c/curl_global_init.html static curl_initializer _curl_init = curl_initializer(); /** * taken from http://stackoverflow.com/questions/2329571/c-libcurl-get-output-into-a-string */ struct string { char *ptr; size_t len; }; 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); s->ptr[new_len] = '\0'; s->len = new_len; return size * nmemb; } void init_string(struct string *s) { s->len = 0; s->ptr = (char*) malloc(s->len + 1); s->ptr[0] = '\0'; } HttpClient::HttpClient(const std::string& url) throw(JsonRpcException) : url(url) { this->timeout = 10000; curl = curl_easy_init(); } HttpClient::~HttpClient() { curl_easy_cleanup(curl); } void HttpClient::SendRPCMessage(const std::string& message, std::string& result) throw (JsonRpcException) { curl_easy_setopt(curl, CURLOPT_URL, this->url.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc); CURLcode res; struct string s; init_string(&s); 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()); } headers = curl_slist_append(headers, "Content-Type: application/json"); headers = curl_slist_append(headers, "charsets: utf-8"); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, message.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, timeout); res = curl_easy_perform(curl); result = s.ptr; free(s.ptr); curl_slist_free_all(headers); if (res != CURLE_OK) { std::stringstream str; str << "libcurl error: " << res; if (res == 7) str << " -> Could not connect to " << this->url; else if(res == 28) str << " -> Operation timed out"; throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, str.str()); } long http_code = 0; curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &http_code); if (http_code != 200) { throw JsonRpcException(Errors::ERROR_RPC_INTERNAL_ERROR, result); } } 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::RemoveHeader(const std::string& attr) { this->headers.erase(attr); } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/connectors/httpclient.h000066400000000000000000000026231275256467400254770ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file httpclient.h * @date 02.01.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_HTTPCLIENT_H_ #define JSONRPC_CPP_HTTPCLIENT_H_ #include "../iclientconnector.h" #include #include #include namespace jsonrpc { class HttpClient : public IClientConnector { public: HttpClient(const std::string& url) throw (JsonRpcException); virtual ~HttpClient(); virtual void SendRPCMessage(const std::string& message, std::string& result) throw (JsonRpcException); 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); private: std::map headers; std::string url; /** * @brief timeout for http request in milliseconds */ long timeout; CURL* curl; }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_HTTPCLIENT_H_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/connectors/linuxtcpsocketclient.cpp000066400000000000000000000126511275256467400301340ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file linuxtcpsocketclient.cpp * @date 17.07.2015 * @author Alexandre Poirot * @license See attached LICENSE.txt ************************************************************************/ #include "linuxtcpsocketclient.h" #include #include #include #include #include #include #include #include #include #include #include #define BUFFER_SIZE 64 #ifndef DELIMITER_CHAR #define DELIMITER_CHAR char(0x0A) #endif //DELIMITER_CHAR using namespace jsonrpc; using namespace std; LinuxTcpSocketClient::LinuxTcpSocketClient(const std::string& hostToConnect, const unsigned int &port) : TcpSocketClientPrivate(), hostToConnect(hostToConnect), port(port) { } LinuxTcpSocketClient::~LinuxTcpSocketClient() { } void LinuxTcpSocketClient::SendRPCMessage(const std::string& message, std::string& result) throw (JsonRpcException) { int socket_fd = this->Connect(); char buffer[BUFFER_SIZE]; bool fullyWritten = false; string toSend = message; do { ssize_t byteWritten = send(socket_fd, toSend.c_str(), toSend.size(), 0); if(byteWritten == -1) { string message = "send() failed"; int err = errno; switch(err) { case EACCES: case EWOULDBLOCK: case EBADF: case ECONNRESET: case EDESTADDRREQ: case EFAULT: case EINTR: case EINVAL: case EISCONN: case EMSGSIZE: case ENOBUFS: case ENOMEM: case ENOTCONN: case ENOTSOCK: case EOPNOTSUPP: case EPIPE: message = strerror(err); break; } close(socket_fd); throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, message); } else if(static_cast(byteWritten) < toSend.size()) { int len = toSend.size() - byteWritten; toSend = toSend.substr(byteWritten + sizeof(char), len); } else fullyWritten = true; } while(!fullyWritten); do { int nbytes = recv(socket_fd, buffer, BUFFER_SIZE, 0); if(nbytes == -1) { string message = "recv() failed"; int err = errno; switch(err) { case EWOULDBLOCK: case EBADF: case ECONNRESET: case EFAULT: case EINTR: case EINVAL: case ENOMEM: case ENOTCONN: case ENOTSOCK: message = strerror(err); break; } close(socket_fd); throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, message); } else { string tmp; tmp.append(buffer, nbytes); result.append(buffer,nbytes); } } while(result.find(DELIMITER_CHAR) == string::npos); close(socket_fd); } int LinuxTcpSocketClient::Connect() throw (JsonRpcException) { if(this->IsIpv4Address(this->hostToConnect)) { return this->Connect(this->hostToConnect, this->port); } else //We were given a hostname { struct addrinfo *result = NULL; struct addrinfo hints; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; char port[6]; snprintf(port, 6, "%d", this->port); int retval = getaddrinfo(this->hostToConnect.c_str(), port, &hints, &result); if(retval != 0) 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) { 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)); foundValidIp = true; } catch(const JsonRpcException& e) { foundValidIp = false; socket_fd = -1; } catch(void* p) { foundValidIp = false; socket_fd = -1; } } } if(!foundValidIp) throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Hostname resolved but connection was refused on the given port."); return socket_fd; } } int LinuxTcpSocketClient::Connect(const string& ip, const int& port) throw (JsonRpcException) { sockaddr_in address; int socket_fd; socket_fd = socket(AF_INET, SOCK_STREAM, 0); if (socket_fd < 0) { string message = "socket() failed"; int err = errno; switch(err) { case EACCES: case EAFNOSUPPORT: case EINVAL: case EMFILE: case ENOBUFS: case ENOMEM: case EPROTONOSUPPORT: message = strerror(err); break; } throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, message); } memset(&address, 0, sizeof(sockaddr_in)); address.sin_family = AF_INET; inet_aton(ip.c_str(), &(address.sin_addr)); address.sin_port = htons(port); if(connect(socket_fd, (struct sockaddr *) &address, sizeof(sockaddr_in)) != 0) { string message = "connect() failed"; int err = errno; switch(err) { case EACCES: case EPERM: case EADDRINUSE: case EAFNOSUPPORT: case EAGAIN: case EALREADY: case EBADF: case ECONNREFUSED: case EFAULT: case EINPROGRESS: case EINTR: case EISCONN: case ENETUNREACH: case ENOTSOCK: case ETIMEDOUT: message = strerror(err); break; } throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, message); } return socket_fd; } bool LinuxTcpSocketClient::IsIpv4Address(const std::string& ip) { struct in_addr addr; return (inet_aton(ip.c_str(), &addr) != 0); } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/connectors/linuxtcpsocketclient.h000066400000000000000000000066411275256467400276030ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file linuxtcpsocketclient.h * @date 17.07.2015 * @author Alexandre Poirot * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_LINUXTCPSOCKETCLIENT_H_ #define JSONRPC_CPP_LINUXTCPSOCKETCLIENT_H_ #include #include #include "tcpsocketclientprivate.h" namespace jsonrpc { /** * This class is the Linux/UNIX implementation of TCPSocketClient. * It uses the POSIX socket API to performs its job. */ class LinuxTcpSocketClient : public TcpSocketClientPrivate { 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) throw (JsonRpcException); private: 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() throw (JsonRpcException); /** * @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) throw (JsonRpcException); /** * @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_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/connectors/tcpsocketclient.cpp000066400000000000000000000023011275256467400270430ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file tcpsocketclient.cpp * @date 17.07.2015 * @author Alexandre Poirot * @license See attached LICENSE.txt ************************************************************************/ #include "tcpsocketclient.h" #ifdef __WIN32__ #include "windowstcpsocketclient.h" #elif __unix__ #include "linuxtcpsocketclient.h" #endif using namespace jsonrpc; using namespace std; TcpSocketClient::TcpSocketClient(const std::string& ipToConnect, const unsigned int &port) { #ifdef __WIN32__ this->realSocket = new WindowsTcpSocketClient(ipToConnect, port); #elif __unix__ this->realSocket = new LinuxTcpSocketClient(ipToConnect, port); #else this->realSocket = NULL; #endif } TcpSocketClient::~TcpSocketClient() { if(this->realSocket != NULL) { delete this->realSocket; this->realSocket = NULL; } } void TcpSocketClient::SendRPCMessage(const std::string& message, std::string& result) throw (JsonRpcException) { if(this->realSocket != NULL) { this->realSocket->SendRPCMessage(message, result); } } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/connectors/tcpsocketclient.h000066400000000000000000000054121275256467400265160ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file unixdomainsocketclient.h * @date 11.05.2015 * @author Alexandre Poirot * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_TCPSOCKETCLIENT_H_ #define JSONRPC_CPP_TCPSOCKETCLIENT_H_ #include "../iclientconnector.h" #include #include #include "tcpsocketclientprivate.h" 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) throw (JsonRpcException); private: TcpSocketClientPrivate *realSocket; /*!< A pointer to the real implementation of this class depending of running OS*/ }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_TCPSOCKETCLIENT_H_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/connectors/tcpsocketclientprivate.h000066400000000000000000000015521275256467400301120ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file tcpsocketclientprivate.h * @date 17.07.2015 * @author Alexandre Poirot * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_TCPSOCKETCLIENTPRIVATE_H_ #define JSONRPC_CPP_TCPSOCKETCLIENTPRIVATE_H_ #include "../iclientconnector.h" #include namespace jsonrpc { /** * This class is an interface to the real implementation of TcpSocketClient. Kind of a strategy design pattern. */ class TcpSocketClientPrivate : public IClientConnector { }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_TCPSOCKETCLIENTPRIVATE_H_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/connectors/unixdomainsocketclient.cpp000066400000000000000000000042051275256467400304350ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file unixdomainsocketclient.cpp * @date 11.05.2015 * @author Alexandre Poirot * @license See attached LICENSE.txt ************************************************************************/ #include "unixdomainsocketclient.h" #include #include #include #include #include #include #include #include #define BUFFER_SIZE 64 #define PATH_MAX 108 #ifndef DELIMITER_CHAR #define DELIMITER_CHAR char(0x0A) #endif //DELIMITER_CHAR using namespace jsonrpc; using namespace std; UnixDomainSocketClient::UnixDomainSocketClient(const std::string& path) : path(path) { } UnixDomainSocketClient::~UnixDomainSocketClient() { } void UnixDomainSocketClient::SendRPCMessage(const std::string& message, std::string& result) throw (JsonRpcException) { sockaddr_un address; int socket_fd, nbytes; char buffer[BUFFER_SIZE]; socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); if (socket_fd < 0) { throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Could not created unix domain socket"); } memset(&address, 0, sizeof(sockaddr_un)); address.sun_family = AF_UNIX; snprintf(address.sun_path, PATH_MAX, "%s", this->path.c_str()); if(connect(socket_fd, (struct sockaddr *) &address, sizeof(sockaddr_un)) != 0) { throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "Could not connect to: " + this->path); } bool fullyWritten = false; string toSend = message; do { ssize_t byteWritten = write(socket_fd, toSend.c_str(), toSend.size()); if(static_cast(byteWritten) < toSend.size()) { int len = toSend.size() - byteWritten; toSend = toSend.substr(byteWritten + sizeof(char), len); } else fullyWritten = true; } while(!fullyWritten); do { nbytes = read(socket_fd, buffer, BUFFER_SIZE); string tmp; tmp.append(buffer, nbytes); result.append(buffer,nbytes); } while(result.find(DELIMITER_CHAR) == string::npos); close(socket_fd); } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/connectors/unixdomainsocketclient.h000066400000000000000000000016751275256467400301120ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file unixdomainsocketclient.h * @date 11.05.2015 * @author Alexandre Poirot * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_UNIXDOMAINSOCKETCLIENT_H_ #define JSONRPC_CPP_UNIXDOMAINSOCKETCLIENT_H_ #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) throw (JsonRpcException); private: std::string path; }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_HTTPCLIENT_H_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/connectors/windowstcpsocketclient.cpp000066400000000000000000000161671275256467400304750ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file windowstcpsocketclient.cpp * @date 17.07.2015 * @author Alexandre Poirot * @license See attached LICENSE.txt ************************************************************************/ #include "windowstcpsocketclient.h" #include #include #include #undef _WIN32_WINNT #define _WIN32_WINNT 0x501 #include #define BUFFER_SIZE 64 #ifndef DELIMITER_CHAR #define DELIMITER_CHAR char(0x0A) #endif //DELIMITER_CHAR using namespace jsonrpc; using namespace std; 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) { SOCKET socket_fd = this->Connect(); char buffer[BUFFER_SIZE]; bool fullyWritten = false; string toSend = message; do { int byteWritten = send(socket_fd, toSend.c_str(), toSend.size(), 0); if(byteWritten == -1) { string message = "send() failed"; int err = WSAGetLastError(); switch(err) { case WSANOTINITIALISED: case WSAENETDOWN: case WSAEACCES: case WSAEINTR: case WSAEINPROGRESS: case WSAEFAULT: case WSAENETRESET: case WSAENOBUFS: case WSAENOTCONN: case WSAENOTSOCK: case WSAEOPNOTSUPP: case WSAESHUTDOWN: case WSAEWOULDBLOCK: case WSAEMSGSIZE: case WSAEHOSTUNREACH: case WSAEINVAL: case WSAECONNABORTED: case WSAECONNRESET: case WSAETIMEDOUT: message = GetErrorMessage(err); break; } closesocket(socket_fd); throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, message); } else if(static_cast(byteWritten) < toSend.size()) { int len = toSend.size() - byteWritten; toSend = toSend.substr(byteWritten + sizeof(char), len); } else fullyWritten = true; } while(!fullyWritten); do { int nbytes = recv(socket_fd, buffer, BUFFER_SIZE, 0); if(nbytes == -1) { string message = "recv() failed"; int err = WSAGetLastError(); switch(err) { case WSANOTINITIALISED: case WSAENETDOWN: case WSAEFAULT: case WSAENOTCONN: case WSAEINTR: case WSAEINPROGRESS: case WSAENETRESET: case WSAENOTSOCK: case WSAEOPNOTSUPP: case WSAESHUTDOWN: case WSAEWOULDBLOCK: case WSAEMSGSIZE: case WSAEINVAL: case WSAECONNABORTED: case WSAETIMEDOUT: case WSAECONNRESET: message = GetErrorMessage(err); break; } closesocket(socket_fd); throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, message); } else { string tmp; tmp.append(buffer, nbytes); result.append(buffer,nbytes); } } while(result.find(DELIMITER_CHAR) == string::npos); closesocket(socket_fd); } 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), (LPTSTR)&lpMsgBuf, 0, NULL); string message(static_cast(lpMsgBuf)); LocalFree(lpMsgBuf); return message; } SOCKET WindowsTcpSocketClient::Connect() throw (JsonRpcException) { if(this->IsIpv4Address(this->hostToConnect)) { return this->Connect(this->hostToConnect, this->port); } else //We were given a hostname { struct addrinfo *result = NULL; struct addrinfo hints; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; char port[6]; port = itoa(this->port, port, 10); DWORD retval = getaddrinfo(this->hostToConnect.c_str(), port, &hints, &result); if(retval != 0) 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) { 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)); foundValidIp = true; } catch(const JsonRpcException& e) { foundValidIp = false; socket_fd = INVALID_SOCKET; } catch(void* p) { foundValidIp = false; socket_fd = INVALID_SOCKET; } } } if(!foundValidIp) 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) { SOCKADDR_IN address; SOCKET socket_fd = socket(AF_INET, SOCK_STREAM, 0); if (socket_fd == INVALID_SOCKET) { string message = "socket() failed"; int err = WSAGetLastError(); switch(err) { case WSANOTINITIALISED: case WSAENETDOWN: case WSAEAFNOSUPPORT: case WSAEINPROGRESS: case WSAEMFILE: case WSAEINVAL: case WSAEINVALIDPROVIDER: case WSAEINVALIDPROCTABLE: case WSAENOBUFS: case WSAEPROTONOSUPPORT: case WSAEPROTOTYPE: case WSAEPROVIDERFAILEDINIT: case WSAESOCKTNOSUPPORT: message = GetErrorMessage(err); break; } throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, message); } memset(&address, 0, sizeof(SOCKADDR_IN)); 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) { string message = "connect() failed"; int err = WSAGetLastError(); switch(err) { case WSANOTINITIALISED: case WSAENETDOWN: case WSAEADDRINUSE: case WSAEINTR: case WSAEINPROGRESS: case WSAEALREADY: case WSAEADDRNOTAVAIL: case WSAEAFNOSUPPORT: case WSAECONNREFUSED: case WSAEFAULT: case WSAEINVAL: case WSAEISCONN: case WSAENETUNREACH: case WSAEHOSTUNREACH: case WSAENOBUFS: case WSAENOTSOCK: case WSAETIMEDOUT: case WSAEWOULDBLOCK: case WSAEACCES: message = GetErrorMessage(err); break; } throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, message); } return socket_fd; } 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/ ). struct ClientSocketInitializer { ClientSocketInitializer() { WSADATA init; if(WSAStartup(MAKEWORD(2, 2), &init) != 0) { throw JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "An issue occured while WSAStartup executed."); } } ~ClientSocketInitializer() { if(WSACleanup() != 0) { cerr << "An issue occured while WSAClean executed." << endl; } } }; struct ClientSocketInitializer clientGlobalInitializer; libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/connectors/windowstcpsocketclient.h000066400000000000000000000072661275256467400301420ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file windowstcpsocketclient.h * @date 17.07.2015 * @author Alexandre Poirot * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_WINDOWSTCPSOCKETCLIENT_H_ #define JSONRPC_CPP_WINDOWSTCPSOCKETCLIENT_H_ #include #include #include "tcpsocketclientprivate.h" #include namespace jsonrpc { /** * This class is the windows implementation of TCPSocketClient. * It uses the Winsock2 API to performs its job. */ class WindowsTcpSocketClient : public TcpSocketClientPrivate { 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) throw (JsonRpcException); private: 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() throw (JsonRpcException); /** * @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) throw (JsonRpcException); /** * @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_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/iclientconnector.h000066400000000000000000000015141275256467400245040ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file abstractclientconnector.h * @date 02.01.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_CLIENTCONNECTOR_H_ #define JSONRPC_CPP_CLIENTCONNECTOR_H_ #include #include namespace jsonrpc { class IClientConnector { public: virtual ~IClientConnector(){} virtual void SendRPCMessage(const std::string& message, std::string& result) throw(JsonRpcException) = 0; }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_CLIENTCONNECTOR_H_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/rpcprotocolclient.cpp000066400000000000000000000120621275256467400252420ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file responsehandler.cpp * @date 13.03.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "rpcprotocolclient.h" #include using namespace jsonrpc; const std::string RpcProtocolClient::KEY_PROTOCOL_VERSION = "jsonrpc"; const std::string RpcProtocolClient::KEY_PROCEDURE_NAME = "method"; const std::string RpcProtocolClient::KEY_ID = "id"; const std::string RpcProtocolClient::KEY_PARAMETER = "params"; const std::string RpcProtocolClient::KEY_AUTH = "auth"; const std::string RpcProtocolClient::KEY_RESULT = "result"; const std::string RpcProtocolClient::KEY_ERROR = "error"; 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) : version(version) { } void RpcProtocolClient::BuildRequest(const std::string &method, const Json::Value ¶meter, std::string &result, bool isNotification) { Json::Value request; Json::FastWriter writer; this->BuildRequest(1, method,parameter,request, isNotification); result = writer.write(request); } void RpcProtocolClient::HandleResponse(const std::string &response, Json::Value& result) throw(JsonRpcException) { Json::Reader reader; Json::Value value; if(reader.parse(response, value)) { this->HandleResponse(value, result); } else { throw JsonRpcException(Errors::ERROR_RPC_JSON_PARSE_ERROR, " " + response); } } Json::Value RpcProtocolClient::HandleResponse(const Json::Value &value, Json::Value &result) throw(JsonRpcException) { if(this->ValidateResponse(value)) { if (this->HasError(value)) { this->throwErrorException(value); } else { result = value[KEY_RESULT]; } } else { 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) { if (this->version == JSONRPC_CLIENT_V2) result[KEY_PROTOCOL_VERSION] = "2.0"; result[KEY_PROCEDURE_NAME] = method; if (parameter != Json::nullValue) result[KEY_PARAMETER] = parameter; if (!isNotification) result[KEY_ID] = id; else if (this->version == JSONRPC_CLIENT_V1) result[KEY_ID] = Json::nullValue; } 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_DATA)) { 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()); } } else { throw JsonRpcException(response[KEY_ERROR][KEY_ERROR_CODE].asInt()); } } bool RpcProtocolClient::ValidateResponse(const Json::Value& response) { if (!response.isObject() || !response.isMember(KEY_ID)) return false; if (this->version == JSONRPC_CLIENT_V1) { if (!response.isMember(KEY_RESULT) || !response.isMember(KEY_ERROR)) return false; 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())) return false; } else if (this->version == JSONRPC_CLIENT_V2) { 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())) return false; } return true; } bool RpcProtocolClient::HasError(const Json::Value& response) { if (this->version == JSONRPC_CLIENT_V1 && !response[KEY_ERROR].isNull()) return true; else if (this->version == JSONRPC_CLIENT_V2 && response.isMember(KEY_ERROR)) return true; return false; } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/client/rpcprotocolclient.h000066400000000000000000000072161275256467400247140ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file responsehandler.h * @date 13.03.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef RESPONSEHANDLER_H #define RESPONSEHANDLER_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); /** * @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); /** * @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) throw (JsonRpcException); /** * @brief HandleResponse * @param response * @param result * @return response id */ Json::Value HandleResponse(const Json::Value &response, Json::Value &result) throw (JsonRpcException); 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; 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); }; } #endif // RESPONSEHANDLER_H libjson-rpc-cpp-0.7.0/src/jsonrpccpp/common/000077500000000000000000000000001275256467400210025ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/src/jsonrpccpp/common/errors.cpp000066400000000000000000000060621275256467400230260ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file errors.cpp * @date 31.12.2012 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "errors.h" #include "exception.h" using namespace jsonrpc; std::map Errors::possibleErrors; Errors::_init Errors::_initializer; const int Errors::ERROR_RPC_JSON_PARSE_ERROR = -32700; const int Errors::ERROR_RPC_METHOD_NOT_FOUND = -32601; const int Errors::ERROR_RPC_INVALID_REQUEST = -32600; const int Errors::ERROR_RPC_INVALID_PARAMS = -32602; const int Errors::ERROR_RPC_INTERNAL_ERROR = -32603; const int Errors::ERROR_SERVER_PROCEDURE_IS_METHOD = -32604; const int Errors::ERROR_SERVER_PROCEDURE_IS_NOTIFICATION = -32605; const int Errors::ERROR_SERVER_PROCEDURE_POINTER_IS_NULL = -32606; const int Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_NOT_FOUND = -32000; const int Errors::ERROR_SERVER_CONNECTOR = -32002; const int Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX = -32007; const int Errors::ERROR_CLIENT_CONNECTOR = -32003; const int Errors::ERROR_CLIENT_INVALID_RESPONSE = -32001; Errors::_init::_init() { //Official Errors possibleErrors[ERROR_RPC_INVALID_REQUEST] = "INVALID_JSON_REQUEST: The JSON sent is not a valid JSON-RPC Request object"; possibleErrors[ERROR_RPC_METHOD_NOT_FOUND] = "METHOD_NOT_FOUND: The method being requested is not available on this server"; 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_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_SPECIFICATION_SYNTAX] = "Procedure specification mallformed"; possibleErrors[ERROR_CLIENT_INVALID_RESPONSE] = "The response is invalid"; possibleErrors[ERROR_CLIENT_CONNECTOR] = "Client connector error"; possibleErrors[ERROR_SERVER_CONNECTOR] = "Server connector error"; } std::string Errors::GetErrorMessage(int errorCode) { if(possibleErrors.find(errorCode) == possibleErrors.end()) { return ""; } return possibleErrors[errorCode]; } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/common/errors.h000066400000000000000000000037661275256467400225030ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file errors.h * @date 31.12.2012 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_ERRORS_H_ #define JSONRPC_CPP_ERRORS_H_ #include #include #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 */ #endif /* JSONRPC_CPP_ERRORS_H_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/common/exception.cpp000066400000000000000000000040071275256467400235050ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file exception.cpp * @date 31.12.2012 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "exception.h" using namespace jsonrpc; 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)) { if (this->message != "") this->message = this->message + ": "; this->message = this->message + message; this->setWhatMessage(); } JsonRpcException::JsonRpcException(int code, const std::string &message, const Json::Value &data) : code(code), message(Errors::GetErrorMessage(code)), data(data) { if (this->message != "") this->message = this->message + ": "; this->message = this->message + message; this->setWhatMessage(); } JsonRpcException::JsonRpcException(const std::string& message) : code(0), message(message) { this->setWhatMessage(); } JsonRpcException::~JsonRpcException() throw () { } int JsonRpcException::GetCode() const { return code; } 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(); } void JsonRpcException::setWhatMessage() { if (this->code != 0) { std::stringstream ss; ss << "Exception " << this->code << " : " << this->message; if (data != Json::nullValue) ss << ", data: " << data.toStyledString(); this->whatString = ss.str(); } else { this->whatString = this->message; } } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/common/exception.h000066400000000000000000000025301275256467400231510ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file exception.h * @date 31.12.2012 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_EXCEPTION_H_ #define JSONRPC_CPP_EXCEPTION_H_ #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 */ #endif /* JSONRPC_CPP_EXCEPTION_H_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/common/jsonparser.h.in000066400000000000000000000010251275256467400237440ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file jsonparser.h * @date 1/21/2015 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_JSONPARSER_H_ #define JSONRPC_CPP_JSONPARSER_H_ #include <@JSONCPP_INCLUDE_PREFIX@/json.h> #endif // JSONRPC_CPP_JSONPARSER_H_ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/common/procedure.cpp000066400000000000000000000123171275256467400235020ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file procedure.cpp * @date 31.12.2012 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "procedure.h" #include "exception.h" #include "errors.h" #include #include using namespace std; using namespace jsonrpc; Procedure::Procedure() : procedureName(""), procedureType(RPC_METHOD), returntype(JSON_BOOLEAN), paramDeclaration(PARAMS_BY_NAME) { } 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*); jsontype_t type; while(paramname != NULL) { type = (jsontype_t)va_arg(parameters, int); this->AddParameter(paramname, type); paramname = va_arg(parameters, const char*); } va_end(parameters); this->procedureName = name; this->returntype = returntype; this->procedureType = RPC_METHOD; this->paramDeclaration = paramType; } Procedure::Procedure(const string &name, parameterDeclaration_t paramType, ...) { va_list parameters; va_start(parameters, paramType); const char* paramname = va_arg(parameters, const char*); jsontype_t type; while(paramname != NULL) { type = (jsontype_t)va_arg(parameters, int); this->AddParameter(paramname, type); paramname = va_arg(parameters, const char*); } va_end(parameters); this->procedureName = name; this->procedureType = RPC_NOTIFICATION; this->paramDeclaration = paramType; this->returntype = JSON_BOOLEAN; } bool Procedure::ValdiateParameters (const Json::Value& parameters) const { if (this->parametersName.empty()) { return true; } if(parameters.isArray() && this->paramDeclaration == PARAMS_BY_POSITION) { return this->ValidatePositionalParameters(parameters); } 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; } 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; } 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::SetReturnType (jsontype_t type) { this->returntype = type; } void Procedure::SetParameterDeclarationType (parameterDeclaration_t type) { this->paramDeclaration = type; } void Procedure::AddParameter (const string& name, jsontype_t type) { this->parametersName[name] = type; this->parametersPosition.push_back(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) { if (!parameters.isMember(it->first)) { ok = false; } else { ok = this->ValidateSingleParameter(it->second, parameters[it->first]); } } return ok; } bool Procedure::ValidatePositionalParameters (const Json::Value ¶meters) const { bool ok = true; if(parameters.size() != this->parametersPosition.size()) { return false; } for(unsigned int i=0; ok && i < this->parametersPosition.size(); i++) { ok = this->ValidateSingleParameter(this->parametersPosition.at(i), parameters[i]); } return ok; } bool Procedure::ValidateSingleParameter (jsontype_t expectedType, const Json::Value &value) const { bool ok = true; switch (expectedType) { case JSON_STRING: if (!value.isString()) ok = false; break; case JSON_BOOLEAN: if (!value.isBool()) ok = false; break; case JSON_INTEGER: if (!value.isIntegral()) ok = false; break; case JSON_REAL: if (!value.isDouble()) ok = false; break; case JSON_OBJECT: if (!value.isObject()) ok = false; break; case JSON_ARRAY: if (!value.isArray()) ok = false; break; } return ok; } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/common/procedure.h000066400000000000000000000115521275256467400231470ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file procedure.h * @date 31.12.2012 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_PROCEDURE_H_ #define JSONRPC_CPP_PROCEDURE_H_ #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 */ #endif /* JSONRPC_CPP_PROCEDURE_H_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/common/specification.h000066400000000000000000000025461275256467400240020ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file specification.h * @date 30.04.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #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" 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 } ; } #endif // JSONRPC_CPP_SPECIFICATION_H libjson-rpc-cpp-0.7.0/src/jsonrpccpp/common/specificationparser.cpp000066400000000000000000000140421275256467400255440ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file specificationparser.cpp * @date 12.03.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "specificationparser.h" #include #include using namespace std; using namespace jsonrpc; vector SpecificationParser::GetProceduresFromFile (const string &filename) throw(JsonRpcException) { string content; GetFileContent(filename, content); return GetProceduresFromString(content); } vector SpecificationParser::GetProceduresFromString(const string &content) throw(JsonRpcException) { Json::Reader reader; Json::Value val; if(!reader.parse(content,val)) { 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"); } vector result; map procnames; for (unsigned int i = 0; i < val.size(); i++) { Procedure proc; GetProcedure(val[i], proc); if (procnames.find(proc.GetProcedureName()) != procnames.end()) { throw JsonRpcException(Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX, "Procedurename not uniqe: " + proc.GetProcedureName()); } procnames[proc.GetProcedureName()] = proc; result.push_back(proc); } return result; } void SpecificationParser::GetProcedure (Json::Value &signature, Procedure &result) { if (signature.isObject() && GetProcedureName(signature) != "") { result.SetProcedureName(GetProcedureName(signature)); if (signature.isMember(KEY_SPEC_RETURN_TYPE)) { result.SetProcedureType(RPC_METHOD); result.SetReturnType(toJsonType(signature[KEY_SPEC_RETURN_TYPE])); } else { 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].isArray()) { result.SetParameterDeclarationType(PARAMS_BY_POSITION); GetPositionalParameters(signature, result); } else if (signature[KEY_SPEC_PROCEDURE_PARAMETERS].isObject()) { result.SetParameterDeclarationType(PARAMS_BY_NAME); GetNamedParameters(signature, result); } } else { 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()); } } 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())); } else { throw JsonRpcException(Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_NOT_FOUND, filename); } } jsontype_t SpecificationParser::toJsonType (Json::Value &val) { jsontype_t result; switch(val.type()) { case Json::uintValue: case Json::intValue: result = JSON_INTEGER; break; case Json::realValue: result = JSON_REAL; break; case Json::stringValue: result = JSON_STRING; break; case Json::booleanValue: result = JSON_BOOLEAN; break; case Json::arrayValue: result = JSON_ARRAY; break; case Json::objectValue: result = JSON_OBJECT; break; default: throw JsonRpcException(Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX,"Unknown parameter type: " + val.toStyledString()); } return 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" << (i+1); 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(); for (unsigned int i=0; i < parameters.size(); ++i) { result.AddParameter(parameters.at(i), toJsonType(val[KEY_SPEC_PROCEDURE_PARAMETERS][parameters.at(i)])); } } string SpecificationParser::GetProcedureName(Json::Value &signature) { if(signature[KEY_SPEC_PROCEDURE_NAME].isString()) return signature[KEY_SPEC_PROCEDURE_NAME].asString(); if (signature[KEY_SPEC_PROCEDURE_METHOD].isString()) return signature[KEY_SPEC_PROCEDURE_METHOD].asString(); if (signature[KEY_SPEC_PROCEDURE_NOTIFICATION].isString()) return signature[KEY_SPEC_PROCEDURE_NOTIFICATION].asString(); return ""; } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/common/specificationparser.h000066400000000000000000000031221275256467400252060ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file specificationparser.h * @date 12.03.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_SPECIFICATIONPARSER_H #define JSONRPC_CPP_SPECIFICATIONPARSER_H #include "procedure.h" #include "exception.h" namespace jsonrpc { class SpecificationParser { public: static std::vector GetProceduresFromFile(const std::string& filename) throw (JsonRpcException); static std::vector GetProceduresFromString(const std::string& spec) throw (JsonRpcException); static void GetFileContent (const std::string& filename, std::string& target); 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); }; } #endif // JSONRPC_CPP_SPECIFICATIONPARSER_H libjson-rpc-cpp-0.7.0/src/jsonrpccpp/common/specificationwriter.cpp000066400000000000000000000053331275256467400255670ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file specificationwriter.cpp * @date 30.04.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "specificationwriter.h" #include "jsonparser.h" #include #include #include using namespace std; using namespace jsonrpc; Json::Value SpecificationWriter::toJsonValue (const vector &procedures) { Json::Value result; Json::Value row; for(unsigned int i=0; i < procedures.size(); i++) { procedureToJsonValue(procedures.at(i), row); result[i] = row; row.clear(); } return result; } std::string SpecificationWriter::toString (const vector &procedures) { Json::StyledWriter wr; return wr.write(toJsonValue(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()) return false; file << toString(procedures); file.close(); return true; } Json::Value SpecificationWriter::toJsonLiteral (jsontype_t type) { Json::Value literal; switch(type) { case JSON_BOOLEAN: literal = true; break; case JSON_STRING: literal = "somestring"; break; case JSON_REAL: literal = 1.0; break; case JSON_ARRAY: literal = Json::arrayValue; break; case JSON_OBJECT: literal["objectkey"] = "objectvalue"; break; case JSON_INTEGER: literal = 1; break; } return literal; } 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) { if(procedure.GetParameterDeclarationType() == PARAMS_BY_NAME) { target[KEY_SPEC_PROCEDURE_PARAMETERS][it->first] = toJsonLiteral(it->second); } else { target[KEY_SPEC_PROCEDURE_PARAMETERS].append(toJsonLiteral(it->second)); } } } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/common/specificationwriter.h000066400000000000000000000021751275256467400252350ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file specificationwriter.h * @date 30.04.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_SPECIFICATIONWRITER_H #define JSONRPC_CPP_SPECIFICATIONWRITER_H #include "procedure.h" #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); private: static Json::Value toJsonLiteral (jsontype_t type); static void procedureToJsonValue (const Procedure& procedure, Json::Value& target); }; } #endif // JSONRPC_CPP_SPECIFICATIONWRITER_H libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server.h000066400000000000000000000005501275256467400211710ustar00rootroot00000000000000/** * @file json-rpc.h * @date 02.08.2011 * @author Peter Spiess-Knafl * @brief json-rpc.h * * This file is meant to include all necessary .h files of this framework. */ #ifndef JSONRPCCPP_SERVER_H_ #define JSONRPCCPP_SERVER_H_ #include #include #endif /* JSONRPCCPP_SERVER_H_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/000077500000000000000000000000001275256467400210205ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/abstractprotocolhandler.cpp000066400000000000000000000060411275256467400264500ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file abstractprotocolhandler.cpp * @date 10/23/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "abstractprotocolhandler.h" #include #include #include using namespace jsonrpc; using namespace std; AbstractProtocolHandler::AbstractProtocolHandler(IProcedureInvokationHandler &handler) : handler(handler) { } AbstractProtocolHandler::~AbstractProtocolHandler() { } void AbstractProtocolHandler::AddProcedure(const Procedure &procedure) { this->procedures[procedure.GetProcedureName()] = procedure; } void AbstractProtocolHandler::HandleRequest(const std::string &request, std::string &retValue) { Json::Reader reader; Json::Value req; Json::Value resp; Json::FastWriter w; 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); } if (resp != Json::nullValue) retValue = w.write(resp); } 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) { handler.HandleMethodCall(method, request[KEY_REQUEST_PARAMETERS], result); this->WrapResult(request, response, result); } else { handler.HandleNotificationCall(method, request[KEY_REQUEST_PARAMETERS]); response = Json::nullValue; } } int AbstractProtocolHandler::ValidateRequest(const Json::Value &request) { int error = 0; Procedure proc; if (!this->ValidateRequestFields(request)) { error = Errors::ERROR_RPC_INVALID_REQUEST; } else { 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) { error = Errors::ERROR_SERVER_PROCEDURE_IS_NOTIFICATION; } 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; } } else { error = Errors::ERROR_RPC_METHOD_NOT_FOUND; } } return error; } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/abstractprotocolhandler.h000066400000000000000000000040301275256467400261110ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file abstractprotocolhandler.h * @date 10/23/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_ABSTRACTPROTOCOLHANDLER_H #define JSONRPC_CPP_ABSTRACTPROTOCOLHANDLER_H #include "iprocedureinvokationhandler.h" #include "iclientconnectionhandler.h" #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" namespace jsonrpc { class AbstractProtocolHandler : public IProtocolHandler { public: AbstractProtocolHandler(IProcedureInvokationHandler &handler); virtual ~AbstractProtocolHandler(); void HandleRequest(const std::string& request, std::string& retValue); virtual void AddProcedure(const Procedure& procedure); 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; protected: IProcedureInvokationHandler &handler; std::map procedures; void ProcessRequest(const Json::Value &request, Json::Value &retValue); int ValidateRequest(const Json::Value &val); }; } // namespace jsonrpc #endif // JSONRPC_CPP_ABSTRACTPROTOCOLHANDLER_H libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/abstractserver.h000066400000000000000000000073371275256467400242350ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file abstractserver.h * @date 30.12.2012 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_ABSTRACTSERVER_H_ #define JSONRPC_CPP_ABSTRACTSERVER_H_ #include #include #include #include #include "abstractserverconnector.h" #include "iprocedureinvokationhandler.h" #include "iclientconnectionhandler.h" #include "requesthandlerfactory.h" 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); 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; } bool StartListening() { return connection.StartListening(); } 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 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; } 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; 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_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/abstractserverconnector.cpp000066400000000000000000000023021275256467400264660ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file abstractserverconnector.cpp * @date 31.12.2012 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "abstractserverconnector.h" #include #include using namespace std; using namespace jsonrpc; AbstractServerConnector::AbstractServerConnector() { this->handler = NULL; } AbstractServerConnector::~AbstractServerConnector() { } bool AbstractServerConnector::OnRequest(const std::string& request, void* addInfo) { string response; if (this->handler != NULL) { this->handler->HandleRequest(request, response); this->SendResponse(response, addInfo); return true; } else { return false; } } void AbstractServerConnector::SetHandler(IClientConnectionHandler* handler) { this->handler = handler; } IClientConnectionHandler *AbstractServerConnector::GetHandler() { return this->handler; } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/abstractserverconnector.h000066400000000000000000000047141275256467400261440ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file abstractserverconnector.h * @date 31.12.2012 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_SERVERCONNECTOR_H_ #define JSONRPC_CPP_SERVERCONNECTOR_H_ #include #include "iclientconnectionhandler.h" 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; /** * This method should send a response to the client in any way that is appropriate for the derived connector class. * @param response - the response that should be send to the client * @param addInfo - additional Info, that the Connector might need for responding. * @return returns true on success, false otherwise */ bool virtual SendResponse(const std::string& response, void* addInfo = NULL) = 0; /** * This method must be called, when a request is recognised. It will do everything else for you (including sending the response). * @param request - the request that has been recognised. * @param addInfo - additional Info, that the Connector might need for responding. */ bool OnRequest(const std::string& request, void* addInfo = NULL); void SetHandler(IClientConnectionHandler* handler); IClientConnectionHandler* GetHandler(); private: IClientConnectionHandler *handler; }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_ERVERCONNECTOR_H_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/connectors/000077500000000000000000000000001275256467400231755ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/connectors/httpserver.cpp000066400000000000000000000135741275256467400261210ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file httpserver.cpp * @date 31.12.2012 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "httpserver.h" #include #include #include #include using namespace jsonrpc; using namespace std; #define BUFFERSIZE 65536 struct mhd_coninfo { struct MHD_PostProcessor *postprocessor; MHD_Connection* connection; stringstream request; HttpServer* server; 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) { } IClientConnectionHandler *HttpServer::GetHandler(const std::string &url) { if (AbstractServerConnector::GetHandler() != NULL) return AbstractServerConnector::GetHandler(); map::iterator it = this->urlhandler.find(url); if (it != this->urlhandler.end()) return it->second; return NULL; } bool HttpServer::StartListening() { if(!this->running) { if (this->path_sslcert != "" && this->path_sslkey != "") { try { SpecificationParser::GetFileContent(this->path_sslcert, this->sslcert); SpecificationParser::GetFileContent(this->path_sslkey, this->sslkey); this->daemon = MHD_start_daemon(MHD_USE_SSL | MHD_USE_SELECT_INTERNALLY, 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_USE_SELECT_INTERNALLY, this->port, NULL, NULL, HttpServer::callback, this, MHD_OPTION_THREAD_POOL_SIZE, this->threads, MHD_OPTION_END); } if (this->daemon != NULL) this->running = true; } return this->running; } bool HttpServer::StopListening() { if(this->running) { MHD_stop_daemon(this->daemon); this->running = false; } return true; } 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); 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); 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); 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, "DAV", "1"); 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) { this->urlhandler[url] = handler; this->SetHandler(NULL); } int 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; client_connection->connection = connection; client_connection->server = static_cast(cls); *con_cls = client_connection; return MHD_YES; } struct mhd_coninfo* client_connection = static_cast(*con_cls); if (string("POST") == method) { if (*upload_data_size != 0) { client_connection->request.write(upload_data, *upload_data_size); *upload_data_size = 0; return MHD_YES; } else { string response; 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 conneciton handler found", client_connection); } else { client_connection->code = MHD_HTTP_OK; handler->HandleRequest(client_connection->request.str(), response); client_connection->server->SendResponse(response, client_connection); } } } else if (string("OPTIONS") == method) { client_connection->code = MHD_HTTP_OK; 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); } delete client_connection; *con_cls = NULL; return MHD_YES; } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/connectors/httpserver.h000066400000000000000000000055561275256467400255670ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file httpserver.h * @date 31.12.2012 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_HTTPSERVERCONNECTOR_H_ #define JSONRPC_CPP_HTTPSERVERCONNECTOR_H_ #include #include #include #if defined(_WIN32) && !defined(__CYGWIN__) #include #if defined(_MSC_FULL_VER) && !defined (_SSIZE_T_DEFINED) #define _SSIZE_T_DEFINED typedef intptr_t ssize_t; #endif // !_SSIZE_T_DEFINED */ #else #include #include #include #endif #include #include #include "../abstractserverconnector.h" 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. */ HttpServer(int port, const std::string& sslcert = "", const std::string& sslkey = "", int threads = 50); virtual bool StartListening(); virtual bool StopListening(); bool virtual SendResponse(const std::string& response, void* addInfo = NULL); bool virtual SendOptionsResponse(void* addInfo); void SetUrlHandler(const std::string &url, IClientConnectionHandler *handler); private: int port; int threads; bool running; std::string path_sslcert; std::string path_sslkey; std::string sslcert; std::string sslkey; struct MHD_Daemon *daemon; std::map urlhandler; static int 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); }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_HTTPSERVERCONNECTOR_H_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/connectors/linuxtcpsocketserver.cpp000066400000000000000000000140561275256467400302150ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file linuxtcpsocketserver.cpp * @date 17.07.2015 * @author Alexandre Poirot * @license See attached LICENSE.txt ************************************************************************/ #include "linuxtcpsocketserver.h" #include #include #include #include #include #include #include #include #include #include #include using namespace jsonrpc; using namespace std; #define BUFFER_SIZE 64 #ifndef DELIMITER_CHAR #define DELIMITER_CHAR char(0x0A) #endif //DELIMITER_CHAR LinuxTcpSocketServer::LinuxTcpSocketServer(const std::string& ipToBind, const unsigned int &port) : AbstractServerConnector(), running(false), ipToBind(ipToBind), port(port) { } bool LinuxTcpSocketServer::StartListening() { if(!this->running) { //Create and bind socket here. //Then launch the listenning loop. this->socket_fd = socket(AF_INET, SOCK_STREAM, 0); if(this->socket_fd < 0) { return false; } fcntl(this->socket_fd, F_SETFL, FNDELAY); int reuseaddr = 1; 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)); this->address.sin_family = AF_INET; 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) { return false; } if(listen(this->socket_fd, 5) != 0) { return false; } //Launch listening loop there this->running = true; int ret = pthread_create(&(this->listenning_thread), NULL, LinuxTcpSocketServer::LaunchLoop, this); if(ret != 0) { pthread_detach(this->listenning_thread); shutdown(this->socket_fd, 2); close(this->socket_fd); } this->running = static_cast(ret==0); return this->running; } else { return false; } } bool LinuxTcpSocketServer::StopListening() { if(this->running) { this->running = false; pthread_join(this->listenning_thread, NULL); shutdown(this->socket_fd, 2); close(this->socket_fd); return !(this->running); } else { return false; } } bool LinuxTcpSocketServer::SendResponse(const string& response, void* addInfo) { bool result = false; int connection_fd = reinterpret_cast(addInfo); string temp = response; if(temp.find(DELIMITER_CHAR) == string::npos) { temp.append(1, DELIMITER_CHAR); } if(DELIMITER_CHAR != '\n') { char eot = DELIMITER_CHAR; string toSend = temp.substr(0, toSend.find_last_of('\n')); toSend += eot; result = this->WriteToSocket(connection_fd, toSend); } else { result = this->WriteToSocket(connection_fd, temp); } CleanClose(connection_fd); return result; } void* LinuxTcpSocketServer::LaunchLoop(void *p_data) { pthread_detach(pthread_self()); LinuxTcpSocketServer *instance = reinterpret_cast(p_data);; instance->ListenLoop(); return NULL; } void LinuxTcpSocketServer::ListenLoop() { int connection_fd = 0; struct sockaddr_in connection_address; memset(&connection_address, 0, sizeof(struct sockaddr_in)); socklen_t address_length = sizeof(connection_address); while(this->running) { if((connection_fd = accept(this->socket_fd, reinterpret_cast(&(connection_address)), &address_length)) > 0) { pthread_t client_thread; struct GenerateResponseParameters *params = new struct GenerateResponseParameters(); params->instance = this; params->connection_fd = connection_fd; int ret = pthread_create(&client_thread, NULL, LinuxTcpSocketServer::GenerateResponse, params); if(ret != 0) { pthread_detach(client_thread); delete params; params = NULL; CleanClose(connection_fd); } } else { usleep(2500); } } } void* LinuxTcpSocketServer::GenerateResponse(void *p_data) { pthread_detach(pthread_self()); struct GenerateResponseParameters* params = reinterpret_cast(p_data); LinuxTcpSocketServer *instance = params->instance; int connection_fd = params->connection_fd; delete params; params = NULL; int nbytes; char buffer[BUFFER_SIZE]; string request; do { //The client sends its json formatted request and a delimiter request. nbytes = recv(connection_fd, buffer, BUFFER_SIZE, 0); if(nbytes == -1) { instance->CleanClose(connection_fd); return NULL; } else { request.append(buffer,nbytes); } } while(request.find(DELIMITER_CHAR) == string::npos); instance->OnRequest(request, reinterpret_cast(connection_fd)); return NULL; } bool LinuxTcpSocketServer::WriteToSocket(const int& fd, const string& toWrite) { bool fullyWritten = false; bool errorOccured = false; string toSend = toWrite; do { ssize_t byteWritten = send(fd, toSend.c_str(), toSend.size(), 0); if(byteWritten < 0) { errorOccured = true; CleanClose(fd); } else if(static_cast(byteWritten) < toSend.size()) { int len = toSend.size() - byteWritten; toSend = toSend.substr(byteWritten + sizeof(char), len); } else fullyWritten = true; } while(!fullyWritten && !errorOccured); return fullyWritten && !errorOccured; } bool LinuxTcpSocketServer::WaitClientClose(const int& fd, const int &timeout) { bool ret = false; int i = 0; while((recv(fd, NULL, 0, 0) != 0) && i < timeout) { usleep(1); ++i; ret = true; } return ret; } int LinuxTcpSocketServer::CloseByReset(const int& fd) { struct linger so_linger; so_linger.l_onoff = 1; so_linger.l_linger = 0; int ret = setsockopt(fd, SOL_SOCKET, SO_LINGER, &so_linger, sizeof(so_linger)); if(ret != 0) return ret; return close(fd); } int LinuxTcpSocketServer::CleanClose(const int& fd) { if(WaitClientClose(fd)) { return close(fd); } else { return CloseByReset(fd); } } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/connectors/linuxtcpsocketserver.h000066400000000000000000000171731275256467400276650ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file linuxtcpsocketserver.h * @date 17.07.2015 * @author Alexandre Poirot * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_LINUXTCPSOCKETSERVERCONNECTOR_H_ #define JSONRPC_CPP_LINUXTCPSOCKETSERVERCONNECTOR_H_ #include #include #include #include #include #include #include #include #include #include "../abstractserverconnector.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 AbstractServerConnector { 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); /** * @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 successfuly 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); private: 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*/ int socket_fd; /*!< The file descriptior of the listening socket*/ struct sockaddr_in address; /*!< The listening socket*/ pthread_t listenning_thread; /*!< The identifier of the listen loop thread*/ /** * @brief The static method that is used as listening thread entry point * @param p_data The parameters for the thread entry point method */ static void* LaunchLoop(void *p_data); /** * @brief The method that launches the listenning loop */ void ListenLoop(); struct GenerateResponseParameters { LinuxTcpSocketServer *instance; int 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 p_data The parameters for the thread entry point method */ static void* GenerateResponse(void *p_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 int& 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 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_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/connectors/tcpsocketserver.cpp000066400000000000000000000030531275256467400271300ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file tcpsocketserver.cpp * @date 17.07.2015 * @author Alexandre Poirot * @license See attached LICENSE.txt ************************************************************************/ #include "tcpsocketserver.h" #ifdef __WIN32__ #include "windowstcpsocketserver.h" #elif __unix__ #include "linuxtcpsocketserver.h" #endif #include using namespace jsonrpc; using namespace std; TcpSocketServer::TcpSocketServer(const std::string& ipToBind, const unsigned int &port) : AbstractServerConnector() { #ifdef __WIN32__ this->realSocket = new WindowsTcpSocketServer(ipToBind, port); #elif __unix__ this->realSocket = new LinuxTcpSocketServer(ipToBind, port); #else this->realSocket = NULL; #endif } TcpSocketServer::~TcpSocketServer() { if(this->realSocket != NULL) { delete this->realSocket; this->realSocket = NULL; } } bool TcpSocketServer::StartListening() { if(this->realSocket != NULL) { this->realSocket->SetHandler(this->GetHandler()); return this->realSocket->StartListening(); } else return false; } bool TcpSocketServer::StopListening() { if(this->realSocket != NULL) return this->realSocket->StopListening(); else return false; } bool TcpSocketServer::SendResponse(const string& response, void* addInfo) { if(this->realSocket != NULL) return this->realSocket->SendResponse(response, addInfo); else return false; } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/connectors/tcpsocketserver.h000066400000000000000000000103031275256467400265710ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file tcpsocketserver.h * @date 17.07.2015 * @author Alexandre Poirot * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_TCPSOCKETSERVERCONNECTOR_H_ #define JSONRPC_CPP_TCPSOCKETSERVERCONNECTOR_H_ #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); /** * @brief ~TcpSocketServer, the destructor of TcpSocketServer */ ~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 successfuly 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 AbstractServerConnector::SendResponse method overload. * * 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); private: AbstractServerConnector *realSocket; /*!< A pointer to the real implementation of this class depending of running OS*/ }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_TCPSOCKETSERVERCONNECTOR_H_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/connectors/unixdomainsocketserver.cpp000066400000000000000000000117661275256467400305270ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file unixdomainsocketserver.cpp * @date 07.05.2015 * @author Alexandre Poirot * @license See attached LICENSE.txt ************************************************************************/ #include "unixdomainsocketserver.h" #include #include #include #include #include #include #include #include #include using namespace jsonrpc; using namespace std; #define BUFFER_SIZE 1024 #define PATH_MAX 108 #ifndef DELIMITER_CHAR #define DELIMITER_CHAR char(0x0A) #endif UnixDomainSocketServer::UnixDomainSocketServer(const string &socket_path) : running(false), socket_path(socket_path.substr(0, PATH_MAX)) { } bool UnixDomainSocketServer::StartListening() { if(!this->running) { //Create and bind socket here. //Then launch the listenning loop. if (access(this->socket_path.c_str(), F_OK) != -1) return false; this->socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); if(this->socket_fd < 0) { return false; } unlink(this->socket_path.c_str()); fcntl(this->socket_fd, F_SETFL, FNDELAY); /* start with a clean address structure */ memset(&(this->address), 0, sizeof(struct sockaddr_un)); this->address.sun_family = AF_UNIX; snprintf(this->address.sun_path, PATH_MAX, "%s", this->socket_path.c_str()); if(bind(this->socket_fd, reinterpret_cast(&(this->address)), sizeof(struct sockaddr_un)) != 0) { return false; } if(listen(this->socket_fd, 5) != 0) { return false; } //Launch listening loop there this->running = true; int ret = pthread_create(&(this->listenning_thread), NULL, UnixDomainSocketServer::LaunchLoop, this); if(ret != 0) { pthread_detach(this->listenning_thread); } this->running = static_cast(ret==0); return this->running; } else { return false; } } bool UnixDomainSocketServer::StopListening() { if(this->running) { this->running = false; pthread_join(this->listenning_thread, NULL); close(this->socket_fd); unlink(this->socket_path.c_str()); return !(this->running); } else { return false; } } bool UnixDomainSocketServer::SendResponse(const string& response, void* addInfo) { bool result = false; int connection_fd = reinterpret_cast(addInfo); string temp = response; if(temp.find(DELIMITER_CHAR) == string::npos) { temp.append(1, DELIMITER_CHAR); } if(DELIMITER_CHAR != '\n') { char eot = DELIMITER_CHAR; string toSend = temp.substr(0, toSend.find_last_of('\n')); toSend += eot; result = this->WriteToSocket(connection_fd, toSend); } else { result = this->WriteToSocket(connection_fd, temp); } close(connection_fd); return result; } void* UnixDomainSocketServer::LaunchLoop(void *p_data) { pthread_detach(pthread_self()); UnixDomainSocketServer *instance = reinterpret_cast(p_data);; instance->ListenLoop(); return NULL; } void UnixDomainSocketServer::ListenLoop() { int connection_fd; socklen_t address_length = sizeof(this->address); while(this->running) { if((connection_fd = accept(this->socket_fd, reinterpret_cast(&(this->address)), &address_length)) > 0) { pthread_t client_thread; struct ClientConnection *params = new struct ClientConnection(); params->instance = this; params->connection_fd = connection_fd; int ret = pthread_create(&client_thread, NULL, UnixDomainSocketServer::GenerateResponse, params); if(ret != 0) { pthread_detach(client_thread); delete params; params = NULL; } } else { usleep(25000); } } } void* UnixDomainSocketServer::GenerateResponse(void *p_data) { pthread_detach(pthread_self()); struct ClientConnection* params = reinterpret_cast(p_data); UnixDomainSocketServer *instance = params->instance; int connection_fd = params->connection_fd; delete params; params = NULL; int nbytes; char buffer[BUFFER_SIZE]; string request; do { //The client sends its json formatted request and a delimiter request. nbytes = read(connection_fd, buffer, BUFFER_SIZE); request.append(buffer,nbytes); } while(request.find(DELIMITER_CHAR) == string::npos); instance->OnRequest(request, reinterpret_cast(connection_fd)); return NULL; } bool UnixDomainSocketServer::WriteToSocket(int fd, const string& toWrite) { bool fullyWritten = false; bool errorOccured = false; string toSend = toWrite; do { ssize_t byteWritten = write(fd, toSend.c_str(), toSend.size()); if(byteWritten < 0) errorOccured = true; else if(byteWritten < static_cast(toSend.size())) { int len = toSend.size() - byteWritten; toSend = toSend.substr(byteWritten + sizeof(char), len); } else fullyWritten = true; } while(!fullyWritten && !errorOccured); return fullyWritten && !errorOccured; } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/connectors/unixdomainsocketserver.h000066400000000000000000000034031275256467400301610ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file unixdomainsocketserver.h * @date 07.05.2015 * @author Alexandre Poirot * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_UNIXDOMAINSOCKETSERVERCONNECTOR_H_ #define JSONRPC_CPP_UNIXDOMAINSOCKETSERVERCONNECTOR_H_ #include #include #include #include #include #include #include #include #include "../abstractserverconnector.h" namespace jsonrpc { /** * This class provides an embedded Unix Domain Socket Server,to handle incoming Requests. */ class UnixDomainSocketServer: public AbstractServerConnector { 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); virtual bool StartListening(); virtual bool StopListening(); bool virtual SendResponse(const std::string& response, void* addInfo = NULL); private: bool running; std::string socket_path; int socket_fd; struct sockaddr_un address; pthread_t listenning_thread; static void* LaunchLoop(void *p_data); void ListenLoop(); struct ClientConnection { UnixDomainSocketServer *instance; int connection_fd; }; static void* GenerateResponse(void *p_data); bool WriteToSocket(int fd, const std::string& toSend); }; } /* namespace jsonrpc */ #endif /* JSONRPC_CPP_HTTPSERVERCONNECTOR_H_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/connectors/windowstcpsocketserver.cpp000066400000000000000000000165101275256467400305450ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file windowstcpsocketserver.cpp * @date 17.07.2015 * @author Alexandre Poirot * @license See attached LICENSE.txt ************************************************************************/ #include "windowstcpsocketserver.h" #include #include #include #include #include #include #include #include using namespace jsonrpc; using namespace std; #define BUFFER_SIZE 64 #ifndef DELIMITER_CHAR #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() { } bool WindowsTcpSocketServer::StartListening() { if(!this->running) { //Create and bind socket here. //Then launch the listenning loop. this->socket_fd = socket(AF_INET, SOCK_STREAM, 0); if(this->socket_fd < 0) { return false; } 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)); /* start with a clean address structure */ memset(&(this->address), 0, sizeof(SOCKADDR_IN)); this->address.sin_family = AF_INET; 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) { return false; } if(listen(this->socket_fd, 5) != 0) { return false; } //Launch listening loop there this->running = true; HANDLE ret = CreateThread(NULL, 0, reinterpret_cast(&(WindowsTcpSocketServer::LaunchLoop)), reinterpret_cast(this), 0, &(this->listenning_thread)); if(ret == NULL) { ExitProcess(3); } else { CloseHandle(ret); } this->running = static_cast(ret!=NULL); return this->running; } else { return false; } } bool WindowsTcpSocketServer::StopListening() { if(this->running) { this->running = false; WaitForSingleObject(OpenThread(THREAD_ALL_ACCESS, FALSE,this->listenning_thread), INFINITE); closesocket(this->socket_fd); return !(this->running); } else { return false; } } bool WindowsTcpSocketServer::SendResponse(const string& response, void* addInfo) { bool result = false; int connection_fd = reinterpret_cast(addInfo); string temp = response; if(temp.find(DELIMITER_CHAR) == string::npos) { temp.append(1, DELIMITER_CHAR); } if(DELIMITER_CHAR != '\n') { char eot = DELIMITER_CHAR; string toSend = temp.substr(0, toSend.find_last_of('\n')); toSend += eot; result = this->WriteToSocket(connection_fd, toSend); } else { result = this->WriteToSocket(connection_fd, temp); } CleanClose(connection_fd); return result; } DWORD WINAPI WindowsTcpSocketServer::LaunchLoop(LPVOID lp_data) { WindowsTcpSocketServer *instance = reinterpret_cast(lp_data);; instance->ListenLoop(); CloseHandle(GetCurrentThread()); return 0; //DO NOT USE ExitThread function here! ExitThread does not call destructors for allocated objects and therefore it would lead to a memory leak. } void WindowsTcpSocketServer::ListenLoop() { while(this->running) { SOCKET connection_fd = INVALID_SOCKET; 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) { unsigned long nonBlocking = 0; ioctlsocket(connection_fd, FIONBIO, &nonBlocking); //Set blocking DWORD client_thread; 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); if(ret == NULL) { delete params; params = NULL; CleanClose(connection_fd); } else { CloseHandle(ret); } } else { Sleep(2.5); } } } DWORD WINAPI WindowsTcpSocketServer::GenerateResponse(LPVOID lp_data) { struct GenerateResponseParameters* params = reinterpret_cast(lp_data); WindowsTcpSocketServer *instance = params->instance; int connection_fd = params->connection_fd; delete params; params = NULL; int nbytes = 0; char buffer[BUFFER_SIZE]; memset(&buffer, 0, BUFFER_SIZE); string request = ""; do { //The client sends its json formatted request and a delimiter request. nbytes = recv(connection_fd, buffer, BUFFER_SIZE, 0); if(nbytes == -1) { instance->CleanClose(connection_fd); } else { request.append(buffer,nbytes); } } while(request.find(DELIMITER_CHAR) == string::npos); instance->OnRequest(request, reinterpret_cast(connection_fd)); CloseHandle(GetCurrentThread()); return 0; //DO NOT USE ExitThread function here! ExitThread does not call destructors for allocated objects and therefore it would lead to a memory leak. } bool WindowsTcpSocketServer::WriteToSocket(const SOCKET& fd, const string& toWrite) { bool fullyWritten = false; bool errorOccured = false; string toSend = toWrite; do { ssize_t byteWritten = send(fd, toSend.c_str(), toSend.size(), 0); if(byteWritten < 0) { errorOccured = true; CleanClose(fd); } else if(byteWritten < toSend.size()) { int len = toSend.size() - byteWritten; toSend = toSend.substr(byteWritten + sizeof(char), len); } else fullyWritten = true; } while(!fullyWritten && !errorOccured); return fullyWritten && !errorOccured; } bool WindowsTcpSocketServer::WaitClientClose(const SOCKET& fd, const int &timeout) { bool ret = false; int i = 0; while((recv(fd, NULL, 0, 0) != 0) && i < timeout) { Sleep(1); ++i; ret = true; } return ret; } int WindowsTcpSocketServer::CloseByReset(const SOCKET& fd) { struct linger so_linger; 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)); if(ret != 0) return ret; return closesocket(fd); } int WindowsTcpSocketServer::CleanClose(const SOCKET& fd) { if(WaitClientClose(fd)) { return closesocket(fd); } else { return CloseByReset(fd); } } //This is inspired from SFML to manage Winsock initialization. Thanks to them! ( http://www.sfml-dev.org/ ). struct ServerSocketInitializer { ServerSocketInitializer() { WSADATA init; if(WSAStartup(MAKEWORD(2, 2), &init) != 0) { JsonRpcException(Errors::ERROR_CLIENT_CONNECTOR, "An issue occured while WSAStartup executed."); } } ~ServerSocketInitializer() { if(WSACleanup() != 0) { cerr << "An issue occured while WSAClean executed." << endl; } } }; struct ServerSocketInitializer serverGlobalInitializer; libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/connectors/windowstcpsocketserver.h000066400000000000000000000172631275256467400302200ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file windowstcpsocketserver.h * @date 17.07.2015 * @author Alexandre Poirot * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_WINDOWSTCPSOCKETSERVERCONNECTOR_H_ #define JSONRPC_CPP_WINDOWSTCPSOCKETSERVERCONNECTOR_H_ #include #include #include #include "../abstractserverconnector.h" 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: /** * @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 successfuly 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); private: 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*/ /** * @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_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/iclientconnectionhandler.h000066400000000000000000000017721275256467400262450ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file iclientconnectionhandler.h * @date 10/23/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_ICLIENTCONNECTIONHANDLER_H #define JSONRPC_CPP_ICLIENTCONNECTIONHANDLER_H #include namespace jsonrpc { class Procedure; class IClientConnectionHandler { public: virtual ~IClientConnectionHandler() {} virtual void HandleRequest(const std::string& request, std::string& retValue) = 0; }; class IProtocolHandler : public IClientConnectionHandler { public: virtual ~IProtocolHandler(){} virtual void AddProcedure(const Procedure& procedure) = 0; }; } #endif // JSONRPC_CPP_ICLIENTCONNECTIONHANDLER_H libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/iprocedureinvokationhandler.h000066400000000000000000000017011275256467400267710ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file iprocedureinvokationhandler.h * @date 23.10.2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_IPROCEDUREINVOKATIONHANDLER_H #define JSONRPC_CPP_IPROCEDUREINVOKATIONHANDLER_H namespace Json { class Value; } namespace jsonrpc { 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; }; } #endif //JSONRPC_CPP_IPROCEDUREINVOKATIONHANDLER_H libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/requesthandlerfactory.cpp000066400000000000000000000021001275256467400261330ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file requesthandlerfactory.cpp * @date 10/23/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "requesthandlerfactory.h" #include "rpcprotocolserverv1.h" #include "rpcprotocolserverv2.h" #include "rpcprotocolserver12.h" using namespace jsonrpc; IProtocolHandler *RequestHandlerFactory::createProtocolHandler(serverVersion_t type, IProcedureInvokationHandler &handler) { IProtocolHandler* result = NULL; switch (type) { case JSONRPC_SERVER_V1: result = new RpcProtocolServerV1(handler); break; case JSONRPC_SERVER_V2: result = new RpcProtocolServerV2(handler); break; case JSONRPC_SERVER_V1V2: result = new RpcProtocolServer12(handler); break; } return result; } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/requesthandlerfactory.h000066400000000000000000000016311275256467400256100ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file requesthandlerfactory.h * @date 10/23/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_REQUESTHANDLERFACTORY_H #define JSONRPC_REQUESTHANDLERFACTORY_H #include "iprocedureinvokationhandler.h" #include "iclientconnectionhandler.h" namespace jsonrpc { typedef enum {JSONRPC_SERVER_V1, JSONRPC_SERVER_V2, JSONRPC_SERVER_V1V2} serverVersion_t; class RequestHandlerFactory { public: static IProtocolHandler* createProtocolHandler(serverVersion_t type, IProcedureInvokationHandler& handler); }; } // namespace jsonrpc #endif // JSONRPC_REQUESTHANDLERFACTORY_H libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/rpcprotocolserver12.cpp000066400000000000000000000030511275256467400254630ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file rpcprotocolserver12.cpp * @date 10/25/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "rpcprotocolserver12.h" #include using namespace jsonrpc; 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) { Json::Reader reader; Json::Value req; Json::Value resp; Json::FastWriter w; 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); } if (resp != Json::nullValue) retValue = w.write(resp); } AbstractProtocolHandler &RpcProtocolServer12::GetHandler(const Json::Value &request) { if (request.isArray() || (request.isObject() && request.isMember("jsonrpc") && request["jsonrpc"].asString() == "2.0")) return rpc2; return rpc1; } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/rpcprotocolserver12.h000066400000000000000000000021541275256467400251330ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file rpcprotocolserver12.h * @date 10/25/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_RPCPROTOCOLSERVER12_H #define JSONRPC_RPCPROTOCOLSERVER12_H #include "abstractprotocolhandler.h" #include "rpcprotocolserverv1.h" #include "rpcprotocolserverv2.h" namespace jsonrpc { class RpcProtocolServer12 : public IProtocolHandler { public: RpcProtocolServer12(IProcedureInvokationHandler &handler); void AddProcedure(const Procedure& procedure); void HandleRequest(const std::string& request, std::string& retValue); private: RpcProtocolServerV1 rpc1; RpcProtocolServerV2 rpc2; AbstractProtocolHandler& GetHandler(const Json::Value& request); }; } // namespace jsonrpc #endif // JSONRPC_RPCPROTOCOLSERVER12_H libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/rpcprotocolserverv1.cpp000066400000000000000000000056761275256467400256060ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file rpcprotocolserverv1.cpp * @date 10/23/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "rpcprotocolserverv1.h" #include #include using namespace jsonrpc; RpcProtocolServerV1::RpcProtocolServerV1(IProcedureInvokationHandler &handler) : AbstractProtocolHandler(handler) { } void RpcProtocolServerV1::HandleJsonRequest(const Json::Value &req, Json::Value &response) { if (req.isObject()) { int error = this->ValidateRequest(req); if (error == 0) { try { this->ProcessRequest(req, response); } catch (const JsonRpcException & exc) { this->WrapException(req, exc, response); } } else { 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); } } bool RpcProtocolServerV1::ValidateRequestFields(const Json::Value &request) { 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())) return false; return true; } 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) { result["error"]["code"] = code; result["error"]["message"] = message; result["result"] = Json::nullValue; if(request.isObject() && request.isMember("id")) { result["id"] = request["id"]; } else { result["id"] = Json::nullValue; } } 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(); } procedure_t RpcProtocolServerV1::GetRequestType(const Json::Value &request) { if (request[KEY_REQUEST_ID] == Json::nullValue) return RPC_NOTIFICATION; return RPC_METHOD; } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/rpcprotocolserverv1.h000066400000000000000000000025321275256467400252370ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file rpcprotocolserverv1.h * @date 10/23/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_RPCPROTOCOLSERVERV1_H #define JSONRPC_CPP_RPCPROTOCOLSERVERV1_H #include #include "abstractprotocolhandler.h" 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); }; } // namespace jsonrpc #endif // JSONRPC_CPP_RPCPROTOCOLSERVERV1_H libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/rpcprotocolserverv2.cpp000066400000000000000000000101611275256467400255700ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file rpcprotocolserverv2.cpp * @date 31.12.2012 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "rpcprotocolserverv2.h" #include #include using namespace std; using namespace jsonrpc; RpcProtocolServerV2::RpcProtocolServerV2(IProcedureInvokationHandler &handler) : AbstractProtocolHandler(handler) { } void RpcProtocolServerV2::HandleJsonRequest (const Json::Value &req, Json::Value &response) { //It could be a Batch Request if (req.isArray()) { this->HandleBatchRequest(req, response); } //It could be a simple Request 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); } } void RpcProtocolServerV2::HandleSingleRequest (const Json::Value &req, Json::Value& response) { int error = this->ValidateRequest(req); if (error == 0) { try { this->ProcessRequest(req, response); } catch (const JsonRpcException & exc) { this->WrapException(req, exc, response); } } else { this->WrapError(req, error, Errors::GetErrorMessage(error),response); } } void RpcProtocolServerV2::HandleBatchRequest (const Json::Value &req, Json::Value& response) { if (req.size() == 0) 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; this->HandleSingleRequest(req[i], result); if (result != Json::nullValue) response.append(result); } } } bool RpcProtocolServerV2::ValidateRequestFields(const Json::Value &request) { if (!request.isObject()) return false; 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)) return false; 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())) return false; return true; } 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) { 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())) { result["id"] = request["id"]; } else { result["id"] = Json::nullValue; } } 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(); } procedure_t RpcProtocolServerV2::GetRequestType(const Json::Value &request) { if (request.isMember(KEY_REQUEST_ID)) return RPC_METHOD; return RPC_NOTIFICATION; } libjson-rpc-cpp-0.7.0/src/jsonrpccpp/server/rpcprotocolserverv2.h000066400000000000000000000032471275256467400252440ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file rpcprotocolserverv2.h * @date 31.12.2012 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_RPCPROTOCOLSERVERV2_H_ #define JSONRPC_CPP_RPCPROTOCOLSERVERV2_H_ #include #include #include #include #include "abstractprotocolhandler.h" #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_ */ libjson-rpc-cpp-0.7.0/src/jsonrpccpp/version.h.in000066400000000000000000000011731275256467400217570ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file version.h.in * @date 12.05.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_VERSION_H_ #define JSONRPC_CPP_VERSION_H_ #define JSONRPC_CPP_MAJOR_VERSION @MAJOR_VERSION@ #define JSONRPC_CPP_MINOR_VERSION @MINOR_VERSION@ #define JSONRPC_CPP_PATCH_VERSION @PATCH_VERSION@ #endif /* JSONRPC_CPP_VERSION_H_ */ libjson-rpc-cpp-0.7.0/src/stubgenerator/000077500000000000000000000000001275256467400202155ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/src/stubgenerator/CMakeLists.txt000066400000000000000000000051271275256467400227620ustar00rootroot00000000000000file(GLOB_RECURSE jsonrpcstub_source *.cpp) file(GLOB_RECURSE jsonrpcstub_header *.h) list(REMOVE_ITEM jsonrpcstub_source "${CMAKE_CURRENT_SOURCE_DIR}/main.cpp") include_directories(..) include_directories(${JSONCPP_INCLUDE_DIRS}) include_directories(${ARGTABLE_INCLUDE_DIRS}) set(ALL_LIBS) if (BUILD_SHARED_LIBS) add_library(libjsonrpcstub SHARED ${jsonrpcstub_source} ${jsonrpcstub_header} ${jsonrpc_helper_source_common}) target_link_libraries(libjsonrpcstub jsonrpccommon ${JSONCPP_LIBRARIES} ${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) add_library(libjsonrpcstubStatic STATIC ${jsonrpcstub_source} ${jsonrpcstub_header} ${jsonrpc_helper_source_common}) target_link_libraries(libjsonrpcstubStatic jsonrpccommonStatic ${JSONCPP_LIBRARIES} ${ARGTABLE_LIBRARIES}) set_target_properties(libjsonrpcstubStatic PROPERTIES OUTPUT_NAME jsonrpccpp-stub) if (NOT BUILD_SHARED_LIBS) add_library(libjsonrpcstub ALIAS libjsonrpcstubStatic) endif() list(APPEND ALL_LIBS libjsonrpcstubStatic) 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) target_link_libraries(jsonrpcstub jsonrpccommon libjsonrpcstub ) #Generate manpage if (NOT ${CMAKE_SYSTEM_NAME} STREQUAL "Windows") configure_file("${CMAKE_SOURCE_DIR}/doc/manpage.in" "${CMAKE_BINARY_DIR}/manpage" @ONLY) add_custom_command(OUTPUT jsonrpcstub.1.gz COMMAND gzip -c "${CMAKE_BINARY_DIR}/manpage" > ${CMAKE_BINARY_DIR}/jsonrpcstub.1.gz COMMENT "Generating man pages" VERBATIM ) add_custom_target(manpage ALL DEPENDS jsonrpcstub.1.gz) install(FILES ${CMAKE_BINARY_DIR}/jsonrpcstub.1.gz DESTINATION share/man/man1/) add_dependencies(jsonrpcstub manpage) 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 "lib/${CMAKE_LIBRARY_PATH}/pkgconfig") install(DIRECTORY ${CMAKE_SOURCE_DIR}/src/stubgenerator/ DESTINATION include/jsonrpccpp/stubgen FILES_MATCHING PATTERN "*.h") install(TARGETS ${ALL_LIBS} jsonrpcstub LIBRARY DESTINATION lib${LIB_SUFFIX}/${CMAKE_LIBRARY_PATH} ARCHIVE DESTINATION lib${LIB_SUFFIX}/${CMAKE_LIBRARY_PATH} RUNTIME DESTINATION bin ) libjson-rpc-cpp-0.7.0/src/stubgenerator/client/000077500000000000000000000000001275256467400214735ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/src/stubgenerator/client/cppclientstubgenerator.cpp000077500000000000000000000121551275256467400267740ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file CPPClientStubGenerator.cpp * @date 01.05.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "cppclientstubgenerator.h" #include "../helper/cpphelper.h" #define TEMPLATE_CPPCLIENT_SIGCLASS "class : public jsonrpc::Client" #define TEMPLATE_CPPCLIENT_SIGCONSTRUCTOR "(jsonrpc::IClientConnector &conn, jsonrpc::clientVersion_t type = jsonrpc::JSONRPC_CLIENT_V2) : jsonrpc::Client(conn, type) {}" #define TEMPLATE_CPPCLIENT_SIGMETHOD " () throw (jsonrpc::JsonRpcException)" #define TEMPLATE_NAMED_ASSIGNMENT "p[\"\"] = ;" #define TEMPLATE_POSITION_ASSIGNMENT "p.append();" #define TEMPLATE_METHODCALL "Json::Value result = this->CallMethod(\"\",p);" #define TEMPLATE_NOTIFICATIONCALL "this->CallNotification(\"\",p);" #define TEMPLATE_RETURNCHECK "if (result)" #define TEMPLATE_RETURN "return result;" using namespace std; using namespace jsonrpc; 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) : StubGenerator(stubname, procedures, filename) { } void CPPClientStubGenerator::generateStub() { vector classname = CPPHelper::splitPackages(this->stubname); CPPHelper::prolog(*this, this->stubname); this->writeLine("#include "); this->writeNewLine(); int depth = CPPHelper::namespaceOpen(*this, stubname); 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->writeNewLine(); for (unsigned int i=0; i < procedures.size(); i++) { this->generateMethod(procedures[i]); } this->decreaseIndentation(); this->decreaseIndentation(); this->writeLine("};"); this->writeNewLine(); CPPHelper::namespaceClose(*this, depth); CPPHelper::epilog(*this, this->stubname); } void CPPClientStubGenerator::generateMethod(Procedure &proc) { string procsignature = TEMPLATE_CPPCLIENT_SIGMETHOD; string returntype = CPPHelper::toCppReturntype(proc.GetReturnType()); if (proc.GetProcedureType() == RPC_NOTIFICATION) returntype = "void"; replaceAll2(procsignature, "", returntype); replaceAll2(procsignature, "", CPPHelper::normalizeString(proc.GetProcedureName())); replaceAll2(procsignature, "", CPPHelper::generateParameterDeclarationList(proc)); this->writeLine(procsignature); this->writeLine("{"); this->increaseIndentation(); this->writeLine("Json::Value p;"); generateAssignments(proc); generateProcCall(proc); this->decreaseIndentation(); this->writeLine("}"); } void CPPClientStubGenerator::generateAssignments(Procedure &proc) { string assignment; parameterNameList_t list = proc.GetParameters(); if(list.size() > 0) { for (parameterNameList_t::iterator it = list.begin(); it != list.end(); ++it) { if(proc.GetParameterDeclarationType() == PARAMS_BY_NAME) { assignment = TEMPLATE_NAMED_ASSIGNMENT; } else { assignment = TEMPLATE_POSITION_ASSIGNMENT; } replaceAll2(assignment, "", it->first); this->writeLine(assignment); } } else { this->writeLine("p = Json::nullValue;"); } } void CPPClientStubGenerator::generateProcCall(Procedure &proc) { string call; if (proc.GetProcedureType() == RPC_METHOD) { call = TEMPLATE_METHODCALL; this->writeLine(replaceAll(call, "", proc.GetProcedureName())); call = TEMPLATE_RETURNCHECK; replaceAll2(call,"", CPPHelper::isCppConversion(proc.GetReturnType())); this->writeLine(call); this->increaseIndentation(); call = TEMPLATE_RETURN; replaceAll2(call,"", CPPHelper::toCppConversion(proc.GetReturnType())); this->writeLine(call); this->decreaseIndentation(); this->writeLine("else"); this->increaseIndentation(); this->writeLine("throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());"); this->decreaseIndentation(); } else { call = TEMPLATE_NOTIFICATIONCALL; replaceAll2(call, "", proc.GetProcedureName()); this->writeLine(call); } } libjson-rpc-cpp-0.7.0/src/stubgenerator/client/cppclientstubgenerator.h000077500000000000000000000021771275256467400264440ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file clientstubgenerator.h * @date 01.05.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_CLIENTSTUBGENERATOR_H #define JSONRPC_CPP_CLIENTSTUBGENERATOR_H #include "../stubgenerator.h" #include "../codegenerator.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); virtual void generateStub(); void generateMethod(Procedure& proc); void generateAssignments(Procedure& proc); void generateProcCall(Procedure &proc); }; } #endif // JSONRPC_CPP_CLIENTSTUBGENERATOR_H libjson-rpc-cpp-0.7.0/src/stubgenerator/client/jsclientstubgenerator.cpp000066400000000000000000000133371275256467400266260ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file jsclientstubgenerator.cpp * @date 10/22/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "jsclientstubgenerator.h" #include using namespace jsonrpc; using namespace std; #define TEMPLATE_JS_PROLOG "function (url) {\n\ this.url = url;\n\ var id = 1;\n\ \n\ function doJsonRpcRequest(method, params, methodCall, callback_success, callback_error) {\n\ var request = {};\n\ if (methodCall)\n\ request.id = id++;\n\ request.jsonrpc = \"2.0\";\n\ request.method = method;\n\ if (params !== null) {\n\ request.params = params;\n\ }\n\ JSON.stringify(request);\n\ \n\ $.ajax({\n\ type: \"POST\",\n\ url: url,\n\ data: JSON.stringify(request),\n\ success: function (response) {\n\ if (methodCall) {\n\ if (response.hasOwnProperty(\"result\") && response.hasOwnProperty(\"id\")) {\n\ callback_success(response.id, response.result);\n\ } else if (response.hasOwnProperty(\"error\")) {\n\ if (callback_error != null)\n\ callback_error(response.error.code,response.error.message);\n\ } else {\n\ if (callback_error != null)\n\ callback_error(-32001, \"Invalid Server response: \" + response);\n\ }\n\ }\n\ },\n\ error: function () {\n\ if (methodCall)\n\ callback_error(-32002, \"AJAX Error\");\n\ },\n\ dataType: \"json\"\n\ });\n\ return id-1;\n\ }\n\ this.doRPC = function(method, params, methodCall, callback_success, callback_error) {\n\ return doJsonRpcRequest(method, params, methodCall, callback_success, callback_error);\n\ }\n\ }\n" #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, callbackError);" #define TEMPLATE_JS_CALL_NOTIFICATION "this.doRPC(\"\", params, false, callbackSuccess, callbackError);" 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) : StubGenerator(stubname, procedures, filename) { } string JSClientStubGenerator::class2Filename(const string &classname) { string result = classname; std::transform(result.begin(), result.end(), result.begin(), ::tolower); return result + ".js"; } void JSClientStubGenerator::generateStub() { this->writeLine("/**"); this->writeLine(" * This file is generated by jsonrpcstub, DO NOT CHANGE IT MANUALLY!"); this->writeLine(" */"); this->write(replaceAll(TEMPLATE_JS_PROLOG, "", stubname)); this->writeNewLine(); for (unsigned int i=0; i < procedures.size(); i++) { this->generateMethod(procedures[i]); } } void JSClientStubGenerator::generateMethod(Procedure &proc) { string method = TEMPLATE_JS_METHOD; replaceAll2(method, "", stubname); replaceAll2(method, "", noramlizeJsLiteral(proc.GetProcedureName())); stringstream param_string; stringstream params_assignment; parameterNameList_t list = proc.GetParameters(); for (parameterNameList_t::iterator it = list.begin(); it != list.end();) { param_string << it->first; if (proc.GetParameterDeclarationType() == PARAMS_BY_NAME) params_assignment << it->first << " : " << it->first; else params_assignment << it->first; if (++it != list.end()) { params_assignment << ", "; } param_string << ", "; } replaceAll2(method, "", param_string.str()); this->writeLine(method); this->increaseIndentation(); string params; if (proc.GetParameters().size() > 0) { if (proc.GetParameterDeclarationType() == PARAMS_BY_NAME) params = TEMPLATE_JS_PARAM_NAMED; else params = TEMPLATE_JS_PARAM_POSITIONAL; replaceAll2(params, "", params_assignment.str()); this->writeLine(params); } else { this->writeLine(TEMPLATE_JS_PARAM_EMPTY); } if (proc.GetProcedureType() == RPC_METHOD) method = TEMPLATE_JS_CALL_METHOD; else method = TEMPLATE_JS_CALL_NOTIFICATION; replaceAll2(method, "", proc.GetProcedureName()); this->writeLine(method); this->decreaseIndentation(); this->writeLine("};"); } 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] == '_')) { result[i] = '_'; } } return result; } libjson-rpc-cpp-0.7.0/src/stubgenerator/client/jsclientstubgenerator.h000066400000000000000000000023051275256467400262640ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file jsclientstubgenerator.h * @date 10/22/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_JSCLIENTSTUBGENERATOR_H #define JSONRPC_CPP_JSCLIENTSTUBGENERATOR_H #include "../stubgenerator.h" 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); static std::string class2Filename(const std::string &classname); virtual void generateStub(); private: virtual void generateMethod(Procedure &proc); static std::string noramlizeJsLiteral(const std::string &literal); }; } // namespace jsonrpc #endif // JSONRPC_JSCLIENTSTUBGENERATOR_H libjson-rpc-cpp-0.7.0/src/stubgenerator/codegenerator.cpp000066400000000000000000000031721275256467400235450ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file codegenerator.cpp * @date 3/21/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "codegenerator.h" using namespace jsonrpc; using namespace std; 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() { this->output->flush(); if (this->file.is_open()) { this->file.close(); } } void CodeGenerator::write(const ::string &line) { if (this->atBeginning) { this->atBeginning = false; for(int i=0; i < this->indentation; i++) *this->output << this->indentSymbol; } *this->output << line; } void CodeGenerator::writeLine(const ::string &line) { this->write(line); this->writeNewLine(); } void CodeGenerator::writeNewLine() { *this->output << endl; this->atBeginning = true; } void CodeGenerator::increaseIndentation() { this->indentation++; } void CodeGenerator::decreaseIndentation() { this->indentation--; } void CodeGenerator::setIndentSymbol(const ::string &symbol) { this->indentSymbol = symbol; } libjson-rpc-cpp-0.7.0/src/stubgenerator/codegenerator.h000066400000000000000000000023531275256467400232120ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file codegenerator.h * @date 3/21/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_CODEGENERATOR_H #define JSONRPC_CPP_CODEGENERATOR_H #include #include #include #include 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 setIndentSymbol(const std::string &symbol); private: std::ostream *output; std::ofstream file; std::string indentSymbol; int indentation; bool atBeginning; }; } #endif // JSONRPC_CPP_CODEGENERATOR_H libjson-rpc-cpp-0.7.0/src/stubgenerator/helper/000077500000000000000000000000001275256467400214745ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/src/stubgenerator/helper/cpphelper.cpp000077500000000000000000000146301275256467400241710ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file cpphelper.cpp * @date 29.09.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "cpphelper.h" #include "../stubgenerator.h" #include #include using namespace std; using namespace jsonrpc; #define TEMPLATE_CPPSERVER_GUARD1 "#ifndef JSONRPC_CPP_STUB__H_" #define TEMPLATE_CPPSERVER_GUARD2 "#define JSONRPC_CPP_STUB__H_" #define TEMPLATE_EPILOG "#endif //JSONRPC_CPP_STUB__H_" string CPPHelper::toCppType (jsontype_t type, bool isConst, bool isReference) { string result; switch(type) { case JSON_BOOLEAN: result = "bool"; break; case JSON_INTEGER: result = "int"; break; case JSON_REAL: result = "double"; break; case JSON_STRING: result = "std::string"; break; default: result = "Json::Value"; break; } if(isConst) { result = "const " + result; } if(isReference) { result = result + "&"; } return result; } string CPPHelper::toCppConversion (jsontype_t type) { string result; switch(type) { case JSON_BOOLEAN: result = ".asBool()"; break; case JSON_INTEGER: result = ".asInt()"; break; case JSON_REAL: result = ".asDouble()"; break; case JSON_STRING: result = ".asString()"; break; default: result = ""; break; } return result; } string CPPHelper::toString (jsontype_t type) { string result; switch(type) { case JSON_BOOLEAN: result = "jsonrpc::JSON_BOOLEAN"; break; case JSON_INTEGER: result = "jsonrpc::JSON_INTEGER"; break; case JSON_REAL: result = "jsonrpc::JSON_REAL"; break; case JSON_STRING: result = "jsonrpc::JSON_STRING"; break; case JSON_OBJECT: result = "jsonrpc::JSON_OBJECT"; break; case JSON_ARRAY: result = "jsonrpc::JSON_ARRAY"; break; } return result; } string CPPHelper::generateParameterDeclarationList (Procedure &proc) { stringstream param_string; parameterNameList_t list = proc.GetParameters(); for (parameterNameList_t::iterator it = list.begin(); it != list.end();) { param_string << toCppParamType(it->second) << " " << it->first; if (++it != list.end()) { param_string << ", "; } } return param_string.str(); } 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) return toCppType(type, true, true); else return toCppType(type, false, false); } string CPPHelper::class2Filename(const string &classname) { vector packages = splitPackages(classname); string data = packages.at(packages.size()-1); std::transform(data.begin(), data.end(), data.begin(), ::tolower); return data+".h"; } std::vector CPPHelper::splitPackages(const string &classname) { string s = classname; string delimiter = "::"; size_t pos = 0; vector tokens; while ((pos = s.find(delimiter)) != string::npos) { tokens.push_back(s.substr(0, pos)); s.erase(0, pos + delimiter.length()); } tokens.push_back(s); return tokens; } 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(" */"); cg.writeNewLine(); string stub_upper = stubname; 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.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); StubGenerator::replaceAll2(stub_upper, "::", "_"); cg.writeLine(StubGenerator::replaceAll(TEMPLATE_EPILOG, "", stub_upper)); } int CPPHelper::namespaceOpen(CodeGenerator &cg, const string &classname) { vector namespaces = splitPackages(classname); for (unsigned int i=0; i < namespaces.size() -1; i++) { cg.write("namespace "); cg.write(namespaces.at(i)); cg.writeLine(" {"); cg.increaseIndentation(); } return namespaces.size()-1; } void CPPHelper::namespaceClose(CodeGenerator &cg, int depth) { for (int i=0; i < depth; i++) { cg.decreaseIndentation(); cg.writeLine("}"); } } 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] == '_')) { result[i] = '_'; } } return result; } string CPPHelper::isCppConversion (jsontype_t type) { string result; switch(type) { case JSON_BOOLEAN: result = ".isBool()"; break; case JSON_INTEGER: result = ".isIntegral()"; break; case JSON_REAL: result = ".isDouble()"; break; case JSON_STRING: result = ".isString()"; break; case JSON_OBJECT: result = ".isObject()"; break; case JSON_ARRAY: result = ".isArray()"; break; } return result; } libjson-rpc-cpp-0.7.0/src/stubgenerator/helper/cpphelper.h000077500000000000000000000033311275256467400236320ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file cpphelper.h * @date 29.09.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_CPPHELPER_H #define JSONRPC_CPP_CPPHELPER_H #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); }; } #endif // JSONRPC_CPP_CPPSTUBGENERATOR_H libjson-rpc-cpp-0.7.0/src/stubgenerator/main.cpp000066400000000000000000000016071275256467400216510ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file main.cpp * @date 29.09.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include #include #include "stubgeneratorfactory.h" using namespace std; using namespace jsonrpc; int main(int argc, char** argv) { vector stubgens; vector procedures; bool result = StubGeneratorFactory::createStubGenerators(argc, argv, procedures, stubgens, stdout, stderr); for (unsigned int i=0; i < stubgens.size(); ++i) { stubgens[i]->generateStub(); } StubGeneratorFactory::deleteStubGenerators(stubgens); return !result; } libjson-rpc-cpp-0.7.0/src/stubgenerator/server/000077500000000000000000000000001275256467400215235ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/src/stubgenerator/server/cppserverstubgenerator.cpp000077500000000000000000000161021275256467400270500ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file CPPServerStubGenerator.cpp * @date 01.05.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "cppserverstubgenerator.h" #include "../helper/cpphelper.h" #include #include #include #define TEMPLATE_CPPSERVER_METHODBINDING "this->bindAndAddMethod(jsonrpc::Procedure(\"\", , , NULL), &::I);" #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) : jsonrpc::AbstractServer<>(conn, type)" #define TEMPLATE_CPPSERVER_SIGMETHOD "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_SERVER_ABSTRACTDEFINITION "virtual () = 0;" using namespace std; using namespace jsonrpc; 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) : StubGenerator(stubname, procedures, filename) { } void CPPServerStubGenerator::generateStub() { vector classname = CPPHelper::splitPackages(this->stubname); CPPHelper::prolog(*this, this->stubname); this->writeLine("#include "); this->writeNewLine(); int depth = CPPHelper::namespaceOpen(*this, stubname); 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("{"); this->generateBindings(); this->writeLine("}"); this->writeNewLine(); this->generateProcedureDefinitions(); this->generateAbstractDefinitions(); this->decreaseIndentation(); this->decreaseIndentation(); this->writeLine("};"); this->writeNewLine(); CPPHelper::namespaceClose(*this, depth); CPPHelper::epilog(*this,this->stubname); } void CPPServerStubGenerator::generateBindings() { string tmp; this->increaseIndentation(); for(vector::iterator it = this->procedures.begin(); it != this->procedures.end(); ++it) { Procedure &proc = *it; if(proc.GetProcedureType() == RPC_METHOD) { tmp = TEMPLATE_CPPSERVER_METHODBINDING; } else { tmp = TEMPLATE_CPPSERVER_NOTIFICATIONBINDING; } replaceAll2(tmp, "", proc.GetProcedureName()); replaceAll2(tmp, "", CPPHelper::normalizeString(proc.GetProcedureName())); replaceAll2(tmp, "", CPPHelper::toString(proc.GetReturnType())); replaceAll2(tmp, "", generateBindingParameterlist(proc)); replaceAll2(tmp, "", this->stubname); if(proc.GetParameterDeclarationType() == PARAMS_BY_NAME) { replaceAll2(tmp, "", "jsonrpc::PARAMS_BY_NAME"); } else { replaceAll2(tmp, "", "jsonrpc::PARAMS_BY_POSITION"); } this->writeLine(tmp); } this->decreaseIndentation(); } void CPPServerStubGenerator::generateProcedureDefinitions() { for(vector::iterator it = this->procedures.begin(); it != this->procedures.end(); ++it) { Procedure &proc = *it; if(proc.GetProcedureType() == RPC_METHOD) this->writeLine(replaceAll(TEMPLATE_CPPSERVER_SIGMETHOD, "", CPPHelper::normalizeString(proc.GetProcedureName()))); else this->writeLine(replaceAll(TEMPLATE_CPPSERVER_SIGNOTIFICATION, "", CPPHelper::normalizeString(proc.GetProcedureName()))); this->writeLine("{"); this->increaseIndentation(); if (proc.GetParameters().empty()) this->writeLine("(void)request;"); if (proc.GetProcedureType() == RPC_METHOD) this->write("response = "); this->write("this->"); this->write(CPPHelper::normalizeString(proc.GetProcedureName())+"("); this->generateParameterMapping(proc); this->writeLine(");"); this->decreaseIndentation(); this->writeLine("}"); } } void CPPServerStubGenerator::generateAbstractDefinitions() { string tmp; for(vector::iterator it = this->procedures.begin(); it != this->procedures.end(); ++it) { Procedure& proc = *it; tmp = TEMPLATE_SERVER_ABSTRACTDEFINITION; string returntype ="void"; if(proc.GetProcedureType() == RPC_METHOD) { returntype = CPPHelper::toCppReturntype(proc.GetReturnType()); } replaceAll2(tmp, "", returntype); replaceAll2(tmp, "", CPPHelper::normalizeString(proc.GetProcedureName())); replaceAll2(tmp, "", CPPHelper::generateParameterDeclarationList(proc)); this->writeLine(tmp); } } string CPPServerStubGenerator::generateBindingParameterlist(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) << ","; } return parameter.str(); } void CPPServerStubGenerator::generateParameterMapping(Procedure &proc) { string tmp; const parameterNameList_t& params = proc.GetParameters(); int i=0; 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); } else { stringstream tmp2; tmp2 << "request["<< i << "u]" << CPPHelper::toCppConversion(it2->second); tmp = tmp2.str(); } this->write(tmp); if(it2 != --params.end()) { this->write(", "); } i++; } } libjson-rpc-cpp-0.7.0/src/stubgenerator/server/cppserverstubgenerator.h000077500000000000000000000023531275256467400265200ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file serverstubgenerator.h * @date 01.05.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_SERVERSTUBGENERATOR_H #define JSONRPC_CPP_SERVERSTUBGENERATOR_H #include "../stubgenerator.h" #include "../codegenerator.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); virtual void generateStub(); void generateBindings(); void generateProcedureDefinitions(); void generateAbstractDefinitions(); std::string generateBindingParameterlist(Procedure &proc); void generateParameterMapping(Procedure &proc); }; } #endif // JSONRPC_CPP_SERVERSTUBGENERATOR_H libjson-rpc-cpp-0.7.0/src/stubgenerator/servertemplate.h000066400000000000000000000037751275256467400234440ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file servertemplate.h * @date 01.05.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_SERVERTEMPLATE_H #define JSONRPC_CPP_SERVERTEMPLATE_H #define TEMPLATE_SERVER_STUB "\ /**\n\ * THIS FILE IS GENERATED BY jsonrpcstub, DO NOT CHANGE IT!!!!!\n\ */\n\ \n\ #ifndef __H_\n\ #define __H_\n\ \n\ #include \n\ \n\ class : public jsonrpc::AbstractServer<>\n\ {\n\ public:\n\ (jsonrpc::AbstractServerConnector& conn) :\n\ jsonrpc::AbstractServer<>(conn) \n\ {\n\ \n\ }\n\ \n\ \n\ \n\ };\n\ #endif //__H_\n\ " #define TEMPLATE_SERVER_METHODBINDING "\ this->bindAndAddMethod(new jsonrpc::Procedure(\"\", , , NULL), &::I);" #define TEMPLATE_SERVER_NOTIFICATIONBINDING "\ this->bindAndAddNotification(new jsonrpc::Procedure(\"\", , NULL), &::I);" #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 "\ inline virtual void I(const Json::Value& request) \n\ {\n\ this->();\n\ }\n\ " #define TEMPLATE_SERVER_ABSTRACTDEFINITION "\ virtual () = 0;\n\ " #endif // JSONRPC_CPP_SERVERTEMPLATE_H libjson-rpc-cpp-0.7.0/src/stubgenerator/stubgenerator.cpp000066400000000000000000000035551275256467400236150ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file stubgenerator.cpp * @date 01.05.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include #include #include #include #include "stubgenerator.h" #include "helper/cpphelper.h" #include "server/cppserverstubgenerator.h" #include "client/cppclientstubgenerator.h" #include "client/jsclientstubgenerator.h" using namespace std; using namespace jsonrpc; #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) : CodeGenerator (outputstream), stubname (stubname), procedures (procedures) { } 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 result = text; replaceAll2(result, fnd, rep); return result; } 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); pos = result.find(find, pos + replace.length()); } } libjson-rpc-cpp-0.7.0/src/stubgenerator/stubgenerator.h000066400000000000000000000025671275256467400232640ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file stubgenerator.h * @date 01.05.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_STUBGENERATOR_H #define JSONRPC_CPP_STUBGENERATOR_H #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); virtual ~StubGenerator(); virtual void generateStub() = 0; 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; }; } #endif // JSONRPC_CPP_STUBGENERATOR_H libjson-rpc-cpp-0.7.0/src/stubgenerator/stubgeneratorfactory.cpp000066400000000000000000000135741275256467400252070ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file stubgeneratorfactory.cpp * @date 11/19/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "stubgeneratorfactory.h" #include #include #include #include #include "helper/cpphelper.h" #include "client/cppclientstubgenerator.h" #include "client/jsclientstubgenerator.h" #include "server/cppserverstubgenerator.h" 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"); 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_end *end = arg_end(20); void* argtable[] = {inputfile, help, version, verbose, cppserver, cppserverfile, cppclient, cppclientfile, jsclient, jsclientfile,end}; if (arg_parse(argc,argv,argtable) > 0) { arg_print_errors(stderr, end, argv[0]); arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return false; } if (help->count > 0) { fprintf(stdout, "Usage: %s ", argv[0]); arg_print_syntax(stdout,argtable,"\n"); cout << endl; arg_print_glossary_gnu(stdout, argtable); arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return true; } if (version->count > 0) { 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; } if (inputfile->count == 0) { fprintf(stderr, "Invalid arguments: specfile must be provided.\n"); arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return false; } try { procedures = SpecificationParser::GetProceduresFromFile(inputfile->filename[0]); if (verbose->count > 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] "); } else { fprintf(stdout, "\t[Notification] "); } fprintf(stdout, "%s\n", procedures.at(i).GetProcedureName().c_str()); } fprintf(stdout, "\n"); } if (cppserver->count > 0) { string filename; if (cppserverfile->count > 0) filename = cppserverfile->sval[0]; 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)); } if (cppclient->count > 0) { string filename; if (cppclientfile->count > 0) filename = cppclientfile->sval[0]; 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)); } if (jsclient->count > 0) { string filename; if (jsclientfile->count > 0) filename = jsclientfile->sval[0]; else 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)); } } catch (const JsonRpcException &ex) { fprintf(stderr, "%s\n", ex.what()); arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return false; } arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return true; } void StubGeneratorFactory::deleteStubGenerators(std::vector &stubgenerators) { for (unsigned int i=0; i < stubgenerators.size(); ++i) { delete stubgenerators[i]; } } libjson-rpc-cpp-0.7.0/src/stubgenerator/stubgeneratorfactory.h000066400000000000000000000016641275256467400246510ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file stubgeneratorfactory.h * @date 11/19/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_STUBGENERATORFACTORY_H #define JSONRPC_CPP_STUBGENERATORFACTORY_H #include #include "stubgenerator.h" 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); }; } // namespace jsonrpc #endif // JSONRPC_CPP_STUBGENERATORFACTORY_H libjson-rpc-cpp-0.7.0/src/stubgenerator/stubhelper.h000066400000000000000000000007521275256467400225470ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file stubhelper.h * @date 01.05.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef STUBHELPER_H #define STUBHELPER_H #include #include #endif // STUBHELPER_H libjson-rpc-cpp-0.7.0/src/test/000077500000000000000000000000001275256467400163105ustar00rootroot00000000000000libjson-rpc-cpp-0.7.0/src/test/CMakeLists.txt000066400000000000000000000074531275256467400210610ustar00rootroot00000000000000 set(CTEST_OUTPUT_ON_FAILURE TRUE) file(GLOB_RECURSE test_source *.cpp) include_directories(..) include_directories(${CMAKE_BINARY_DIR}) include_directories(${JSONCPP_INCLUDE_DIRS}) 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 ) 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 ) 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() list(REMOVE_ITEM test_source "${CMAKE_CURRENT_SOURCE_DIR}/testhttpserver.cpp") endif() if(UNIX_DOMAIN_SOCKET_SERVER AND UNIX_DOMAIN_SOCKET_CLIENT) add_definitions(-DUNIXDOMAINSOCKET_TESTING) endif() if(TCP_SOCKET_SERVER AND TCP_SOCKET_CLIENT) add_definitions(-DTCPSOCKET_TESTING) endif() 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() add_executable(unit_testsuite ${test_source}) target_link_libraries(unit_testsuite jsonrpccommon) target_link_libraries(unit_testsuite jsonrpcserver) 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() if(COMPILE_STUBGEN) target_link_libraries(unit_testsuite libjsonrpcstub) add_dependencies(unit_testsuite libjsonrpcstub) 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) add_test(NAME connector_http WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[connector_http]") 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() 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() if(COMPILE_STUBGEN) add_test(NAME stubgen WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite "[stubgenerator]") endif() 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() add_test(NAME all WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unit_testsuite) libjson-rpc-cpp-0.7.0/src/test/checkexception.h000066400000000000000000000012141275256467400214530ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file checkexception.h * @date 6/7/2015 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #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);} #endif // CHECKEXCEPTION_H libjson-rpc-cpp-0.7.0/src/test/main.cpp000066400000000000000000000006531275256467400177440ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file main.cpp * @date 1/21/2015 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #define CATCH_CONFIG_MAIN #include libjson-rpc-cpp-0.7.0/src/test/mockclientconnectionhandler.cpp000066400000000000000000000017171275256467400245700ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file mockclientconnectionhandler.cpp * @date 10/29/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "mockclientconnectionhandler.h" #if _MSC_VER #include #include #else #include #endif using namespace std; using namespace jsonrpc; MockClientConnectionHandler::MockClientConnectionHandler() : response(""), request(""), timeout(0) { } void MockClientConnectionHandler::HandleRequest(const std::string &request, std::string &retValue) { #if _MSC_VER std::this_thread::sleep_for(std::chrono::microseconds(timeout*1000)); #else usleep(timeout*1000); #endif this->request = request; retValue = response; } libjson-rpc-cpp-0.7.0/src/test/mockclientconnectionhandler.h000066400000000000000000000016771275256467400242420ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file mockclientconnectionhandler.h * @date 10/29/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_MOCKCLIENTCONNECTIONHANDLER_H #define JSONRPC_CPP_MOCKCLIENTCONNECTIONHANDLER_H #include #include namespace jsonrpc { class MockClientConnectionHandler : public IClientConnectionHandler { public: MockClientConnectionHandler(); virtual void HandleRequest(const std::string& request, std::string& retValue); std::string response; std::string request; long timeout; }; } #endif // JSONRPC_CPP_MOCKCLIENTCONNECTIONHANDLER_H libjson-rpc-cpp-0.7.0/src/test/mockclientconnector.cpp000066400000000000000000000020451275256467400230600ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file mockclientconnector.cpp * @date 10/9/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "mockclientconnector.h" using namespace jsonrpc; using namespace std; MockClientConnector::MockClientConnector() { } string MockClientConnector::GetRequest() { return request; } Json::Value MockClientConnector::GetJsonRequest() { Json::Reader reader; Json::Value result; if (reader.parse(request, result)) return result; else return Json::nullValue; } void MockClientConnector::SetResponse(const std::string &response) { this->response = response; } void MockClientConnector::SendRPCMessage(const string &message, string &result) throw(JsonRpcException) { request = message; result = this->response; } libjson-rpc-cpp-0.7.0/src/test/mockclientconnector.h000066400000000000000000000020511275256467400225220ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file mockclientconnector.h * @date 10/9/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_MOCKCLIENTCONNECTOR_H #define JSONRPC_MOCKCLIENTCONNECTOR_H #include namespace jsonrpc { class MockClientConnector : public IClientConnector { public: MockClientConnector(); void SetResponse(const std::string &response); std::string GetRequest(); Json::Value GetJsonRequest(); virtual void SendRPCMessage(const std::string& message, std::string& result) throw(JsonRpcException); private: std::string response; std::string request; }; } // namespace jsonrpc #endif // JSONRPC_MOCKCLIENTCONNECTOR_H libjson-rpc-cpp-0.7.0/src/test/mockserverconnector.cpp000066400000000000000000000026351275256467400231150ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file mockserverconnector.cpp * @date 10/10/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "mockserverconnector.h" using namespace jsonrpc; using namespace std; MockServerConnector::MockServerConnector() { } bool MockServerConnector::StartListening() { return true; } bool MockServerConnector::StopListening() { return true; } bool MockServerConnector::SendResponse(const string &response, void *addInfo) { (void)addInfo; this->response = response; return true; } bool MockServerConnector::SetRequest(const string &request) { this->request = request; return this->OnRequest(this->request, NULL); } Json::Value MockServerConnector::GetJsonRequest() { Json::Reader reader; Json::Value result; if (reader.parse(request, result)) return result; else return Json::nullValue; } string MockServerConnector::GetResponse() { return this->response; } Json::Value MockServerConnector::GetJsonResponse() { Json::Reader reader; Json::Value result; if (reader.parse(response, result)) return result; else return Json::nullValue; } libjson-rpc-cpp-0.7.0/src/test/mockserverconnector.h000066400000000000000000000023131275256467400225530ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file mockserverconnector.h * @date 10/10/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_MOCKSERVERCONNECTOR_H #define JSONRPC_MOCKSERVERCONNECTOR_H #include #include namespace jsonrpc { class MockServerConnector : public AbstractServerConnector { public: MockServerConnector(); virtual bool StartListening(); virtual bool StopListening(); bool virtual SendResponse(const std::string& response, void* addInfo = NULL); bool SetRequest(const std::string &request); Json::Value GetJsonRequest(); std::string GetResponse(); Json::Value GetJsonResponse(); private: std::string request; std::string response; }; } // namespace jsonrpc #endif // JSONRPC_MOCKSERVERCONNECTOR_H libjson-rpc-cpp-0.7.0/src/test/spec.json000066400000000000000000000015331275256467400201370ustar00rootroot00000000000000[ { "name": "sayHello", "params": { "name": "Peter" }, "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" } ] libjson-rpc-cpp-0.7.0/src/test/test_client.cpp000066400000000000000000000232251275256467400213350ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file test_client.cpp * @date 28.09.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include #include #include "mockclientconnector.h" #include "checkexception.h" #define TEST_MODULE "[client]" 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_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; } struct F { MockClientConnector c; Client client; Json::Value params; F() : client(c, JSONRPC_CLIENT_V2) { } }; struct F1 { MockClientConnector c; Client client; Json::Value params; F1() : client(c, JSONRPC_CLIENT_V1) { } }; } using namespace testclient; TEST_CASE_METHOD(F, "test_client_id", TEST_MODULE) { params.append(33); c.SetResponse("{\"jsonrpc\":\"2.0\", \"id\": \"1\", \"result\": 23}"); Json::Value response = client.CallMethod("abcd", params); CHECK(response.asInt() == 23); c.SetResponse("{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 24}"); response = client.CallMethod("abcd", params); CHECK(response.asInt() == 24); } TEST_CASE_METHOD(F, "test_client_v2_method_success", TEST_MODULE) { params.append(23); c.SetResponse("{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23}"); Json::Value response = client.CallMethod("abcd", params); Json::Value v = c.GetJsonRequest(); CHECK(v["method"].asString() == "abcd"); CHECK(v["params"][0].asInt() == 23); CHECK(v["jsonrpc"].asString() == "2.0"); CHECK(v["id"].asInt() == 1); } TEST_CASE_METHOD(F, "test_client_v2_notification_success", TEST_MODULE) { params.append(23); client.CallNotification("abcd", params); Json::Value v = c.GetJsonRequest(); CHECK(v["method"].asString() == "abcd"); CHECK(v["params"][0].asInt() == 23); CHECK(v["jsonrpc"].asString() == "2.0"); CHECK(v.isMember("id") == false); } 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); } 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); } 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); c.SetResponse("{\"jsonrpc\":\"2.0\", \"id2\": 1, \"result\": 23}"); 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); 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); c.SetResponse("{\"jsonrpc\":\"2.0\", \"id\": 1, \"error\": {}}"); 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); c.SetResponse("{}"); CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("[]"); 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); } TEST_CASE_METHOD(F, "test_client_v2_batchcall_success", TEST_MODULE) { BatchCall bc; CHECK(bc.addCall("abc", Json::nullValue, false) == 1); CHECK(bc.addCall("def", Json::nullValue, true) == -1); CHECK(bc.addCall("abc", Json::nullValue, false) == 2); c.SetResponse("[{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23},{\"jsonrpc\":\"2.0\", \"id\": 2, \"result\": 24}]"); BatchResponse response = client.CallProcedures(bc); CHECK(response.hasErrors() == false); CHECK(response.getResult(1).asInt() == 23); CHECK(response.getResult(2).asInt() == 24); CHECK(response.getResult(3).isNull() == true); Json::Value request = c.GetJsonRequest(); CHECK(request.size() == 3); CHECK(request[0]["method"].asString() == "abc"); CHECK(request[0]["id"].asInt() == 1); CHECK(request[1]["method"].asString() == "def"); CHECK(request[1]["id"].isNull() == true); CHECK(request[2]["id"].asInt() == 2); bc.toString(false); } TEST_CASE_METHOD(F, "test_client_v2_batchcall_error", TEST_MODULE) { BatchCall bc; CHECK(bc.addCall("abc", Json::nullValue, false) == 1); CHECK(bc.addCall("def", Json::nullValue, false) == 2); CHECK(bc.addCall("abc", Json::nullValue, false) == 3); c.SetResponse("[{\"jsonrpc\":\"2.0\", \"id\": 1, \"result\": 23},{\"jsonrpc\":\"2.0\", \"id\": 2, \"error\": {\"code\": -32001, \"message\": \"error1\"}},{\"jsonrpc\":\"2.0\", \"id\": null, \"error\": {\"code\": -32002, \"message\": \"error2\"}}]"); BatchResponse response = client.CallProcedures(bc); CHECK(response.hasErrors() == true); CHECK(response.getResult(1).asInt() == 23); CHECK(response.getResult(2).isNull() == true); CHECK(response.getResult(3).isNull() == true); CHECK(response.getErrorMessage(2) == "error1"); CHECK(response.getErrorMessage(3) == ""); c.SetResponse("{}"); CHECK_EXCEPTION_TYPE(client.CallProcedures(bc), JsonRpcException, check_exception2); c.SetResponse("[1,2,3]"); CHECK_EXCEPTION_TYPE(client.CallProcedures(bc), JsonRpcException, check_exception2); c.SetResponse("[[],[],[]]"); CHECK_EXCEPTION_TYPE(client.CallProcedures(bc), JsonRpcException, check_exception2); } TEST_CASE_METHOD(F1, "test_client_v1_method_success", TEST_MODULE) { params.append(23); c.SetResponse("{\"id\": 1, \"result\": 23, \"error\": null}"); Json::Value response = client.CallMethod("abcd", params); Json::Value v = c.GetJsonRequest(); CHECK(v["method"].asString() == "abcd"); CHECK(v["params"][0].asInt() == 23); CHECK(v.isMember("jsonrpc") == false); CHECK(v["id"].asInt() == 1); CHECK(response.asInt() == 23); } TEST_CASE_METHOD(F1, "test_client_v1_notification_success", TEST_MODULE) { params.append(23); client.CallNotification("abcd", params); Json::Value v = c.GetJsonRequest(); CHECK(v["method"].asString() == "abcd"); CHECK(v["params"][0].asInt() == 23); CHECK(v.isMember("id") == true); CHECK(v["id"] == Json::nullValue); } 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); 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); } 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); c.SetResponse("{\"id\": 1, \"result\": 23}"); 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); c.SetResponse("{\"id\": 1}"); 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); c.SetResponse("{\"id\": 1, \"result\": null, \"error\": {}}"); CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("{}"); CHECK_EXCEPTION_TYPE(client.CallMethod("abcd", Json::nullValue), JsonRpcException, check_exception2); c.SetResponse("[]"); 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); } libjson-rpc-cpp-0.7.0/src/test/test_common.cpp000066400000000000000000000174571275256467400213610ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file test_common.cpp * @date 28.09.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include #include #include #include #include #include "checkexception.h" #define TEST_MODULE "[common]" 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_exception2(JsonRpcException const & ex) { return ex.GetCode() == Errors::ERROR_SERVER_PROCEDURE_SPECIFICATION_SYNTAX; } } 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); //Expected to pass validation Json::Value param1; param1["name"] = "Peter"; param1["ssnr"] = 4711; CHECK(proc1.ValidateNamedParameters(param1) == true); //Expected to fail validation Json::Value param2; param2.append("Peter"); param2.append(4711); CHECK(proc1.ValidateNamedParameters(param2) == false); //Expected to fail validation Json::Value param3; param3.append(4711); 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, NULL); Json::Value param4; Json::Value array; array.append(0); param4["bool"] = true; param4["object"] = param1; param4["array"] = array; param4["real"] = 0.332; param4["int"] = 3; CHECK(proc2.ValidateNamedParameters(param4) == true); param4["bool"] = "String"; CHECK(proc2.ValidateNamedParameters(param4) == false); param4["bool"] = true; param4["object"] = "String"; CHECK(proc2.ValidateNamedParameters(param4) == false); param4["object"] = param1; param4["real"] = "String"; CHECK(proc2.ValidateNamedParameters(param4) == false); param4["real"] = 0.322; param4["array"] = "String"; CHECK(proc2.ValidateNamedParameters(param4) == false); param4["array"] = array; param4["int"] = "String"; CHECK(proc2.ValidateNamedParameters(param4) == false); } TEST_CASE("test_exception", TEST_MODULE) { JsonRpcException ex(Errors::ERROR_CLIENT_CONNECTOR); CHECK(string(ex.what()) == "Exception -32003 : Client connector error"); CHECK(string(ex.GetMessage()) == "Client connector error"); CHECK(ex.GetCode() == -32003); JsonRpcException ex2(Errors::ERROR_CLIENT_CONNECTOR, "addInfo"); CHECK(string(ex2.what()) == "Exception -32003 : Client connector error: addInfo"); JsonRpcException ex3("addInfo"); CHECK(string(ex3.what()) == "addInfo"); CHECK(ex3.GetMessage() == "addInfo"); CHECK(ex3.GetCode() == 0); Json::Value data; data.append(13); data.append(41); 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); } TEST_CASE("test_specificationparser_success", TEST_MODULE) { std::vector procs = SpecificationParser::GetProceduresFromFile("testspec5.json"); REQUIRE(procs.size() == 4); CHECK(procs[0].GetProcedureName() == "testmethod"); CHECK(procs[0].GetReturnType() == JSON_STRING); CHECK(procs[0].GetProcedureType() == RPC_METHOD); CHECK(procs[0].GetParameterDeclarationType() == PARAMS_BY_NAME); CHECK(procs[2].GetProcedureName() == "testmethod2"); CHECK(procs[2].GetReturnType() == JSON_REAL); CHECK(procs[2].GetProcedureType() == RPC_METHOD); CHECK(procs[2].GetParameterDeclarationType() == PARAMS_BY_NAME); CHECK(procs[1].GetProcedureName() == "testnotification"); CHECK(procs[1].GetProcedureType() == RPC_NOTIFICATION); CHECK(procs[1].GetParameterDeclarationType() == PARAMS_BY_NAME); CHECK(procs[3].GetProcedureName() == "testnotification2"); CHECK(procs[3].GetProcedureType() == RPC_NOTIFICATION); CHECK(procs[3].GetParameterDeclarationType() == PARAMS_BY_NAME); } 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("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)); Json::Value result = SpecificationWriter::toJsonValue(procedures); REQUIRE(result.isArray() == true); REQUIRE(result.size() == procedures.size()); CHECK(result[0]["name"].asString() == "testmethod1"); CHECK(result[1]["name"].asString() == "testmethod2"); CHECK(result[2]["name"].asString() == "testnotification1"); CHECK(result[3]["name"].asString() == "testnotification2"); CHECK(result[4]["name"].asString() == "testnotification3"); REQUIRE(result[0]["params"].isObject() == true); CHECK(result[0]["params"]["param1"].isIntegral() == true); CHECK(result[0]["params"]["param2"].isDouble() == true); REQUIRE(result[1]["params"].isArray() == true); CHECK(result[1]["params"][0].isObject() == true); CHECK(result[1]["params"][1].isArray() == true); REQUIRE(result[2]["params"].isObject() == true); CHECK(result[2]["params"]["param1"].isBool() == true); CHECK(result[2]["params"]["param2"].isString() == true); REQUIRE(result[3]["params"].isArray() == true); CHECK(result[3]["params"][0].isIntegral() == true); CHECK(result[3]["params"][1].isString() == true); CHECK(result[4].isMember("params") == false); CHECK(result[0]["returns"].isIntegral() == true); CHECK(result[1]["returns"].isIntegral() == true); CHECK(SpecificationWriter::toFile("testspec.json", procedures) == true); CHECK(SpecificationWriter::toFile("/a/b/c/testspec.json", procedures) == false); } libjson-rpc-cpp-0.7.0/src/test/test_connector_http.cpp000066400000000000000000000141651275256467400231130ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file test_connector_http.cpp * @date 28.09.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifdef HTTP_TESTING #include #include #include #include #include "mockclientconnectionhandler.h" #include "testhttpserver.h" #include "checkexception.h" using namespace jsonrpc; using namespace std; #define TEST_PORT 8383 #define CLIENT_URL "http://localhost:8383" #define TEST_MODULE "[connector_http]" namespace testhttpserver { struct F { HttpServer server; HttpClient client; MockClientConnectionHandler handler; F() : server(TEST_PORT), client(CLIENT_URL) { server.SetHandler(&handler); server.StartListening(); } ~F() { server.StopListening(); } }; 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; } } using namespace testhttpserver; TEST_CASE_METHOD(F, "test_http_success", TEST_MODULE) { handler.response = "exampleresponse"; string result; client.SendRPCMessage("examplerequest", result); CHECK(handler.request == "examplerequest"); CHECK(result == "exampleresponse"); } 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); } #ifndef WIN32 TEST_CASE("test_http_server_multiplestart", TEST_MODULE) { HttpServer server(TEST_PORT); CHECK(server.StartListening() == true); HttpServer server2(TEST_PORT); CHECK(server2.StartListening() == false); CHECK(server.StopListening() == true); } #endif 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); 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); } TEST_CASE("test_http_client_headers", TEST_MODULE) { TestHttpServer server(TEST_PORT); HttpClient client(CLIENT_URL); REQUIRE(server.StartListening() == true); client.AddHeader("X-Auth", "1234"); server.SetResponse("asdf"); string result; client.SendRPCMessage("", result); CHECK(result == "asdf"); CHECK(server.GetHeader("X-Auth") == "1234"); client.RemoveHeader("X-Auth"); client.SendRPCMessage("", result); CHECK(server.GetHeader("X-Auth") == ""); server.StopListening(); } TEST_CASE_METHOD(F, "test_http_get", TEST_MODULE) { CURL* curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, CLIENT_URL); curl_easy_setopt(curl, CURLOPT_NOBODY, 1); CURLcode code = curl_easy_perform(curl); REQUIRE(code == CURLE_OK); long http_code = 0; curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &http_code); CHECK(http_code == 405); curl_easy_cleanup(curl); } TEST_CASE_METHOD(F, "test_http_get_options", TEST_MODULE) { CURL* curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, CLIENT_URL); curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "OPTIONS"); CURLcode code = curl_easy_perform(curl); REQUIRE(code == CURLE_OK); long http_code = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); CHECK(http_code == 200); // No error when server asked for OPTIONS. curl_easy_cleanup(curl); } TEST_CASE("test_http_server_endpoints", TEST_MODULE) { MockClientConnectionHandler handler1; MockClientConnectionHandler handler2; handler1.response = "response1"; handler2.response = "response2"; HttpServer server(TEST_PORT); server.SetUrlHandler("/handler1", &handler1); server.SetUrlHandler("/handler2", &handler2); REQUIRE(server.StartListening() == true); HttpClient client1("http://localhost:8383/handler1"); HttpClient client2("http://localhost:8383/handler2"); HttpClient client3("http://localhost:8383/handler3"); string response; client1.SendRPCMessage("test", response); CHECK(response == "response1"); client2.SendRPCMessage("test", response); CHECK(response == "response2"); CHECK_EXCEPTION_TYPE(client3.SendRPCMessage("test", response), JsonRpcException, check_exception2); client3.SetUrl("http://localhost:8383/handler2"); client3.SendRPCMessage("test", response); CHECK(response == "response2"); server.StopListening(); } TEST_CASE_METHOD(F, "test_http_server_longpost", TEST_MODULE) { int mb = 5; unsigned long size = mb * 1024*1024; char* str = (char*) malloc(size * sizeof(char)); if (str == NULL) { FAIL("Could not allocate enough memory for test"); } for (unsigned long i=0; i < size; i++) { str[i] = (char)('a'+(i%26)); } str[size-1] = '\0'; handler.response = str; string response; client.SetTimeout(-1); client.SendRPCMessage(str, response); CHECK(handler.request == str); CHECK(response == handler.response); CHECK(response.size() == size-1); free(str); } TEST_CASE("test_http_server_ssl", TEST_MODULE) { HttpServer server(TEST_PORT, "/a/b/c", "/d/e/f"); CHECK(server.StartListening() == false); HttpServer server2(TEST_PORT, "server.pem", "server.key"); CHECK(server2.StartListening() == true); server2.StopListening(); } #endif libjson-rpc-cpp-0.7.0/src/test/test_connector_tcpsocket.cpp000066400000000000000000000052011275256467400241220ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file test_connector_tcpsocket.cpp * @date 27/07/2015 * @author Alexandre Poirot * @license See attached LICENSE.txt ************************************************************************/ #ifdef TCPSOCKET_TESTING #include #include #include #include "mockclientconnectionhandler.h" #include "checkexception.h" using namespace jsonrpc; using namespace std; #ifndef DELIMITER_CHAR #define DELIMITER_CHAR char(0x0A) #endif #define TEST_MODULE "[connector_tcpsocket]" #define IP "127.0.0.1" #define PORT 50000 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; } } using namespace testtcpsocketserver; TEST_CASE_METHOD(F, "test_tcpsocket_success", TEST_MODULE) { handler.response = "exampleresponse"; handler.timeout = 100; string result; string request = "examplerequest"; request.push_back(DELIMITER_CHAR); string expectedResult = "exampleresponse"; expectedResult.push_back(DELIMITER_CHAR); client.SendRPCMessage(request, result); CHECK(handler.request == request); CHECK(result == expectedResult); } TEST_CASE("test_tcpsocket_server_multiplestart", TEST_MODULE) { TcpSocketServer server(IP, PORT); CHECK(server.StartListening() == true); CHECK(server.StartListening() == false); TcpSocketServer server2(IP, PORT); CHECK(server2.StartListening() == false); CHECK(server2.StopListening() == false); CHECK(server.StopListening() == true); } TEST_CASE("test_tcpsocket_client_invalid", TEST_MODULE) { TcpSocketClient client("127.0.0.1", 40000); //If this test fails, check that port 40000 is really unused. If it is used, change this port value to an unused port, recompile tests and run tests again. string result; CHECK_EXCEPTION_TYPE(client.SendRPCMessage("foobar", result), JsonRpcException, check_exception1); } #endif libjson-rpc-cpp-0.7.0/src/test/test_connector_unixdomainsocket.cpp000066400000000000000000000052261275256467400255160ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file test_connector_unixdomainsocket.cpp * @date 6/8/2015 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifdef UNIXDOMAINSOCKET_TESTING #include #include #include #include "mockclientconnectionhandler.h" #include "checkexception.h" using namespace jsonrpc; using namespace std; #ifndef DELIMITER_CHAR #define DELIMITER_CHAR char(0x0A) #endif #define TEST_MODULE "[connector_unixdomainsocket]" #define SOCKET_PATH "/tmp/jsonrpccpp-socket" namespace testunixdomainsocketserver { struct F { UnixDomainSocketServer server; UnixDomainSocketClient client; MockClientConnectionHandler handler; F() : server(SOCKET_PATH), client(SOCKET_PATH) { server.SetHandler(&handler); REQUIRE(server.StartListening()); } ~F() { server.StopListening(); unlink(SOCKET_PATH); } }; bool check_exception1(JsonRpcException const&ex) { return ex.GetCode() == Errors::ERROR_CLIENT_CONNECTOR; } } using namespace testunixdomainsocketserver; TEST_CASE_METHOD(F, "test_unixdomainsocket_success", TEST_MODULE) { handler.response = "exampleresponse"; handler.timeout = 100; string result; string request = "examplerequest"; request.push_back(DELIMITER_CHAR); string expectedResult = "exampleresponse"; expectedResult.push_back(DELIMITER_CHAR); client.SendRPCMessage(request, result); CHECK(handler.request == request); CHECK(result == expectedResult); } TEST_CASE("test_unixdomainsocket_server_multiplestart", TEST_MODULE) { UnixDomainSocketServer server(SOCKET_PATH); CHECK(server.StartListening() == true); CHECK(server.StartListening() == false); UnixDomainSocketServer server2(SOCKET_PATH); CHECK(server2.StartListening() == false); CHECK(server2.StopListening() == false); CHECK(server.StopListening() == true); unlink(SOCKET_PATH); } TEST_CASE("test_unixdomainsocket_client_invalid", TEST_MODULE) { UnixDomainSocketClient client("tmp/someinvalidpath"); string result; CHECK_EXCEPTION_TYPE(client.SendRPCMessage("foobar", result), JsonRpcException, check_exception1); } #endif libjson-rpc-cpp-0.7.0/src/test/test_integration.cpp000066400000000000000000000065441275256467400224070ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file test_integration.cpp * @date 28.09.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifdef STUBGEN_TESTING #include #include #include #include "gen/abstractstubserver.h" #include "gen/stubclient.h" using namespace jsonrpc; using namespace std; #define TEST_PORT 8383 #define CLIENT_URL "http://localhost:8383" #define TEST_PATH "/tmp/jsonrpccppintegrationtest" #define TEST_MODULE "[integration]" class StubServer : public AbstractStubServer { public: StubServer(AbstractServerConnector &connector) : AbstractStubServer(connector) {} virtual void notifyServer() { } 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 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; result["name"] = name; result["age"] = age; return result; } virtual std::string methodWithoutParameters() { return "foo"; } }; #ifdef HTTP_TESTING TEST_CASE("test_integration_http", TEST_MODULE) { HttpServer sconn(TEST_PORT); HttpClient cconn(CLIENT_URL); StubServer server(sconn); server.StartListening(); StubClient client(cconn); CHECK(client.addNumbers(3,4) == 7); CHECK(client.addNumbers2(3.2,4.2) == 7.4); CHECK(client.sayHello("Test") == "Hello Test"); CHECK(client.methodWithoutParameters() == "foo"); CHECK(client.isEqual("str1", "str1") == true); CHECK(client.isEqual("str1", "str2") == false); Json::Value result = client.buildObject("Test", 33); CHECK(result["name"].asString() == "Test"); CHECK(result["age"].asInt() == 33); server.StopListening(); } #endif #ifdef UNIXDOMAINSOCKET_TESTING #include #include TEST_CASE("test_integration_unixdomain", TEST_MODULE) { UnixDomainSocketServer sconn(TEST_PATH); UnixDomainSocketClient cconn(TEST_PATH); StubServer server(sconn); server.StartListening(); StubClient client(cconn); CHECK(client.addNumbers(3,4) == 7); CHECK(client.addNumbers2(3.2,4.2) == 7.4); CHECK(client.sayHello("Test") == "Hello Test"); CHECK(client.methodWithoutParameters() == "foo"); CHECK(client.isEqual("str1", "str1") == true); CHECK(client.isEqual("str1", "str2") == false); Json::Value result = client.buildObject("Test", 33); CHECK(result["name"].asString() == "Test"); CHECK(result["age"].asInt() == 33); server.StopListening(); } #endif #endif libjson-rpc-cpp-0.7.0/src/test/test_server.cpp000066400000000000000000000416371275256467400213740ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file test_server.cpp * @date 28.09.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include #include "testserver.h" #include "mockserverconnector.h" #define TEST_MODULE "[server]" using namespace jsonrpc; using namespace std; namespace testserver { struct F { MockServerConnector c; TestServer server; F() : server(c) {} }; struct F1 { MockServerConnector c; TestServer server; F1() : server(c, JSONRPC_SERVER_V1) {} }; } using namespace testserver; TEST_CASE_METHOD(F, "test_server_v2_method_success", TEST_MODULE) { c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello\",\"params\":{\"name\":\"Peter\"}}"); CHECK(c.GetJsonResponse()["result"].asString() == "Hello: Peter!"); CHECK(c.GetJsonResponse()["id"].asInt() == 1); CHECK(c.GetJsonResponse()["jsonrpc"].asString() == "2.0"); CHECK(c.GetJsonResponse().isMember("error") == false); c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"add\",\"params\":{\"value1\":5,\"value2\":7}}"); CHECK(c.GetJsonResponse()["result"].asInt() == 12); CHECK(c.GetJsonResponse()["id"].asInt() == 1); 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]}"); CHECK(c.GetJsonResponse()["result"].asInt() == -2); CHECK(c.GetJsonResponse()["id"].asInt() == 1); CHECK(c.GetJsonResponse()["jsonrpc"].asString() == "2.0"); CHECK(c.GetJsonResponse().isMember("error") == false); c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": null, \"method\": \"sub\",\"params\":[5,7]}"); CHECK(c.GetJsonResponse()["result"].asInt() == -2); CHECK(c.GetJsonResponse()["id"].isNull() == true); 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]}"); CHECK(c.GetJsonResponse()["result"].asInt() == -2); CHECK(c.GetJsonResponse()["id"].asString() == "1"); CHECK(c.GetJsonResponse()["jsonrpc"].asString() == "2.0"); CHECK(c.GetJsonResponse().isMember("error") == false); c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 4294967295, \"method\": \"sub\",\"params\":[5,7]}"); CHECK(c.GetJsonResponse()["result"].asInt() == -2); CHECK(c.GetJsonResponse()["id"].asLargestUInt() == (unsigned long)4294967295); CHECK(c.GetJsonResponse()["jsonrpc"].asString() == "2.0"); CHECK(c.GetJsonResponse().isMember("error") == false); } TEST_CASE_METHOD(F, "test_server_v2_notification_success", TEST_MODULE) { c.SetRequest("{\"jsonrpc\":\"2.0\", \"method\": \"initCounter\",\"params\":{\"value\": 33}}"); CHECK(server.getCnt() == 33); CHECK(c.GetResponse() == ""); c.SetRequest("{\"jsonrpc\":\"2.0\", \"method\": \"incrementCounter\",\"params\":{\"value\": 33}}"); CHECK(server.getCnt() == 66); CHECK(c.GetResponse() == ""); } TEST_CASE_METHOD(F, "test_server_v2_invalidjson", TEST_MODULE) { c.SetRequest("{\"jsonrpc\":\"2."); CHECK(c.GetJsonResponse()["error"]["code"] == -32700); CHECK(c.GetJsonResponse().isMember("result") == false); } TEST_CASE_METHOD(F, "test_server_v2_invalidrequest", TEST_MODULE) { //wrong rpc version c.SetRequest("{\"jsonrpc\":\"1.0\", \"id\": 1, \"method\": \"sayHello\",\"params\":{\"name\":\"Peter\"}}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32600); CHECK(c.GetJsonResponse().isMember("result") == false); //wrong rpc version type c.SetRequest("{\"jsonrpc\":2.0, \"id\": 1, \"method\": \"sayHello\",\"params\":{\"name\":\"Peter\"}}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32600); CHECK(c.GetJsonResponse().isMember("result") == false); //no method name c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1,\"params\":{\"name\":\"Peter\"}}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32600); CHECK(c.GetJsonResponse().isMember("result") == false); //wrong method name type c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": {}, \"params\":{\"name\":\"Peter\"}}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32600); CHECK(c.GetJsonResponse().isMember("result") == false); //invalid param structure c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello\",\"params\":1}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32600); CHECK(c.GetJsonResponse().isMember("result") == false); // c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 3.2, \"method\": \"sayHello\",\"params\":{\"name\":\"Peter\"}}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32600); CHECK(c.GetJsonResponse().isMember("result") == false); c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": 3,\"params\":{\"name\":\"Peter\"}}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32600); CHECK(c.GetJsonResponse().isMember("result") == false); c.SetRequest("{}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32600); CHECK(c.GetJsonResponse().isMember("result") == false); c.SetRequest("[]"); CHECK(c.GetJsonResponse()["error"]["code"] == -32600); CHECK(c.GetJsonResponse().isMember("result") == false); c.SetRequest("23"); CHECK(c.GetJsonResponse()["error"]["code"] == -32600); CHECK(c.GetJsonResponse().isMember("result") == false); } TEST_CASE_METHOD(F, "test_server_v2_method_error", TEST_MODULE) { //invalid methodname c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello2\",\"params\":{\"name\":\"Peter\"}}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32601); CHECK(c.GetJsonResponse().isMember("result") == false); //call notification as procedure c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"initCounter\",\"params\":{\"value\":3}}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32605); CHECK(c.GetJsonResponse().isMember("result") == false); //call procedure as notification c.SetRequest("{\"jsonrpc\":\"2.0\", \"method\": \"sayHello\",\"params\":{\"name\":\"Peter\"}}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32604); CHECK(c.GetJsonResponse().isMember("result") == false); c.SetRequest("{\"jsonrpc\":\"2.0\", \"method\": \"sub\",\"params\":{\"value1\":3, \"value\": 4}}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32604); CHECK(c.GetJsonResponse().isMember("result") == false); c.SetRequest("{\"jsonrpc\":\"2.0\", \"method\": \"add\",\"params\":[3,4]}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32604); CHECK(c.GetJsonResponse().isMember("result") == false); //userspace exception 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); CHECK(c.GetJsonResponse().isMember("result") == false); } TEST_CASE_METHOD(F, "test_server_v2_params_error", TEST_MODULE) { //invalid param type c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello\",\"params\":{\"name\":23}}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32602); CHECK(c.GetJsonResponse().isMember("result") == false); //invalid param name c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello\",\"params\":{\"name2\":\"Peter\"}}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32602); CHECK(c.GetJsonResponse().isMember("result") == false); //invalid parameter passing mode (array instead of object) c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello\",\"params\":[\"Peter\"]}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32602); CHECK(c.GetJsonResponse().isMember("result") == false); //missing parameter field c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello\"}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32602); CHECK(c.GetJsonResponse().isMember("result") == false); } TEST_CASE_METHOD(F, "test_server_v2_batchcall_success", TEST_MODULE) { //Simple Batchcall with only methods c.SetRequest("[{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello\",\"params\":{\"name\":\"Peter\"}},{\"jsonrpc\":\"2.0\", \"id\": 2, \"method\": \"add\",\"params\":{\"value1\":23,\"value2\": 33}}]"); CHECK(c.GetJsonResponse().size() == 2); CHECK(c.GetJsonResponse()[0]["result"].asString() == "Hello: Peter!"); CHECK(c.GetJsonResponse()[0]["id"].asInt() == 1); CHECK(c.GetJsonResponse()[1]["result"].asInt() == 56); CHECK(c.GetJsonResponse()[1]["id"].asInt() == 2); //Batchcall containing methods and notifications c.SetRequest("[{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello\",\"params\":{\"name\":\"Peter\"}},{\"jsonrpc\":\"2.0\", \"method\": \"initCounter\",\"params\":{\"value\":23}}]"); CHECK(c.GetJsonResponse().size() == 1); CHECK(c.GetJsonResponse()[0]["result"].asString() == "Hello: Peter!"); CHECK(c.GetJsonResponse()[0]["id"].asInt() == 1); CHECK(server.getCnt() == 23); //Batchcall containing only notifications c.SetRequest("[{\"jsonrpc\":\"2.0\", \"method\": \"initCounter\",\"params\":{\"value\":23}},{\"jsonrpc\":\"2.0\", \"method\": \"initCounter\",\"params\":{\"value\":23}}]"); CHECK(c.GetResponse() == ""); } TEST_CASE_METHOD(F, "test_server_v2_batchcall_error", TEST_MODULE) { //success and error responses c.SetRequest("[{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello\",\"params\":{\"name\":\"Peter\"}},{},{\"jsonrpc\":\"2.0\", \"id\": 3, \"method\": \"sayHello\",\"params\":{\"name\":\"Peter3\"}}]"); CHECK(c.GetJsonResponse().size() == 3); CHECK(c.GetJsonResponse()[0]["result"].asString() == "Hello: Peter!"); CHECK(c.GetJsonResponse()[0]["id"].asInt() == 1); CHECK(c.GetJsonResponse()[1]["error"]["code"].asInt() == -32600); CHECK(c.GetJsonResponse()[1]["id"].isNull() == true); CHECK(c.GetJsonResponse()[2]["result"].asString() == "Hello: Peter3!"); CHECK(c.GetJsonResponse()[2]["id"].asInt() == 3); //only invalid requests c.SetRequest("[1,2,3]"); CHECK(c.GetJsonResponse().size() == 3); CHECK(c.GetJsonResponse()[0]["error"]["code"].asInt() == -32600); CHECK(c.GetJsonResponse()[1]["error"]["code"].asInt() == -32600); CHECK(c.GetJsonResponse()[2]["error"]["code"].asInt() == -32600); } TEST_CASE_METHOD(F1, "test_server_v1_method_success", TEST_MODULE) { c.SetRequest("{\"id\": 1, \"method\": \"sub\",\"params\":[5,7]}}"); CHECK(c.GetJsonResponse()["result"].asInt() == -2); CHECK(c.GetJsonResponse()["id"].asInt() == 1); CHECK(c.GetJsonResponse().isMember("jsonrpc") == false); CHECK(c.GetJsonResponse().isMember("error") == true); CHECK(c.GetJsonRequest()["error"] == Json::nullValue); c.SetRequest("{\"id\": \"1\", \"method\": \"sub\",\"params\":[5,7]}"); CHECK(c.GetJsonResponse()["result"].asInt() == -2); CHECK(c.GetJsonResponse()["id"].asString() == "1"); CHECK(c.GetJsonResponse().isMember("jsonrpc") == false); CHECK(c.GetJsonResponse().isMember("error") == true); CHECK(c.GetJsonRequest()["error"] == Json::nullValue); c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": \"1\", \"method\": \"sub\",\"params\":[5,7]}"); CHECK(c.GetJsonResponse()["result"].asInt() == -2); CHECK(c.GetJsonResponse()["id"].asString() == "1"); CHECK(c.GetJsonResponse().isMember("jsonrpc") == false); CHECK(c.GetJsonResponse().isMember("error") == true); CHECK(c.GetJsonRequest()["error"] == Json::nullValue); } TEST_CASE_METHOD(F1, "test_server_v1_notification_success", TEST_MODULE) { c.SetRequest("{\"id\": null, \"method\": \"initZero\", \"params\": null}"); CHECK(server.getCnt() == 0); CHECK(c.GetResponse() == ""); } TEST_CASE_METHOD(F1, "test_server_v1_method_invalid_request", TEST_MODULE) { c.SetRequest("{\"method\": \"sub\", \"params\": []}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32600); CHECK(c.GetJsonResponse()["result"] == Json::nullValue); c.SetRequest("{\"id\": 1, \"method\": \"sub\", \"params\": {\"foo\": true}}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32600); CHECK(c.GetJsonResponse()["result"] == Json::nullValue); c.SetRequest("{\"id\": 1, \"method\": \"sub\", \"params\": true}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32600); CHECK(c.GetJsonResponse()["result"] == Json::nullValue); c.SetRequest("{\"id\": 1, \"params\": []}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32600); CHECK(c.GetJsonResponse()["result"] == Json::nullValue); c.SetRequest("{}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32600); CHECK(c.GetJsonResponse()["result"] == Json::nullValue); c.SetRequest("[]"); CHECK(c.GetJsonResponse()["error"]["code"] == -32600); CHECK(c.GetJsonResponse()["result"] == Json::nullValue); c.SetRequest("23"); CHECK(c.GetJsonResponse()["error"]["code"] == -32600); CHECK(c.GetJsonResponse()["result"] == Json::nullValue); } TEST_CASE_METHOD(F1, "test_server_v1_method_error", TEST_MODULE) { c.SetRequest("{\"id\": 1, \"method\": \"sub\", \"params\": [33]}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32602); CHECK(c.GetJsonResponse()["result"] ==Json::nullValue); c.SetRequest("{\"id\": 1, \"method\": \"sub\", \"params\": [33, \"foo\"]}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32602); CHECK(c.GetJsonResponse()["result"] == Json::nullValue); c.SetRequest("{\"id\": 1, \"method\": \"sub\"}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32600); CHECK(c.GetJsonResponse()["result"] == Json::nullValue); //userspace exception c.SetRequest("{\"id\": 1, \"method\": \"exceptionMethod\",\"params\":null}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32099); CHECK(c.GetJsonResponse()["error"]["message"] == "User exception"); CHECK(c.GetJsonResponse()["result"] == Json::nullValue); } TEST_CASE("test_server_hybrid", TEST_MODULE) { MockServerConnector c; TestServer server(c, JSONRPC_SERVER_V1V2); c.SetRequest("{\"id\": 1, \"method\": \"sub\",\"params\":[5,7]}}"); CHECK(c.GetJsonResponse()["result"].asInt() == -2); CHECK(c.GetJsonResponse()["id"].asInt() == 1); CHECK(c.GetJsonResponse().isMember("jsonrpc") == false); CHECK(c.GetJsonResponse().isMember("error") == true); CHECK(c.GetJsonRequest()["error"] == Json::nullValue); c.SetRequest("{\"id\": null, \"method\": \"initZero\", \"params\": null}"); CHECK(server.getCnt() == 0); CHECK(c.GetResponse() == ""); c.SetRequest("{\"jsonrpc\":\"2.0\", \"id\": 1, \"method\": \"sayHello\",\"params\":{\"name\":\"Peter\"}}"); CHECK(c.GetJsonResponse()["result"].asString() == "Hello: Peter!"); CHECK(c.GetJsonResponse()["id"].asInt() == 1); CHECK(c.GetJsonResponse()["jsonrpc"].asString() == "2.0"); CHECK(c.GetJsonResponse().isMember("error") == false); c.SetRequest("{\"jsonrpc\":\"2.0\", \"method\": \"initCounter\",\"params\":{\"value\": 33}}"); CHECK(server.getCnt() == 33); CHECK(c.GetResponse() == ""); c.SetRequest("{\"jsonrpc\":\"2.0\", \"params\":{\"value\": 33}}"); CHECK(c.GetJsonResponse()["error"]["code"] == -32600); CHECK(c.GetJsonResponse().isMember("result") == false); c.SetRequest("{\"jsonrpc\":\"2.0\", \"params\":{\"value\": 33"); CHECK(c.GetJsonResponse()["error"]["code"] == -32700); CHECK(c.GetJsonResponse().isMember("result") == false); } 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.StartListening() == true); CHECK(server.StopListening() == true); MockServerConnector c2; CHECK(c2.SetRequest("abcd") == false); } libjson-rpc-cpp-0.7.0/src/test/test_stubgenerator.cpp000066400000000000000000000206011275256467400227360ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file test_connector_http.cpp * @date 28.09.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifdef STUBGEN_TESTING #include #include #include #include #include #include #include #include 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); } }; } using namespace teststubgen; #define TEST_MODULE "[stubgenerator]" TEST_CASE("test stubgen cppclient", TEST_MODULE) { stringstream 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("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) throw (jsonrpc::JsonRpcException)") != string::npos); CHECK(result.find("void test_notification(const std::string& name) throw (jsonrpc::JsonRpcException)") != string::npos); CHECK(result.find("double test_method2(const Json::Value& object, const Json::Value& values) throw (jsonrpc::JsonRpcException)") != string::npos); CHECK(result.find("void test_notification2(const Json::Value& object, const Json::Value& values) throw (jsonrpc::JsonRpcException)") != 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); 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("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 double test_method2(const Json::Value& object, const Json::Value& values) = 0;") != string::npos); CHECK(result.find("virtual void test_notification2(const Json::Value& object, const Json::Value& values) = 0;") != string::npos); 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); 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"); JSClientStubGenerator stubgen("TestStubClient", procedures, stream); stubgen.generateStub(); string result = stream.str(); CHECK(result.find("function TestStubClient(url) {") != string::npos); 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); CHECK(result.find("TestStubClient.prototype.test_method2 = function(object, values, callbackSuccess, callbackError)") != string::npos); CHECK(result.find("TestStubClient.prototype.test_notification2 = function(object, values, callbackSuccess, callbackError)") != string::npos); CHECK(JSClientStubGenerator::class2Filename("TestClass") == "testclass.js"); } TEST_CASE("test_stubgen_indentation", TEST_MODULE) { stringstream stream; CodeGenerator cg(stream); cg.setIndentSymbol(" "); cg.increaseIndentation(); cg.write("abc"); CHECK(stream.str() == " abc"); stringstream stream2; CodeGenerator cg2(stream2); cg2.setIndentSymbol("\t"); cg2.increaseIndentation(); cg2.write("abc"); CHECK(stream2.str() == "\tabc"); } 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(stubgens.empty() == true); CHECK(procedures.empty() == true); } 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(stubgens.empty() == true); CHECK(procedures.empty() == true); } 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(stubgens.empty() == true); CHECK(procedures.empty() == true); vector stubgens2; vector procedures2; const char* argv2[2] = {"jsonrpcstub","--cpxp-client=TestClient"}; 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"}; CHECK(StubGeneratorFactory::createStubGenerators(3, (char**)argv3, procedures3, stubgens3, stdout, stderr) == false); CHECK(stubgens3.empty() == true); CHECK(procedures3.empty() == true); } 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"}; CHECK(StubGeneratorFactory::createStubGenerators(5, (char**)argv, procedures, stubgens, stdout, stderr) == true); CHECK(stubgens.size() == 3); CHECK(procedures.size() == 7); StubGeneratorFactory::deleteStubGenerators(stubgens); } TEST_CASE_METHOD(F, "test_stubgen_factory_fileoverride", TEST_MODULE) { vector stubgens; vector procedures; const char* argv[9] = {"jsonrpcstub", "testspec6.json", "--js-client=TestClient", "--cpp-client=TestClient", "--cpp-server=TestServer", "--cpp-client-file=client.h", "--cpp-server-file=server.h", "--js-client-file=client.js", "-v"}; CHECK(StubGeneratorFactory::createStubGenerators(9, (char**)argv, procedures, stubgens, stdout, stderr) == true); CHECK(stubgens.size() == 3); CHECK(procedures.size() == 7); StubGeneratorFactory::deleteStubGenerators(stubgens); } #endif libjson-rpc-cpp-0.7.0/src/test/testhttpserver.cpp000066400000000000000000000046271275256467400221330ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file testhttpserver.cpp * @date 11/16/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "testhttpserver.h" 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); return (this->daemon != NULL); } bool TestHttpServer::StopListening() { MHD_stop_daemon(this->daemon); return true; } bool TestHttpServer::SendResponse(const std::string &response, void *addInfo) { (void)response; (void)addInfo; return true; } 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()) return this->headers[key]; return ""; } int 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; (void)method; (void)version; TestHttpServer* _this = static_cast(cls); if (*con_cls == NULL) { *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_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); MHD_destroy_response(result); } return MHD_YES; } int 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; return MHD_YES; } libjson-rpc-cpp-0.7.0/src/test/testhttpserver.h000066400000000000000000000030561275256467400215730ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file testhttpserver.h * @date 11/16/2014 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_TESTHTTPSERVER_H #define JSONRPC_TESTHTTPSERVER_H #include #include #include namespace jsonrpc { class TestHttpServer : public AbstractServerConnector { public: TestHttpServer(int port); virtual bool StartListening(); virtual bool StopListening(); bool virtual SendResponse(const std::string& response, void* addInfo = NULL); void SetResponse(const std::string &response); std::string GetHeader(const std::string &key); private: int port; MHD_Daemon* daemon; std::map headers; std::string response; static int 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 int header_iterator (void *cls, enum MHD_ValueKind kind, const char *key, const char *value); }; } // namespace jsonrpc #endif // JSONRPC_TESTHTTPSERVER_H libjson-rpc-cpp-0.7.0/src/test/testserver.cpp000066400000000000000000000062001275256467400212200ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file testserver.cpp * @date 08.03.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #include "testserver.h" #include 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); 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::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::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)request; (void)response; Json::Value data; data.append(33); throw JsonRpcException(-32099, "User exception", data); } void TestServer::initCounter(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; cnt = 0; } int TestServer::getCnt() { return cnt; } 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) { return AbstractServer::bindAndAddNotification(proc, pointer); } libjson-rpc-cpp-0.7.0/src/test/testserver.h000066400000000000000000000031651275256467400206740ustar00rootroot00000000000000/************************************************************************* * libjson-rpc-cpp ************************************************************************* * @file testserver.h * @date 08.03.2013 * @author Peter Spiess-Knafl * @license See attached LICENSE.txt ************************************************************************/ #ifndef JSONRPC_CPP_SERVER_H #define JSONRPC_CPP_SERVER_H #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); private: int cnt; }; } #endif // JSONRPC_CPP_SERVER_H libjson-rpc-cpp-0.7.0/src/test/testspec1.json000066400000000000000000000000111275256467400211060ustar00rootroot00000000000000{[..w334 libjson-rpc-cpp-0.7.0/src/test/testspec2.json000066400000000000000000000001541275256467400211170ustar00rootroot00000000000000[ { "params": { "name": "Peter" }, "returns": "Hello Peter" } ] libjson-rpc-cpp-0.7.0/src/test/testspec3.json000066400000000000000000000001361275256467400211200ustar00rootroot00000000000000[ [ "foo", { "name": "Peter" }, "Hello Peter" ] ] libjson-rpc-cpp-0.7.0/src/test/testspec4.json000066400000000000000000000002001275256467400211110ustar00rootroot00000000000000[ { "name": "", "params": { "name": "Peter" }, "returns": "Hello Peter" } ] libjson-rpc-cpp-0.7.0/src/test/testspec5.json000066400000000000000000000007031275256467400211220ustar00rootroot00000000000000[ { "method": "testmethod", "params": {"name": "myname"}, "returns": "somestring" }, { "notification": "testnotification", "params": {"name": "myname"} }, { "name": "testmethod2", "params": {"values": [1,2,3], "object": {"a": "b"}}, "returns": 33.2 }, { "name": "testnotification2", "params": {"values": [1,2,3], "object": {"a": "b"}} } ] libjson-rpc-cpp-0.7.0/src/test/testspec6.json000066400000000000000000000013221275256467400211210ustar00rootroot00000000000000[ { "method": "test.method", "params": {"name": "myname"}, "returns": "somestring" }, { "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": [] } ]