1/*************************************************************************
2 * libjson-rpc-cpp
3 *************************************************************************
4 * @file client.cpp
5 * @date 03.01.2013
6 * @author Peter Spiess-Knafl <dev@spiessknafl.at>
7 * @license See attached LICENSE.txt
8 ************************************************************************/
9
10#include "client.h"
11#include "rpcprotocolclient.h"
12#include <sstream>
13
14using namespace jsonrpc;
15using namespace std;
16
17Client::Client(IClientConnector &connector, clientVersion_t version, bool omitEndingLineFeed) : connector(connector) {
18 this->protocol = new RpcProtocolClient(version, omitEndingLineFeed);
19}
20
21Client::~Client() { delete this->protocol; }
22
23void Client::CallMethod(const std::string &name, const Json::Value &parameter, Json::Value &result) {
24 std::string request, response;
25 protocol->BuildRequest(name, parameter, request, false);
26 connector.SendRPCMessage(request, response);
27 protocol->HandleResponse(response, result);
28}
29
30void Client::CallProcedures(const BatchCall &calls, BatchResponse &result) {
31 std::string request, response;
32 request = calls.toString();
33 connector.SendRPCMessage(request, response);
34 Json::Value tmpresult;
35
36 try {
37 istringstream(response) >> tmpresult;
38 if(!tmpresult.isArray()) {
39 throw JsonRpcException(Errors::ERROR_CLIENT_INVALID_RESPONSE, "Array expected.");
40 }
41 } catch (const Json::Exception &e) {
42 throw JsonRpcException(Errors::ERROR_RPC_JSON_PARSE_ERROR, Errors::GetErrorMessage(Errors::ERROR_RPC_JSON_PARSE_ERROR), response);
43 }
44
45 for (unsigned int i = 0; i < tmpresult.size(); i++) {
46 if (tmpresult[i].isObject()) {
47 Json::Value singleResult;
48 try {
49 Json::Value id = this->protocol->HandleResponse(tmpresult[i], singleResult);
50 result.addResponse(id, singleResult, false);
51 } catch (JsonRpcException &ex) {
52 Json::Value id = -1;
53 if (tmpresult[i].isMember("id"))
54 id = tmpresult[i]["id"];
55 result.addResponse(id, tmpresult[i]["error"], true);
56 }
57 } else
58 throw JsonRpcException(Errors::ERROR_CLIENT_INVALID_RESPONSE, "Object in Array expected.");
59 }
60}
61
62BatchResponse Client::CallProcedures(const BatchCall &calls) {
63 BatchResponse result;
64 this->CallProcedures(calls, result);
65 return result;
66}
67
68Json::Value Client::CallMethod(const std::string &name, const Json::Value &parameter) {
69 Json::Value result;
70 this->CallMethod(name, parameter, result);
71 return result;
72}
73
74void Client::CallNotification(const std::string &name, const Json::Value &parameter) {
75 std::string request, response;
76 protocol->BuildRequest(name, parameter, request, true);
77 connector.SendRPCMessage(request, response);
78}
79