void Roster::update(const json::Value& data, bool whiny) { if (data.isObject() && data.isMember("id") && data.isMember("user") && data.isMember("name") //&& //data.isMember("type") ) { TraceS(this) << "Updating: " << json::stringify(data, true) << endl; std::string id = data["id"].asString(); Peer* peer = get(id, false); if (!peer) { peer = new Peer(data); add(id, peer); } else static_cast<json::Value&>(*peer) = data; } else if (data.isArray()) { for (auto it = data.begin(); it != data.end(); it++) { update(*it, whiny); } } else { std::string error("Bad presence data: " + json::stringify(data)); ErrorS(this) << error << endl; if (whiny) throw std::runtime_error(error); } }
// Create the animation object from json Animation::Animation(const Json::Value& value) : length(-numeric_limits<float>::infinity()) { // We first need to validate that this a Json object if(!value.isObject()) { throw std::runtime_error("Animation::Animation(const Json::Value& value) - value must be a object"); } // Store the name of the animation id = value["id"].asString(); // We need to iterate through the bones array const Json::Value& bones = value["bones"]; // Process the bones for(Json::Value::const_iterator bIt = bones.begin(); bIt != bones.end(); bIt++) { // Get the name of the bone we are exploring std::string boneName = (*bIt)["boneId"].asString(); // Create a vector for the keyframe std::vector<Keyframe *> keyframes; // Iterate through the keyframes const Json::Value& serializedKeyframes = (*bIt)["keyframes"]; // Process the keyframes for(Json::Value::const_iterator kIt = serializedKeyframes.begin(); kIt != serializedKeyframes.end(); kIt++) { // Allocate a keyframe object from the serialized keyframe Keyframe *keyframe = new Keyframe(*kIt); // Store this keyframe in the vector keyframes.push_back(keyframe); } // Decide the length of the animation length = keyframes[keyframes.size() - 1]->keytime - keyframes[0]->keytime; // Store this bone boneKeyframes[boneName] = keyframes; } }
TEST_F(GetPortVlansIdTest, PositiveExecute) { network::json::GetPortVlansId command_json; GetPortVlansId* command = new GetPortVlansId(TEST_UUID, TEST_PORT_ID); EXPECT_NO_THROW(command_json.set_command(command)); Json::Value params; Json::Value result; params[COMPONENT] = TEST_UUID; params[PORT_IDENTIFIER] = TEST_PORT_ID; EXPECT_NO_THROW(command_json.method(params, result)); ASSERT_TRUE(result.isObject()); for (std::uint32_t i = 0; i < 10; ++i) { ASSERT_EQ(result[VLAN_IDENTIFIERS][i][ID].asString(), std::to_string(i)); } }
bool Settings::fromJson(const Json::Value &json) { if (!json.isObject()) return false; m_json = json; for (const auto & key: json.getMemberNames()) { if (json[key].isObject()) { //setJson(key, json[key]); // save type info auto s = new Settings; s->fromJson(json[key]); setGroup(key, s); } else if (json[key].isArray()) { //setJson(key, json[key]); } else { set(key, json[key].asString()); m_json.removeMember(key); // todo: remove } } return true; }
bool Talk::ParseAudioMessageAttach(const IMMessage& msg, IMAudio& audio) { if (msg.type_ != kNIMMessageTypeAudio) return false; Json::Value values; Json::Reader reader; if (reader.parse(msg.attach_, values) && values.isObject()) { audio.display_name_ = values[kNIMAudioMsgKeyDisplayName].asString(); audio.file_extension_ = values[kNIMAudioMsgKeyExt].asString(); audio.md5_ = values[kNIMAudioMsgKeyMd5].asString(); audio.size_ = values[kNIMAudioMsgKeySize].asUInt64(); audio.url_ = values[kNIMAudioMsgKeyUrl].asString(); audio.duration_ = values[kNIMAudioMsgKeyDuration].asUInt(); return true; } return false; }
static void CallbackLogin(const char* json_res, const void *callback) { if (callback != nullptr) { LoginRes res; Json::Value values; Json::Reader reader; if (reader.parse(PCharToString(json_res), values) && values.isObject()) { res.res_code_ = (NIMResCode)values[kNIMResCode].asInt(); res.login_step_ = (NIMLoginStep)values[kNIMLoginStep].asUInt(); res.relogin_ = values[kNIMRelogin].asBool(); res.retrying_ = values[kNIMRetrying].asBool(); ParseOtherClientsPres(values[kNIMOtherClientsPres], res.other_clients_); } Client::LoginCallback *cb = (Client::LoginCallback *)callback; (*cb)(res); } }
Json::Value JsonRpcPrivate::handleObject(Json::Value const & jsonObject) { Json::Value response; if (!jsonObject.isObject()) { Json::Value const null; response = invalidRequest(null); } else { Json::Value const id(jsonObject["id"]); //TODO: handle special responses (e.g. parse errors) if (isRequest(jsonObject)) { response = handleRequest(jsonObject, id); } else if (isResponse(jsonObject)) { Json::Value const null; response = null; handleResponse(jsonObject, id); } else { response = invalidRequest(id); } } return response; }
bool ParseFriendsProfile(const std::string& friends_profile_json, std::list<FriendProfile>& profiles) { Json::Value values; Json::Reader reader; if (reader.parse(friends_profile_json, values) && values.isObject() && values[kNIMFriendKey].isArray()) { Json::Value friends = values[kNIMFriendKey]; int len = friends.size(); for (int i = 0; i < len; i++) { FriendProfile profile; ParseFriendProfile(friends[i], profile); profiles.push_back(profile); } return true; } return false; }
CString CPeraPDWeb::getClientSubFlowId( void ) { ZTools::WriteZToolsFormatLog("CPeraPDWeb::getClientSubFlowId begin >>>>> %s" , "\r\n" ); CWebMethodParamData * pParam = NULL; CWebMethodData wmd; // wmd.m_sMethodName = "getClientSubFlowId"; // if ( !InvokeJsMethod( &wmd ) ) { ZTools::WriteZToolsFormatLog("调用 js 方法 getClientSubFlowId 失败 %s" , "\r\n" ); return ""; } ZTools::WriteZToolsFormatLog("调用 js 方法 getClientSubFlowId 返回 %s\r\n" , wmd.m_sResult ); Json::Reader reader; Json::Value obj; try { if (!reader.parse((char*)(LPCTSTR) wmd.m_sResult, obj, false)) return ""; if (!obj.isObject()) return ""; CString sFlowId = ( obj["flowId"].isString() ) ? obj["flowId"].asCString() : _T(""); CString sOptMsg = ( obj["optMsg "].isString() ) ? obj["optMsg "].asCString() : _T(""); if ( !sOptMsg.IsEmpty() || sFlowId.IsEmpty() ) return ""; return sFlowId; } catch (...) { return ""; } ZTools::WriteZToolsFormatLog("CPeraPDWeb::getClientSubFlowId end <<<<<< %s" , "\r\n" ); return ""; }
CString CallKeepTicket(CString sTicket) { CString sReturn; CString sTicketValue; int nPos = sTicket.Find('='); if (nPos == -1) { return sReturn; } else { sTicketValue = sTicket.Right(sTicket.GetLength() - sTicket.Find('=') - 1); } CString sResult = KeepTicket(sTicketValue); Json::Value jRoot; Json::Reader reader; if (!reader.parse((LPCTSTR)sResult, jRoot)) { return sReturn; } if (!jRoot.isObject()) return sReturn; CString sMsg; CString sTime; sMsg = ( jRoot["result"].isString() ) ? jRoot["result"].asCString() : _T(""); sTime = ( jRoot["maxInactiveInterval"].isString() ) ? jRoot["maxInactiveInterval"].asCString() : _T(""); int nTime = atoi(sTime); if (nTime > 0) { nTime *= 40000; } if (nTime > 0) { s_nNextCallTime = nTime; } sReturn = sMsg; return sReturn; }
static void CreateDicom(RestApiPostCall& call) { // curl http://localhost:8042/tools/create-dicom -X POST -d '{"PatientName":"Hello^World"}' // curl http://localhost:8042/tools/create-dicom -X POST -d '{"PatientName":"Hello^World","PixelData":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAAAAAA6mKC9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gUGDDcB53FulQAAAElJREFUGNNtj0sSAEEEQ1+U+185s1CtmRkblQ9CZldsKHJDk6DLGLJa6chjh0ooQmpjXMM86zPwydGEj6Ed/UGykkEM8X+p3u8/8LcOJIWLGeMAAAAASUVORK5CYII="}' Json::Value replacements; if (call.ParseJsonRequest(replacements) && replacements.isObject()) { ParsedDicomFile dicom; Json::Value::Members members = replacements.getMemberNames(); for (size_t i = 0; i < members.size(); i++) { const std::string& name = members[i]; std::string value = replacements[name].asString(); DicomTag tag = FromDcmtkBridge::ParseTag(name); if (tag == DICOM_TAG_PIXEL_DATA) { dicom.EmbedImage(value); } else { dicom.Replace(tag, value); } } DicomInstanceToStore toStore; toStore.SetParsedDicomFile(dicom); std::string id; StoreStatus status = OrthancRestApi::GetContext(call).Store(id, toStore); if (status == StoreStatus_Failure) { LOG(ERROR) << "Error while storing a manually-created instance"; return; } OrthancRestApi::GetApi(call).AnswerStoredInstance(call, id, status); } }
void RequestAdvertController::WomanListAdvertCallbackHandle(long requestId, const string& url, bool requestRet, const char* buf, int size) { AdWomanListAdvertItem item; string errnum = ""; string errmsg = ""; bool bFlag = false; if (requestRet) { // request success Json::Value dataJson; if( HandleResult(buf, size, errnum, errmsg, &dataJson) ) { if (dataJson.isObject()) { bFlag = item.Parsing(dataJson); } if (!bFlag) { // parsing fail errnum = LOCAL_ERROR_CODE_PARSEFAIL; errmsg = LOCAL_ERROR_CODE_PARSEFAIL_DESC; FileLog("httprequest", "RequestAdvertController::WomanListAdvertCallbackHandle() parsing fail:" "(url:%s, size:%d, buf:%s)", url.c_str(), size, buf); } } } else { // request fail errnum = LOCAL_ERROR_CODE_TIMEOUT; errmsg = LOCAL_ERROR_CODE_TIMEOUT_DESC; } if( m_Callback.onRequestAdWomanListAdvert != NULL ) { // item.advertId = "advertId"; // item.image = "image"; // item.height = 15; // item.width = 12; // item.adurl = "adurl"; // item.openType = AD_OT_SYSTEMBROWER; m_Callback.onRequestAdWomanListAdvert(requestId, bFlag, errnum, errmsg, item); } }
Message MessagesClient::parseJsonMessage(const Json::Value &json) { if (!json.isObject()) { throw ProtocolError("Malformed JSON document (object expected)"); } Message msg; msg.id = CheckedConverter::toUint32(json["id"]); msg.lastModified = CheckedConverter::toUint64(json["lastModified"]); msg.deleted = CheckedConverter::toBool(json["deleted"]); if (!msg.deleted) { msg.dateReceived = CheckedConverter::toDateTime(json["dateReceived"]); msg.keySafe = CheckedConverter::toVector(json["keySafe"]); msg.content = CheckedConverter::toVector(json["content"]); } msg.meta = CheckedConverter::toVector(json["meta"], AllowEmpty::True); msg.hasAttachments = CheckedConverter::toBool(json["hasAttachments"]); return msg; }
bool OnTBTClientStateMarshaller::fromJSON(const Json::Value& json,OnTBTClientState& c) { try { if(!json.isObject()) return false; if(!json.isMember("state")) return false; { const Json::Value& j=json["state"]; if(!TBTStateMarshaller::fromJSON(j,c.state)) return false; } } catch(...) { return false; } return checkIntegrity(c); }
bool ParseSysMessages(const std::string& sysmsgs_json, std::list<SysMessage>& msgs, int* unread) { Json::Value values; Json::Reader reader; if (reader.parse(sysmsgs_json, values) && values.isObject()) { *unread = values[kNIMSysMsglogQueryKeyUnreadCount].asUInt(); Json::Value content = values[kNIMSysMsglogQueryKeyContent]; int len = content.size(); for (int i = 0; i < len; i++) { SysMessage msg; ParseSysMessageContent(content[i], msg); msgs.push_back(msg); } return true; } return false; }
bool DialNumber_requestMarshaller::fromJSON(const Json::Value& json,DialNumber_request& c) { try { if(!json.isObject()) return false; if(!json.isMember("number")) return false; { const Json::Value& j=json["number"]; if(!j.isString()) return false; c.number=j.asString(); } } catch(...) { return false; } return checkIntegrity(c); }
static void ParseReplacements(DicomModification& target, const Json::Value& replacements) { if (!replacements.isObject()) { throw OrthancException(ErrorCode_BadRequest); } Json::Value::Members members = replacements.getMemberNames(); for (size_t i = 0; i < members.size(); i++) { const std::string& name = members[i]; std::string value = replacements[name].asString(); DicomTag tag = FromDcmtkBridge::ParseTag(name); target.Replace(tag, value); VLOG(1) << "Replace: " << name << " " << tag << " == " << value << std::endl; } }
bool UnsubscribeButton_requestMarshaller::fromJSON(const Json::Value& json,UnsubscribeButton_request& c) { try { if(!json.isObject()) return false; if(!json.isMember("buttonName")) return false; { const Json::Value& j=json["buttonName"]; if(!ButtonNameMarshaller::fromJSON(j,c.buttonName)) return false; } } catch(...) { return false; } return checkIntegrity(c); }
void MusicConfigLoader::ReadTrackObject(Json::Value& node) { ATLASSERT(node.isObject()); // extract object member ATLASSERT(node.isMember(c_pszaId)); ATLASSERT(node.isMember(c_pszaLen)); ATLASSERT(node.isMember(c_pszaFile)); ATLASSERT(node.isMember(c_pszaTags)); CString cszId = node.get(c_pszaId, Json::Value::null).asCString(); unsigned int uiLen = node.get(c_pszaLen, Json::Value::null).asUInt(); CString cszFile = node.get(c_pszaFile, Json::Value::null).asCString(); Json::Value tags = node.get(c_pszaTags, Json::Value::null); std::set<CString> setTags; ReadTags(tags, setTags); AddMusicTrack(cszId, uiLen, cszFile, setTags); }
static void CallbackGetChatRoomInfo(__int64 room_id, int error_code, const char *result, const char *json_extension, const void *user_data) { if (user_data) { ChatRoom::GetChatRoomInfoCallback *cb = (ChatRoom::GetChatRoomInfoCallback*)user_data; if (*cb) { Json::Value value; Json::Reader reader; if (reader.parse(PCharToString(result), value) && value.isObject()) { ChatRoomInfo info; info.ParseFromJsonValue(value); (*cb)(room_id, error_code, info); return; } (*cb)(room_id, error_code, ChatRoomInfo()); } } }
bool ParseSessionList(const std::string& sessions_json, SessionDataList& session_list) { Json::Value values; Json::Reader reader; if (reader.parse(sessions_json, values) && values.isObject()) { session_list.count_ = values[kNIMSessionListCount].asUInt(); session_list.unread_count_ = values[kNIMSessionListUnreadCount].asUInt(); Json::Value sessions = values[kNIMSessionListContent]; int len = sessions.size(); for (int i = 0; i < len; i++) { SessionData session; ParseSession(sessions[i], session); session_list.sessions_.push_back(session); } return true; } return false; }
bool Talk::ParseImageMessageAttach(const IMMessage& msg, IMImage& image) { if (msg.type_ != kNIMMessageTypeImage) return false; Json::Value values; Json::Reader reader; if (reader.parse(msg.attach_, values) && values.isObject()) { image.display_name_ = values[kNIMImgMsgKeyDisplayName].asString(); image.file_extension_ = values[kNIMImgMsgKeyExt].asString(); image.height_ = values[kNIMImgMsgKeyHeight].asUInt(); image.width_ = values[kNIMImgMsgKeyWidth].asUInt(); image.md5_ = values[kNIMImgMsgKeyMd5].asString(); image.size_ = values[kNIMImgMsgKeySize].asUInt64(); image.url_ = values[kNIMImgMsgKeyUrl].asString(); return true; } return false; }
TEST_F(GetManagerInfoTest, PositiveExecute) { compute::json::GetManagerInfo command_json; GetManagerInfo* command = new GetManagerInfo("TestModuleId"); EXPECT_NO_THROW(command_json.set_command(command)); Json::Value params; Json::Value result; params["component"] = "TestModuleId"; EXPECT_NO_THROW(command_json.method(params, result)); ASSERT_TRUE(result.isObject()); ASSERT_TRUE(result["firmwareVersion"].isString()); ASSERT_TRUE(result["ipv4address"].isString()); ASSERT_TRUE(result["serialConsole"].isObject()); ASSERT_TRUE(result["status"].isObject()); ASSERT_TRUE(result["status"]["state"].isString()); ASSERT_TRUE(result["status"]["health"].isString()); ASSERT_TRUE(result["serialConsole"]["signalType"].isString()); ASSERT_TRUE(result["serialConsole"]["bitrate"].isUInt()); ASSERT_TRUE(result["serialConsole"]["parity"].isString()); ASSERT_TRUE(result["serialConsole"]["dataBits"].isUInt()); ASSERT_TRUE(result["serialConsole"]["stopBits"].isUInt()); ASSERT_TRUE(result["serialConsole"]["flowControl"].isString()); ASSERT_TRUE(result["serialConsole"]["pinOut"].isString()); ASSERT_TRUE(result["serialConsole"]["enabled"].isBool()); ASSERT_EQ(result["firmwareVersion"].asString(), "Test Firmware Version"); ASSERT_EQ(result["ipv4address"].asString(), "127.0.0.1"); ASSERT_EQ(result["status"]["state"].asString(), "Test State"); ASSERT_EQ(result["status"]["health"].asString(), "Test Health"); ASSERT_EQ(result["serialConsole"]["signalType"].asString(), "Test Signal Type"); ASSERT_EQ(result["serialConsole"]["bitrate"].asUInt(), 8); ASSERT_EQ(result["serialConsole"]["parity"].asString(), "Test Parity"); ASSERT_EQ(result["serialConsole"]["dataBits"].asUInt(), 8); ASSERT_EQ(result["serialConsole"]["stopBits"].asUInt(), 8); ASSERT_EQ(result["serialConsole"]["flowControl"].asString(), "Test Flow Control"); ASSERT_EQ(result["serialConsole"]["pinOut"].asString(), "Test Pin Out"); ASSERT_EQ(result["serialConsole"]["enabled"].asBool(), true); }
TEST_F(GetManagerInfoTest, PositiveExecute) { storage::json::GetManagerInfo command_json; GetManagerInfo* command = new GetManagerInfo("TestModuleId"); EXPECT_NO_THROW(command_json.set_command(command)); Json::Value params; Json::Value result; params[COMPONENT] = "TestModuleId"; EXPECT_NO_THROW(command_json.method(params, result)); ASSERT_TRUE(result.isObject()); ASSERT_TRUE(result[FIRMWARE_VERSION].isString()); ASSERT_TRUE(result[IPV4_ADDRESS].isString()); ASSERT_TRUE(result[SERIAL_CONSOLE].isObject()); ASSERT_TRUE(result[STATUS].isObject()); ASSERT_TRUE(result[STATUS][STATE].isString()); ASSERT_TRUE(result[STATUS][HEALTH].isString()); ASSERT_TRUE(result[SERIAL_CONSOLE][TYPE].isString()); ASSERT_TRUE(result[SERIAL_CONSOLE][BITRATE].isUInt()); ASSERT_TRUE(result[SERIAL_CONSOLE][PARITY].isString()); ASSERT_TRUE(result[SERIAL_CONSOLE][DATABITS].isUInt()); ASSERT_TRUE(result[SERIAL_CONSOLE][STOPBITS].isUInt()); ASSERT_TRUE(result[SERIAL_CONSOLE][FLOW_CONTROL].isString()); ASSERT_TRUE(result[SERIAL_CONSOLE][PINOUT].isString()); ASSERT_TRUE(result[SERIAL_CONSOLE][ENABLED].isBool()); ASSERT_EQ(result[FIRMWARE_VERSION].asString(), "Test Firmware Version"); ASSERT_EQ(result[IPV4_ADDRESS].asString(), "127.0.0.1"); ASSERT_EQ(result[STATUS][STATE].asString(), "Test State"); ASSERT_EQ(result[STATUS][HEALTH].asString(), "Test Health"); ASSERT_EQ(result[SERIAL_CONSOLE][TYPE].asString(), "Test Signal Type"); ASSERT_EQ(result[SERIAL_CONSOLE][BITRATE].asUInt(), 8); ASSERT_EQ(result[SERIAL_CONSOLE][PARITY].asString(), "Test Parity"); ASSERT_EQ(result[SERIAL_CONSOLE][DATABITS].asUInt(), 8); ASSERT_EQ(result[SERIAL_CONSOLE][STOPBITS].asUInt(), 8); ASSERT_EQ(result[SERIAL_CONSOLE][FLOW_CONTROL].asString(), "Test Flow Control"); ASSERT_EQ(result[SERIAL_CONSOLE][PINOUT].asString(), "Test Pin Out"); ASSERT_EQ(result[SERIAL_CONSOLE][ENABLED].asBool(), true); }
bool CJsonDataDelteFile::Parse(const char * pszInJs) { Clear(); string strSrc = pszInJs == NULL ? "" : pszInJs; if (strSrc.empty()) return false; Json::Reader reader; Json::Value obj; try { if (!reader.parse(strSrc, obj, false)) return false; if (!obj.isObject()) return false; m_strUserId = obj["UserId"].isString() ? obj["UserId"].asString() : ""; Json::Value & Filelist = obj["FileList"]; if (!Filelist.isArray()) { Clear(); return false; } for (size_t i=0;i<Filelist.size();i++) { CDataDeleteFile DFile; DFile.m_strNetDiskDir = Filelist[i]["Path"].isString() ? Filelist[i]["Path"].asString():""; DFile.m_strItemName = Filelist[i]["Name"].isString() ? Filelist[i]["Name"].asString():""; DFile.m_strType = Filelist[i]["Type"].isString()? Filelist[i]["Type"].asString():""; m_vDelFileList.push_back(DFile); } return true; } catch(...) { Clear(); return false; } return false; }
sk_sp<sksg::Gradient> AttachGradient(const Json::Value& obj, AttachContext* ctx) { SkASSERT(obj.isObject()); const auto& stops = obj["g"]; if (!stops.isObject()) return nullptr; const auto stopCount = ParseDefault(stops["p"], -1); if (stopCount < 0) return nullptr; sk_sp<sksg::Gradient> gradient_node; sk_sp<GradientAdapter> adapter; if (ParseDefault(obj["t"], 1) == 1) { auto linear_node = sksg::LinearGradient::Make(); adapter = sk_make_sp<LinearGradientAdapter>(linear_node, stopCount); gradient_node = std::move(linear_node); } else { auto radial_node = sksg::RadialGradient::Make(); adapter = sk_make_sp<RadialGradientAdapter>(radial_node, stopCount); // TODO: highlight, angle gradient_node = std::move(radial_node); } BindProperty<VectorValue>(stops["k"], &ctx->fAnimators, [adapter](const VectorValue& stops) { adapter->setColorStops(stops); }); BindProperty<VectorValue>(obj["s"], &ctx->fAnimators, [adapter](const VectorValue& s) { adapter->setStartPoint(ValueTraits<VectorValue>::As<SkPoint>(s)); }); BindProperty<VectorValue>(obj["e"], &ctx->fAnimators, [adapter](const VectorValue& e) { adapter->setEndPoint(ValueTraits<VectorValue>::As<SkPoint>(e)); }); return gradient_node; }
void TConfigParser::LoadPort(const Json::Value& port_data, const std::string& id_prefix) { if (!port_data.isObject()) throw TConfigParserException("malformed config"); if (!port_data.isMember("path")) throw TConfigParserException("path not specified"); if (port_data.isMember("enabled") && !port_data["enabled"].asBool()) return; PPortConfig port_config(new TPortConfig); port_config->ConnSettings.Device = port_data["path"].asString(); if (port_data.isMember("baud_rate")) port_config->ConnSettings.BaudRate = GetInt(port_data, "baud_rate"); if (port_data.isMember("parity")) port_config->ConnSettings.Parity = port_data["parity"].asCString()[0]; // FIXME (can be '\0') if (port_data.isMember("data_bits")) port_config->ConnSettings.DataBits = GetInt(port_data, "data_bits"); if (port_data.isMember("stop_bits")) port_config->ConnSettings.StopBits = GetInt(port_data, "stop_bits"); if (port_data.isMember("response_timeout_ms")) port_config->ConnSettings.ResponseTimeout = std::chrono::milliseconds( GetInt(port_data, "response_timeout_ms")); if (port_data.isMember("poll_interval")) port_config->PollInterval = std::chrono::milliseconds( GetInt(port_data, "poll_interval")); const Json::Value array = port_data["devices"]; for(unsigned int index = 0; index < array.size(); ++index) LoadDevice(port_config, array[index], id_prefix + std::to_string(index)); HandlerConfig->AddPortConfig(port_config); }
int UdpHandler::process_packet(const udp_packet* pi) { if(pi->data[0] != '{') return 0 ; Json::Reader reader ; Json::Value request ; if(! reader.parse(pi->data,pi->data + pi->data_size,request,false) ) { return 0 ; } //request : {action,app_name,rule_name,salt} if(!request.isObject()) return send_response(pi->addr,-1,"invalid request") ; if(!request["app_name"].isString()) return send_response(pi->addr,-1,"need app_name") ; if(!request["rule_name"].isString()) return send_response(pi->addr,-1,"need rule_name"); if(!request["action"].isString()) return send_response(pi->addr,-1,"need action"); string action = request["action"].asString() ; string app_name = request["app_name"].asString() ; string rule_name = request["rule_name"].asString() ; string seq = request["seq"].isString() ? request["seq"].asString() : "" ; if(action.compare("get")==0 || action.compare("create")==0) { std::string salt ; if(request["salt"].isString() ) salt = request["salt"].asString(); return process_action_create(rule_name,app_name,seq,salt,pi->addr); } else { return process_action_monitor(rule_name,app_name,seq,pi->addr) ; } }
bool Handler::Check(const Json::Value& root, Json::Value& error) { Json::Value err; /* check the JSON-RPC version => 2.0 */ if(!root.isObject() || !root.isMember("jsonrpc") || root["jsonrpc"] != "2.0") { error["id"] = Json::Value::null; error["jsonrpc"] = "2.0"; err["code"] = INVALID_REQUEST; err["message"] = "Invalid JSON-RPC request."; error["error"] = err; return false; } if(root.isMember("id") && (root["id"].isArray() || root["id"].isObject())) { error["id"] = Json::Value::null; error["jsonrpc"] = "2.0"; err["code"] = INVALID_REQUEST; err["message"] = "Invalid JSON-RPC request."; error["error"] = err; return false; } /* extract "method" attribute */ if(!root.isMember("method") || !root["method"].isString()) { error["id"] = Json::Value::null; error["jsonrpc"] = "2.0"; err["code"] = INVALID_REQUEST; err["message"] = "Invalid JSON-RPC request."; error["error"] = err; return false; } return true; }
void AsyncScriptExecutor::GetElementIdList(const Json::Value& json_object) { LOG(TRACE) << "Entering AsyncScriptExecutor::GetElementIdList"; if (json_object.isArray()) { for (unsigned int i = 0; i < json_object.size(); ++i) { GetElementIdList(json_object[i]); } } else if (json_object.isObject()) { if (json_object.isMember(JSON_ELEMENT_PROPERTY_NAME)) { // Capture the ID of any element in the arg list, and std::string element_id; element_id = json_object[JSON_ELEMENT_PROPERTY_NAME].asString(); this->element_id_list_.push_back(element_id); } else { std::vector<std::string> property_names = json_object.getMemberNames(); std::vector<std::string>::const_iterator it = property_names.begin(); for (; it < property_names.end(); ++it) { GetElementIdList(json_object[*it]); } } } }