void SessionMethodValue::setXmlValutRts2 (rts2core::Connection *conn, std::string valueName, XmlRpcValue &x_val) { int i_val; double d_val; std::string s_val; rts2core::Value *val = conn->getValue (valueName.c_str ()); if (!val) { throw XmlRpcException ("Cannot find value '" + std::string (valueName) + "' on device '" + std::string (conn->getName ()) + "'."); } switch (val->getValueBaseType ()) { case RTS2_VALUE_INTEGER: case RTS2_VALUE_LONGINT: if (x_val.getType () == XmlRpcValue::TypeInt) { i_val = (int) (x_val); } else { s_val = (std::string) (x_val); i_val = atoi (s_val.c_str ()); } conn->queCommand (new rts2core::CommandChangeValue (conn->getOtherDevClient (), valueName, '=', i_val)); break; case RTS2_VALUE_DOUBLE: if (x_val.getType () == XmlRpcValue::TypeDouble) { d_val = (double) (x_val); } else { s_val = (std::string) (x_val); d_val = atof (s_val.c_str ()); } conn->queCommand (new rts2core::CommandChangeValue (conn->getOtherDevClient (), valueName, '=', d_val)); break; case RTS2_VALUE_FLOAT: if (x_val.getType () == XmlRpcValue::TypeDouble) { d_val = (double) (x_val); } else { s_val = (std::string) (x_val); d_val = atof (s_val.c_str ()); } conn->queCommand (new rts2core::CommandChangeValue (conn->getOtherDevClient (), valueName, '=', (float) d_val)); break; case RTS2_VALUE_STRING: conn->queCommand (new rts2core::CommandChangeValue (conn->getOtherDevClient (), valueName, '=', (std::string) (x_val))); break; default: conn->queCommand (new rts2core::CommandChangeValue (conn->getOtherDevClient (), valueName, '=', (std::string) (x_val), true)); break; } }
// Encode the request to call the specified method with the specified parameters into xml bool XmlRpcCurlClient::generateRequest(const char* methodName, XmlRpcValue const& params) { std::string body = REQUEST_BEGIN; body += methodName; body += REQUEST_END_METHODNAME; // If params is an array, each element is a separate parameter if (params.valid()) { body += PARAMS_TAG; if (params.getType() == XmlRpcValue::TypeArray) { for (int i=0; i<params.size(); ++i) { body += PARAM_TAG; body += params[i].toXml(); body += PARAM_ETAG; } } else { body += PARAM_TAG; body += params.toXml(); body += PARAM_ETAG; } body += PARAMS_ETAG; } body += REQUEST_END; _request = body; return true; }
void testArray(XmlRpcValue const& d) { // Array XmlRpcValue a; a.setSize(4); a[0] = 1; a[1] = std::string("two"); a[2] = 43.7; a[3] = "four"; assert(int(a[0]) == 1); assert(a[2] == d); char csaXml[] = "<value><array>\n" " <data>\n" " <value><i4>1</i4></value> \n" " <value> <string>two</string></value>\n" " <value><double>43.7</double></value>\n" " <value>four</value>\n" " </data>\n" "</array></value>"; int offset = 0; XmlRpcValue aXml(csaXml, &offset); assert(a == aXml); }
// Convert the response xml into a result value bool XmlRpcClient::parseResponse(XmlRpcValue& result) { // Parse response xml into result int offset = 0; if ( ! XmlRpcUtil::findTag(METHODRESPONSE_TAG,_response,&offset)) { XmlRpcUtil::error("Error in XmlRpcClient::parseResponse: Invalid response - no methodResponse. Response:\n%s", _response.c_str()); return false; } // Expect either <params><param>... or <fault>... if ((XmlRpcUtil::nextTagIs(PARAMS_TAG,_response,&offset) && XmlRpcUtil::nextTagIs(PARAM_TAG,_response,&offset)) || XmlRpcUtil::nextTagIs(FAULT_TAG,_response,&offset) && (_isFault = true)) { if ( ! result.fromXml(_response, &offset)) { XmlRpcUtil::error("Error in XmlRpcClient::parseResponse: Invalid response value. Response:\n%s", _response.c_str()); _response = ""; return false; } } else { XmlRpcUtil::error("Error in XmlRpcClient::parseResponse: Invalid response - no param or fault tag. Response:\n%s", _response.c_str()); _response = ""; return false; } _response = ""; return result.valid(); }
const DataType& XmlRpcFunction::parameterType (size_t synopsis_index, size_t parameter_index) { XmlRpcValue func_synop = mSynopsis.arrayGetItem(synopsis_index); XmlRpcValue param = func_synop.arrayGetItem(parameter_index + 1); return findDataType(param.getString()); }
// Encode the request to call the specified method with the specified parameters into xml bool XmlRpcClient::generateRequest(const char* methodName, XmlRpcValue const& params) { std::string body = REQUEST_BEGIN; body += methodName; body += REQUEST_END_METHODNAME; // If params is an array, each element is a separate parameter if (params.valid()) { body += PARAMS_TAG; if (params.getType() == XmlRpcValue::TypeArray) { for (int i=0; i<params.size(); ++i) { body += PARAM_TAG; body += params[i].toXml(); body += PARAM_ETAG; } } else { body += PARAM_TAG; body += params.toXml(); body += PARAM_ETAG; } body += PARAMS_ETAG; } body += REQUEST_END; std::string header = generateHeader(body); XmlRpcUtil::log(4, "XmlRpcClient::generateRequest: header is %d bytes, content-length is %d.", header.length(), body.length()); _request = header + body; return true; }
static void AdvancedTest() { XmlRpcValue args, result; // Passing datums: args[0] = "a string"; args[1] = 1; args[2] = true; args[3] = 3.14159; struct tm timeNow; args[4] = XmlRpcValue(&timeNow); // Passing an array: XmlRpcValue array; array[0] = 4; array[1] = 5; array[2] = 6; args[5] = array; // Note: if there's a chance that the array contains zero elements, // you'll need to call: // array.initAsArray(); // ...because otherwise the type will never get set to "TypeArray" and // the value will be a "TypeInvalid". // Passing a struct: XmlRpcValue record; record["SOURCE"] = "a"; record["DESTINATION"] = "b"; record["LENGTH"] = 5; args[6] = record; // We don't support zero-size struct's...Surely no-one needs these? // Make the call: XmlRpcClient Connection("https://61.95.191.232:9600/arumate/rpc/xmlRpcServer.php"); Connection.setIgnoreCertificateAuthority(); if (! Connection.execute("arumate.getMegawatts", args, result)) { std::cout << Connection.getError(); return; } // Pull the data out: if (result.getType() != XmlRpcValue::TypeStruct) { std::cout << "I was expecting a struct."; return; } int i = result["n"]; std::string s = result["name"]; array = result["A"]; for (int i=0; i < array.size(); i++) std::cout << (int)array[i] << "\n"; record = result["subStruct"]; std::cout << (std::string)record["foo"] << "\n"; }
void XMLRPC2DIServer::xmlrpcval2amarg(XmlRpcValue& v, AmArg& a, unsigned int start_index) { if (v.valid()) { for (int i=start_index; i<v.size();i++) { switch (v[i].getType()) { case XmlRpcValue::TypeInt: { a.push(AmArg((int)v[i])); } break; case XmlRpcValue::TypeDouble:{ a.push(AmArg((double)v[i])); } break; case XmlRpcValue::TypeString:{ a.push(AmArg(((string)v[i]).c_str())); } break; // TODO: support more types (datetime, struct, ...) default: throw XmlRpcException("unsupported parameter type", 400); }; } } }
// Array bool XmlRpcValue::arrayFromXml(std::string const& valueXml, int* offset) { if ( ! XmlRpcUtil::nextTagIs(DATA_TAG, valueXml, offset)) return false; _type = TypeArray; _value.asArray = new ValueArray; XmlRpcValue v; while (v.fromXml(valueXml, offset)) _value.asArray->push_back(v); // copy... // Skip the trailing </data> (void) XmlRpcUtil::nextTagIs(DATA_ETAG, valueXml, offset); return true; }
// Execute multiple calls and return the results in an array. bool XmlRpcServerConnection::executeMulticall(const std::string& in_methodName, XmlRpcValue& params, XmlRpcValue& result) { if (in_methodName != SYSTEM_MULTICALL) return false; // There ought to be 1 parameter, an array of structs if (params.size() != 1 || params[0].getType() != XmlRpcValue::TypeArray) throw XmlRpcException(SYSTEM_MULTICALL + ": Invalid argument (expected an array)"); int nc = params[0].size(); result.setSize(nc); for (int i=0; i<nc; ++i) { if ( ! params[0][i].hasMember(METHODNAME) || ! params[0][i].hasMember(PARAMS)) { result[i][FAULTCODE] = -1; result[i][FAULTSTRING] = SYSTEM_MULTICALL + ": Invalid argument (expected a struct with members methodName and params)"; continue; } const std::string& methodName = params[0][i][METHODNAME]; XmlRpcValue& methodParams = params[0][i][PARAMS]; XmlRpcValue resultValue; resultValue.setSize(1); try { if ( ! executeMethod(methodName, methodParams, resultValue[0]) && ! executeMulticall(methodName, params, resultValue[0])) { result[i][FAULTCODE] = -1; result[i][FAULTSTRING] = methodName + ": unknown method name"; } else result[i] = resultValue; } catch (const XmlRpcException& fault) { result[i][FAULTCODE] = fault.getCode(); result[i][FAULTSTRING] = fault.getMessage(); } } return true; }
void RecordsValues::sessionExecute (XmlRpcValue& params, XmlRpcValue& result) { if (params.getType () != XmlRpcValue::TypeInvalid) throw XmlRpcException ("Invalid number of parameters"); try { rts2db::RecvalsSet recvals = rts2db::RecvalsSet (); int i = 0; time_t t; recvals.load (); for (rts2db::RecvalsSet::iterator iter = recvals.begin (); iter != recvals.end (); iter++) { rts2db::Recval rv = iter->second; XmlRpcValue res; res["id"] = rv.getId (); res["device"] = rv.getDevice (); res["value_name"] = rv.getValueName (); res["value_type"] = rv.getType (); t = rv.getFrom (); res["from"] = XmlRpcValue (gmtime (&t)); t = rv.getTo (); res["to"] = XmlRpcValue (gmtime (&t)); result[i++] = res; } } catch (rts2db::SqlError err) { throw XmlRpcException (err.what ()); } }
void TargetAltitude::sessionExecute (XmlRpcValue& params, XmlRpcValue& result) { if (params.size () != 4) throw XmlRpcException ("Invalid number of parameters"); if (((int) params[0]) < 0) throw XmlRpcException ("Target id < 0"); rts2db::Target *tar = createTarget ((int) params[0], Configuration::instance ()->getObserver (), Configuration::instance ()->getObservatoryAltitude ()); if (tar == NULL) { throw XmlRpcException ("Cannot create target"); } time_t tfrom = (int)params[1]; double jd_from = ln_get_julian_from_timet (&tfrom); time_t tto = (int)params[2]; double jd_to = ln_get_julian_from_timet (&tto); double stepsize = ((double)params[3]) / 86400; // test for insane request if ((jd_to - jd_from) / stepsize > 10000) { throw XmlRpcException ("Too many points"); } int i; double j; for (i = 0, j = jd_from; j < jd_to; i++, j += stepsize) { result[i][0] = j; ln_hrz_posn hrz; tar->getAltAz (&hrz, j); result[i][1] = hrz.alt; } }
void MasterStateIs::sessionExecute (XmlRpcValue& params, XmlRpcValue& result) { int ms = ((HttpD *) getMasterApp ())->getMasterStateFull (); if (params.size () == 1) { if (params[0] == "on") { result = !(ms & SERVERD_ONOFF_MASK); } else if (params[0] == "standby") { result = (ms & SERVERD_ONOFF_MASK) == SERVERD_STANDBY; } else if (params[0] == "off") { result = (ms & SERVERD_ONOFF_MASK) == SERVERD_HARD_OFF || (ms & SERVERD_ONOFF_MASK) == SERVERD_SOFT_OFF; } else if (params[0] == "rnight") { result = (ms & SERVERD_STATUS_MASK) == SERVERD_NIGHT && !(ms & SERVERD_ONOFF_MASK); } else { throw XmlRpcException ("Invalid status name parameter"); } } else { throw XmlRpcException ("Invalid number of parameters"); } }
void UserLogin::execute (struct sockaddr_in *saddr, XmlRpcValue& params, XmlRpcValue& result) { if (params.size() != 2) throw XmlRpcException ("Invalid number of parameters"); result = verifyUser (params[0], params[1]); }
void RecordsAverage::sessionExecute (XmlRpcValue& params, XmlRpcValue& result) { if (params.size () != 3) throw XmlRpcException ("Invalid number of parameters"); try { rts2db::RecordAvgSet recset = rts2db::RecordAvgSet (params[0], rts2db::HOUR); int i = 0; time_t t; recset.load (params[1], params[2]); for (rts2db::RecordAvgSet::iterator iter = recset.begin (); iter != recset.end (); iter++) { rts2db::RecordAvg rv = (*iter); XmlRpcValue res; t = rv.getRecTime (); res[0] = XmlRpcValue (gmtime (&t)); res[1] = rv.getAverage (); res[2] = rv.getMinimum (); res[3] = rv.getMaximum (); res[4] = rv.getRecCout (); result[i++] = res; } } catch (rts2db::SqlError err) { throw XmlRpcException (err.what ()); } }
// Execute the named procedure on the remote server. // Params should be an array of the arguments for the method. // Returns true if the request was sent and a result received (although the result // might be a fault). bool XmlRpcClient::execute(const char* method, XmlRpcValue const& params, XmlRpcValue& result) { XmlRpcUtil::log(1, "XmlRpcClient::execute: method %s (_connectionState %d).", method, _connectionState); // This is not a thread-safe operation, if you want to do multithreading, use separate // clients for each thread. If you want to protect yourself from multiple threads // accessing the same client, replace this code with a real mutex. if (_executing) return false; _executing = true; ClearFlagOnExit cf(_executing); _sendAttempts = 0; _isFault = false; if ( ! setupConnection()) return false; if ( ! generateRequest(method, params)) return false; result.clear(); double msTime = -1.0; // Process until exit is called _disp.work(msTime); if (_connectionState != IDLE || ! parseResponse(result)) return false; XmlRpcUtil::log(1, "XmlRpcClient::execute: method %s completed.", method); _response = ""; return true; }
void XmlRpcServerConnection::generateFaultResponse(std::string const& errorMsg, int errorCode) { const char RESPONSE_1[] = "<?xml version=\"1.0\"?>\r\n" "<methodResponse><fault>\r\n\t"; const char RESPONSE_2[] = "\r\n</fault></methodResponse>\r\n"; XmlRpcValue faultStruct; faultStruct[FAULTCODE] = errorCode; faultStruct[FAULTSTRING] = errorMsg; std::string body = RESPONSE_1 + faultStruct.toXml() + RESPONSE_2; std::string header = generateHeader(body); _response = header + body; }
void execute(XmlRpcValue& params, XmlRpcValue& result) { int nArgs = params.size(); int requiredSize; wchar_t wFieldText[129]; bool ShowMsg=false; Log(2,L"RX: %d",nArgs); for (int i=0; i<nArgs; i++) { int y = (int) (params[i]["Row"]); int x = (int) (params[i]["Column"]); std::string& fieldText = params[i]["Field"]; int attribute = params[i]["Attribute"]; requiredSize = mbstowcs(NULL, fieldText.c_str(), 0); // C4996 if (requiredSize>127) requiredSize=127; mbstowcs(wFieldText,fieldText.c_str(),requiredSize+1); //row updated? if (0 != wcsncmp(ScreenContent[y]+x, wFieldText, wcslen(wFieldText))) { wcsncpy(ScreenContent[y]+x, wFieldText, wcslen(wFieldText)); Log(2,L"R:%d C:%d <%s>",y,x,wFieldText); } } DumpScreenContent(); result = "OK"; }
// Convert the response xml into a result value bool XmlRpcClient::parseResponse(XmlRpcValue& result) { std::string r; _response.swap(r); // Parse response xml into result bool emptyParam; int offset = 0; if ( ! XmlRpcUtil::findTag("methodResponse",r,&offset,&emptyParam) || emptyParam) { XmlRpcUtil::error("Error in XmlRpcClient::parseResponse: Invalid response - no methodResponse. Response:\n%s", r.c_str()); return false; } // Expect either <params><param>... or <fault>... if (XmlRpcUtil::nextTagIs("params",r,&offset,&emptyParam) && XmlRpcUtil::nextTagIs("param",r,&offset,&emptyParam)) { if (emptyParam) { result = 0; // No result? } else if ( ! result.fromXml(r, &offset)) { XmlRpcUtil::error("Error in XmlRpcClient::parseResponse: Invalid response value. Response:\n%s", r.c_str()); return false; } } else if (XmlRpcUtil::nextTagIs("fault",r,&offset,&emptyParam)) { _isFault = true; if (emptyParam || ! result.fromXml(r, &offset)) { result = 0; // No result? return false; } } else { XmlRpcUtil::error("Error in XmlRpcClient::parseResponse: Invalid response - no param or fault tag. Response:\n%s", r.c_str()); return false; } return result.valid(); }
bool XMLRPCManager::validateXmlrpcResponse(const std::string& method, XmlRpcValue &response, XmlRpcValue &payload) { if (response.getType() != XmlRpcValue::TypeArray) { ROSCPP_LOG_DEBUG("XML-RPC call [%s] didn't return an array", method.c_str()); return false; } if (response.size() != 2 && response.size() != 3) { ROSCPP_LOG_DEBUG("XML-RPC call [%s] didn't return a 2 or 3-element array", method.c_str()); return false; } if (response[0].getType() != XmlRpcValue::TypeInt) { ROSCPP_LOG_DEBUG("XML-RPC call [%s] didn't return a int as the 1st element", method.c_str()); return false; } int status_code = response[0]; if (response[1].getType() != XmlRpcValue::TypeString) { ROSCPP_LOG_DEBUG("XML-RPC call [%s] didn't return a string as the 2nd element", method.c_str()); return false; } std::string status_string = response[1]; if (status_code != 1) { ROSCPP_LOG_DEBUG("XML-RPC call [%s] returned an error (%d): [%s]", method.c_str(), status_code, status_string.c_str()); return false; } if (response.size() > 2) { payload = response[2]; } else { std::string empty_array = "<value><array><data></data></array></value>"; int offset = 0; payload = XmlRpcValue(empty_array, &offset); } return true; }
void execute(XmlRpcValue& params, XmlRpcValue& result) { int nArgs = params.size(); double sum = 0.0; for (int i=0; i<nArgs; ++i) sum += double(params[i]); result = sum; }
void ListTargetsByType::sessionExecute (XmlRpcValue& params, XmlRpcValue& result) { char target_types[params.size ()+1]; int j; for (j = 0; j < params.size (); j++) target_types[j] = *(((std::string)params[j]).c_str()); target_types[j] = '\0'; rts2db::TargetSet *tar_set = new rts2db::TargetSet (target_types); tar_set->load (); double value; int i = 0; XmlRpcValue retVar; double JD = ln_get_julian_from_sys (); for (rts2db::TargetSet::iterator tar_iter = tar_set->begin(); tar_iter != tar_set->end (); tar_iter++, i++) { rts2db::Target *tar = (*tar_iter).second; retVar["id"] = tar->getTargetID (); retVar["type"] = tar->getTargetType (); if (tar->getTargetName ()) retVar["name"] = tar->getTargetName (); else retVar["name"] = "NULL"; retVar["enabled"] = tar->getTargetEnabled (); if (tar->getTargetComment ()) retVar["comment"] = tar->getTargetComment (); else retVar["comment"] = ""; value = tar->getLastObs(); retVar["last_obs"] = value; struct ln_equ_posn pos; tar->getPosition (&pos, JD); retVar["ra"] = pos.ra; retVar["dec"] = pos.dec; struct ln_hrz_posn hrz; tar->getAltAz (&hrz, JD); retVar["alt"] = hrz.alt; retVar["az"] = hrz.az; result[i++] = retVar; } }
void execute(XmlRpcValue& params, XmlRpcValue& result) { string tmp = params[0]; vector<string> list = chat.Listar(); for(int i = 0; i < list.size(); i++) result[i] = (string)list[i]; cout << "Listando: " << result.size() << endl; }
bool HmValue::TriggerValueGet() { if( _sendingChannel ) { XmlRpcValue value = _channel->GetValue(_valueId); if( value.valid() ) { HandleXmlRpcEvent( value ); return true; }else{ _sendingChannel->MarkAsUndefined(); LOG( Logger::LOG_WARNING, "Error getting value %s.%s", _channel->GetSerial().c_str(), _valueId.c_str()); return false; } }else{ return true; } }
void DeviceType::sessionExecute (XmlRpcValue& params, XmlRpcValue &result) { if (params.size () != 1) throw XmlRpcException ("Single device name expected"); HttpD *serv = (HttpD *) getMasterApp (); rts2core::Connection *conn = serv->getOpenConnection (((std::string)params[0]).c_str()); if (conn == NULL) throw XmlRpcException ("Cannot get device with name " + (std::string)params[0]); result = conn->getOtherType (); }
void DeviceCommand::sessionExecute (XmlRpcValue& params, XmlRpcValue &result) { if (params.size () != 2) throw XmlRpcException ("Device name and command (as single parameter) expected"); HttpD *serv = (HttpD *) getMasterApp (); rts2core::Connection *conn = serv->getOpenConnection (((std::string)params[0]).c_str()); if (conn == NULL) throw XmlRpcException ("Device named " + (std::string)params[0] + " does not exists"); conn->queCommand (new rts2core::Command (serv, ((std::string)params[1]).c_str())); }
void XmlRpcServer::listMethods(XmlRpcValue& result) { int i = 0; result.setSize(_methods.size()+1); for (MethodMap::iterator it=_methods.begin(); it != _methods.end(); ++it) result[i++] = it->first; // Multicall support is built into XmlRpcServer::executeRequest result[i] = MULTICALL; }
inline void XmlRpcClient::call_asynch(std::string method_name, XmlRpcValue param_array, xmlrpc_response_handler callback, void* user_data) { xmlrpc_client_call_asynch_params( mServerUrl.c_str(), method_name.c_str(), callback, user_data, param_array.borrowReference()); }
void XMLRPC2DIServer::xmlrpcval2amarg(XmlRpcValue& v, AmArg& a, unsigned int start_index) { if (v.valid()) { for (int i=start_index; i<v.size();i++) { switch (v[i].getType()) { case XmlRpcValue::TypeInt: { /* DBG("X->A INT\n");*/ a.push(AmArg((int)v[i])); } break; case XmlRpcValue::TypeDouble:{ /* DBG("X->A DBL\n");*/ a.push(AmArg((double)v[i])); } break; case XmlRpcValue::TypeString:{ /* DBG("X->A STR\n");*/ a.push(AmArg(((string)v[i]).c_str())); } break; case XmlRpcValue::TypeArray: { // DBG("X->A ARR\n"); a.push(AmArg()); a[a.size()-1].assertArray(0); AmArg arr; xmlrpcval2amarg(v[i], a[a.size()-1], 0); } break; // TODO: support more types (datetime, struct, ...) default: throw XmlRpcException("unsupported parameter type", 400); }; } } }
inline XmlRpcValue XmlRpcClient::call (std::string method_name, XmlRpcValue param_array) { XmlRpcEnv env; xmlrpc_value *result = xmlrpc_client_call_params(env, mServerUrl.c_str(), method_name.c_str(), param_array.borrowReference()); env.throwIfFaultOccurred(); return XmlRpcValue(result, XmlRpcValue::CONSUME_REFERENCE); }