void Endpoint_v1::TicketRequest::onRequestFinished() { QByteArray respbytes = reply->readAll(); reply->deleteLater(); std::string response ( respbytes.begin(), respbytes.end() ); JSONNode respnode = libJSON::parse ( response ); JSONNode errnode = respnode.at ( "error" ); if (errnode.as_string() != "") { emit failed(QString("server_failure"), QString(errnode.as_string().c_str())); return; } available = FHttpApi::Data_GetTicketDefault; JSONNode subnode = respnode.at ("ticket"); ticket = new Ticket(); ticket->ticket = subnode.as_string().c_str(); ticket->name = _un; ticket->password = _p; subnode = respnode.at("default_character"); defaultCharacter = subnode.as_string().c_str(); subnode = respnode.at("characters"); qslFromJsonArray(subnode, characters); subnode = respnode.at("bookmarks"); qslFromJsonArray(subnode, bookmarks); emit succeeded(); }
void CDropbox::RequestAccountInfo() { MCONTACT hContact = CDropbox::GetDefaultContact(); ptrA token(db_get_sa(NULL, MODULE, "TokenSecret")); GetAccountInfoRequest request(token); NLHR_PTR response(request.Send(hNetlibConnection)); HandleHttpResponseError(response); JSONNode root = JSONNode::parse(response->pData); if (root.empty()) return; JSONNode referral_link = root.at("referral_link"); if (!referral_link.empty()) db_set_s(hContact, MODULE, "Homepage", referral_link.as_string().c_str()); JSONNode display_name = root.at("display_name"); if (!display_name.empty()) { ptrT display_name(mir_utf8decodeT(display_name.as_string().c_str())); TCHAR *sep = _tcsrchr(display_name, _T(' ')); if (sep) { db_set_ts(hContact, MODULE, "LastName", sep + 1); display_name[mir_tstrlen(display_name) - mir_tstrlen(sep)] = '\0'; db_set_ts(hContact, MODULE, "FirstName", display_name); } else { db_set_ts(hContact, MODULE, "FirstName", display_name); db_unset(hContact, MODULE, "LastName"); } } JSONNode country = root.at("country"); if (!country.empty()) { std::string isocode = country.as_string(); if (isocode.empty()) db_unset(hContact, MODULE, "Country"); else { char *country = (char *)CallService(MS_UTILS_GETCOUNTRYBYISOCODE, (WPARAM)isocode.c_str(), 0); db_set_s(hContact, MODULE, "Country", country); } } JSONNode quota_info = root.at("quota_info"); if (!quota_info.empty()) { db_set_dw(hContact, MODULE, "SharedQuota", quota_info.at("shared").as_int()); db_set_dw(hContact, MODULE, "NormalQuota", quota_info.at("normal").as_int()); db_set_dw(hContact, MODULE, "TotalQuota", quota_info.at("quota").as_int()); } }
int main(){ JSONNode n = read_formatted("input.json"); JSONNode n1 = read_formatted("input1.json"); test *tst = new test(); int status; //n.set_name(abi::__cxa_demangle(typeid(*tst).name(), 0,0,&status )); n.push_back(JSONNode("FF::Node_Subclass", abi::__cxa_demangle(typeid(*tst).name(), 0,0,&status ))); if(n1.type()==JSON_NULL){ std::cout<<"null"<<std::endl; } JSONNode n2 (JSON_NODE); n2.set_name("Child1"); n2.push_back(JSONNode("id",1)); n.set_name("Parrent"); n.push_back(n2); JSONNode::iterator it =n.find_nocase("String Node"); if(it->as_string()=="-1"){std::cout<<it->as_int()<<std::endl;} it->as_int()!=-1 ? (std::cout<< "it is"<<std::endl) : (std::cout<<"Mapper Warning: processor id is -1"<<std::endl); if (n.at("String Node")==""){ std::cout<<"ha ha ha"<<std::endl; } std::cout<< "This is the name: "<<n.name()<<std::endl; n.at("String Node")=""; bool x =true; n.push_back(JSONNode("MyBOOLNODE", x)); n["String Node"]=x; //n.erase(n.find_nocase("String Node")); write_formatted(n1, "out1.json"); write_formatted(n, "out.json"); JSONNode::const_iterator i =n.find_nocase("ArrayOfNumbers"); std::string strLowerCase= "ARRAYOfNUMbers"; std::string myTest= "ff::ff_farm<adaptive_loadbalancer, ff::ff_gatherer>"; std::transform(myTest.begin(), myTest.end(), myTest.begin(), ::tolower); std::size_t found = myTest.find("adaptive_loadbalancer"); if (found!=std::string::npos) std::cout << "first 'needle' found at: " << found << '\n'; std::cout<< "here it is: " << myTest<< std::endl; JSONNode n_ar = n.at("ArrayOfNumbers"); std::cout<<"here :"<<n_ar[0].as_int()<< std::endl; // if (0 == strcasecmp("hello", "HELLO")) if(strcasecmp((i->name()).c_str(), strLowerCase.c_str()) == 0) //if(!(n2.empty())) std::cout<<"haha"<<i->size()<<std::endl; std::cout<<i->name()<<std::endl; std::cout<<((i->as_array()).begin()+1)->as_int()<<std::endl; std::cout<<((i->as_array()).at(1)).as_int()<<std::endl; std::cout<<((i->as_array())[1]).as_int()<<std::endl; //std::cout<<i->as_string()<<std::endl; //JSONNode c(JSON_ARRAY); //c=i->as_array(); //JSONNode nk= c.at(0); //JSONNode::const_iterator it = c.begin(); //std::cout <<nk.as_int()<<std::endl; return 0; }
void CDropbox::RequestAccountInfo() { MCONTACT hContact = CDropbox::GetDefaultContact(); ptrA token(db_get_sa(NULL, MODULE, "TokenSecret")); GetAccountInfoRequest request(token); NLHR_PTR response(request.Send(hNetlibConnection)); HandleHttpResponseError(response); JSONNode root = JSONNode::parse(response->pData); if (root.empty()) return; JSONNode referral_link = root.at("referral_link"); if (!referral_link.empty()) db_set_s(hContact, MODULE, "Homepage", referral_link.as_string().c_str()); JSONNode display_name = root.at("display_name"); if (!display_name.empty()) { CMString tszDisplayName(display_name.as_mstring()); int pos = tszDisplayName.ReverseFind(' '); if (pos != -1) { db_set_ts(hContact, MODULE, "LastName", tszDisplayName.Mid(pos+1)); db_set_ts(hContact, MODULE, "FirstName", tszDisplayName.Left(pos)); } else { db_set_ts(hContact, MODULE, "FirstName", tszDisplayName); db_unset(hContact, MODULE, "LastName"); } } JSONNode country = root.at("country"); if (!country.empty()) { std::string isocode = country.as_string(); if (isocode.empty()) db_unset(hContact, MODULE, "Country"); else { char *szCountry = (char *)CallService(MS_UTILS_GETCOUNTRYBYISOCODE, (WPARAM)isocode.c_str(), 0); db_set_s(hContact, MODULE, "Country", szCountry); } } JSONNode quota_info = root.at("quota_info"); if (!quota_info.empty()) { db_set_dw(hContact, MODULE, "SharedQuota", quota_info.at("shared").as_int()); db_set_dw(hContact, MODULE, "NormalQuota", quota_info.at("normal").as_int()); db_set_dw(hContact, MODULE, "TotalQuota", quota_info.at("quota").as_int()); } }
void CDropbox::CommandDelete(void *arg) { CommandParam *param = (CommandParam*)arg; char *path = (char*)param->data; if (path == NULL) { CMStringA error(FORMAT, T2Utf(TranslateT("\"%s\" command has invalid parameter.\nUse \"/help\" for more info.")), "/delete"); ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_SUCCESS, param->hProcess, 0); CallContactService(param->instance->GetDefaultContact(), PSR_MESSAGE, 0, (LPARAM)error.GetBuffer()); return; } ptrA token(db_get_sa(NULL, MODULE, "TokenSecret")); ptrA encodedPath(mir_utf8encode(path)); DeleteRequest request(token, encodedPath); NLHR_PTR response(request.Send(param->instance->hNetlibConnection)); if (response == NULL || response->resultCode != HTTP_STATUS_OK) { ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_FAILED, param->hProcess, 0); return; } JSONNode root = JSONNode::parse(response->pData); if (root.empty()) { ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_FAILED, param->hProcess, 0); return; } bool isDeleted = root.at("is_deleted").as_bool(); CMStringA message(FORMAT, "%s %s", path, !isDeleted ? T2Utf(TranslateT("is not deleted")) : T2Utf(TranslateT("is deleted"))); ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_SUCCESS, param->hProcess, 0); CallContactService(param->instance->GetDefaultContact(), PSR_MESSAGE, 0, (LPARAM)message.GetBuffer()); }
void CDropbox::CommandShare(void *arg) { CommandParam *param = (CommandParam*)arg; char *path = (char*)param->data; if (path == NULL) { CMStringA error(FORMAT, T2Utf(TranslateT("\"%s\" command has invalid parameter.\nUse \"/help\" for more info.")), "/share"); ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_SUCCESS, param->hProcess, 0); CallContactService(param->instance->GetDefaultContact(), PSR_MESSAGE, 0, (LPARAM)error.GetBuffer()); return; } ptrA token(db_get_sa(NULL, MODULE, "TokenSecret")); ptrA encodedPath(mir_utf8encode(path)); bool useShortUrl = db_get_b(NULL, MODULE, "UseSortLinks", 1) > 0; ShareRequest request(token, encodedPath, useShortUrl); NLHR_PTR response(request.Send(param->instance->hNetlibConnection)); if (response == NULL || response->resultCode != HTTP_STATUS_OK) { ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_FAILED, param->hProcess, 0); return; } JSONNode root = JSONNode::parse(response->pData); if (root.empty()) { ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_FAILED, param->hProcess, 0); return; } CMStringA link = root.at("url").as_string().c_str(); ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_SUCCESS, param->hProcess, 0); CallContactService(param->instance->GetDefaultContact(), PSR_MESSAGE, 0, (LPARAM)link.GetBuffer()); }
void CDropbox::CommandContent(void *arg) { CommandParam *param = (CommandParam*)arg; char *path = (char*)param->data; if (path == NULL) path = ""; ptrA token(db_get_sa(NULL, MODULE, "TokenSecret")); ptrA encodedPath(mir_utf8encode(path)); GetMetadataRequest request(token, encodedPath); NLHR_PTR response(request.Send(param->instance->hNetlibConnection)); if (response == NULL || response->resultCode != HTTP_STATUS_OK) { ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_FAILED, param->hProcess, 0); return; } JSONNode root = JSONNode::parse(response->pData); if (root.empty()) { ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_FAILED, param->hProcess, 0); return; } CMStringA message; bool isDir = root.at("is_dir").as_bool(); if (!isDir) message.AppendFormat("\"%s\" %s", encodedPath, T2Utf(TranslateT("is file"))); else { JSONNode content = root.at("contents").as_array(); for (size_t i = 0; i < content.size(); i++) { JSONNode item = content[i]; if (item.empty()) { if (i == 0) message.AppendFormat("\"%s\" %s", encodedPath, T2Utf(TranslateT("is empty"))); break; } CMStringA subName(item.at("path").as_string().c_str()); message.AppendFormat("%s\n", (subName[0] == '/') ? subName.Mid(1) : subName); } } ProtoBroadcastAck(MODULE, param->hContact, ACKTYPE_MESSAGE, ACKRESULT_SUCCESS, param->hProcess, 0); CallContactService(param->instance->GetDefaultContact(), PSR_MESSAGE, 0, (LPARAM)message.GetBuffer()); }
//------------------------------------------------------------------------------ // downloads recent trade data: std::string KClient::trades(const std::string& pair, const std::string& since, std::vector<KTrade>& output) { KInput ki; ki["pair"] = pair; ki["since"] = since; // download and parse data json_string data = libjson::to_json_string( public_method("Trades", ki) ); JSONNode root = libjson::parse(data); // throw an exception if there are errors in the JSON response if (!root.at("error").empty()) { std::ostringstream oss; oss << "Kraken response contains errors: "; // append errors to output string stream for (JSONNode::const_iterator it = root["error"].begin(); it != root["error"].end(); ++it) oss << std::endl << " * " << libjson::to_std_string(it->as_string()); throw std::runtime_error(oss.str()); } // throw an exception if result is empty if (root.at("result").empty()) { throw std::runtime_error("Kraken response doesn't contain result data"); } JSONNode &result = root["result"]; JSONNode &result_pair = result[0]; std::string last = libjson::to_std_string( result.at("last").as_string() ); std::vector<KTrade> buf; for (JSONNode::const_iterator it = result_pair.begin(); it != result_pair.end(); ++it) buf.push_back(KTrade(*it)); output.swap(buf); return last; }
bool USB_device::processMessage(ClientConn& client, string& cmd, JSONNode& n){ if (cmd == "controlTransfer"){ unsigned id = jsonIntProp(n, "id", 0); uint8_t bmRequestType = jsonIntProp(n, "bmRequestType", 0xC0); uint8_t bRequest = jsonIntProp(n, "bRequest"); uint16_t wValue = jsonIntProp(n, "wValue", 0); uint16_t wIndex = jsonIntProp(n, "wIndex", 0); bool isIn = bmRequestType & 0x80; JSONNode reply(JSON_NODE); reply.push_back(JSONNode("_action", "return")); reply.push_back(JSONNode("id", id)); int ret = -1000; if (isIn){ uint16_t wLength = jsonIntProp(n, "wLength", 64); if (wLength > 64) wLength = 64; if (wLength < 0) wLength = 0; uint8_t data[wLength]; ret = controlTransfer(bmRequestType, bRequest, wValue, wIndex, data, wLength); if (ret >= 0){ JSONNode data_arr(JSON_ARRAY); for (int i=0; i<ret && i<wLength; i++){ data_arr.push_back(JSONNode("", data[i])); } data_arr.set_name("data"); reply.push_back(data_arr); } }else{ string datastr; JSONNode data = n.at("data"); if (data.type() == JSON_ARRAY){ for(JSONNode::iterator i=data.begin(); i!=data.end(); i++){ datastr.push_back(i->as_int()); } }else{ datastr = data.as_string(); } ret = controlTransfer(bmRequestType, bRequest, wValue, wIndex, (uint8_t *)datastr.data(), datastr.size()); } reply.push_back(JSONNode("status", ret)); client.sendJSON(reply); }else if(cmd == "enterBootloader"){ std::cout << "enterBootloader: "; int r = controlTransfer(0x40|0x80, 0xBB, 0, 0, NULL, 100); std::cout << "return " << r << std::endl; }else{ return false; } return true; }
int getIntFromArray(JSONNode node, char* name) { try { return node.at(name).as_array()[0].as_int(); } catch(exception& e) { cout << " Parse error" << e.what() << endl; } return -65535; }
void CDropbox::RequestAccountInfo(void *p) { CDropbox *self = (CDropbox*)p; MCONTACT hContact = self->GetDefaultContact(); ptrA token(db_get_sa(NULL, MODULE, "TokenSecret")); GetCurrentAccountRequest request(token); NLHR_PTR response(request.Send(self->hNetlibConnection)); HandleJsonResponseError(response); JSONNode root = JSONNode::parse(response->pData); if (root.empty()) return; JSONNode referral_link = root.at("referral_link"); if (!referral_link.empty()) db_set_s(hContact, MODULE, "Homepage", referral_link.as_string().c_str()); JSONNode email = root.at("email"); if (!email.empty()) db_set_s(hContact, MODULE, "e-mail", email.as_string().c_str()); JSONNode name = root.at("name"); if (!name.empty()) { db_set_utf(hContact, MODULE, "FirstName", name.at("given_name").as_string().c_str()); db_set_utf(hContact, MODULE, "LastName", name.at("surname").as_string().c_str()); } JSONNode country = root.at("country"); if (!country.empty()) { std::string isocode = country.as_string(); if (isocode.empty()) db_unset(hContact, MODULE, "Country"); else { char *szCountry = (char *)CallService(MS_UTILS_GETCOUNTRYBYISOCODE, (WPARAM)isocode.c_str(), 0); db_set_s(hContact, MODULE, "Country", szCountry); } } /*JSONNode quota_info = root.at("quota_info"); if (!quota_info.empty()) { ULONG lTotalQuota = quota_info.at("quota").as_int(); ULONG lNormalQuota = quota_info.at("normal").as_int(); ULONG lSharedQuota = quota_info.at("shared").as_int(); db_set_dw(hContact, MODULE, "SharedQuota", lSharedQuota); db_set_dw(hContact, MODULE, "NormalQuota", lNormalQuota); db_set_dw(hContact, MODULE, "TotalQuota", lTotalQuota); db_set_s(hContact, "CList", "StatusMsg", CMStringA(FORMAT, Translate("Free %ld of %ld MB"), (lTotalQuota - lNormalQuota) / (1024 * 1024), lTotalQuota / (1024 * 1024))); }*/ }
bool ServerSocket::handle_admin(JSONNode& n) { is_admin = true; string cmd = n.at("cmd").as_string(); if(cmd == "_connect") { return(true); } else if(cmd == "_users") { return(handle_admin_users()); } else if(cmd == "_stats") { return(handle_admin_stats()); } else if(cmd == "_stop") { return(handle_admin_stop()); } return(true); }
void CDropbox::HandleJsonResponseError(NETLIBHTTPREQUEST *response) { if (response == NULL) throw DropboxException(HttpStatusToText(HTTP_STATUS_ERROR)); if (response->resultCode == HTTP_STATUS_OK) return; if (response->resultCode != HTTP_STATUS_CONFLICT) { if (response->dataLength) throw DropboxException(response->pData); throw DropboxException(HttpStatusToText((HTTP_STATUS)response->resultCode)); } JSONNode root = JSONNode::parse(response->pData); if (root.empty()) throw DropboxException(HttpStatusToText(HTTP_STATUS_ERROR)); JSONNode error = root.at("error_summary"); if (error.empty()) return; throw DropboxException(error.as_string().c_str()); }
void TestSuite::TestInspectors(void){ UnitTest::SetPrefix("TestInspectors.cpp - Inspectors"); JSONNode test = JSONNode(JSON_NULL); #ifdef JSON_CASTABLE assertEquals(test.as_string(), JSON_TEXT("")); assertEquals(test.as_int(), 0); assertEquals(test.as_float(), 0.0f); assertEquals(test.as_bool(), false); #endif test = 15.5f; assertEquals(test.type(), JSON_NUMBER); #ifdef JSON_CASTABLE assertEquals(test.as_string(), JSON_TEXT("15.5")); #endif assertEquals(test.as_int(), 15); assertEquals(test.as_float(), 15.5f); #ifdef JSON_CASTABLE assertEquals(test.as_bool(), true); #endif test = 0.0f; assertEquals(test.type(), JSON_NUMBER); #ifdef JSON_CASTABLE assertEquals(test.as_string(), JSON_TEXT("0")); #endif assertEquals(test.as_int(), 0); assertEquals(test.as_float(), 0.0f); #ifdef JSON_CASTABLE assertEquals(test.as_bool(), false); #endif test = true; assertEquals(test.type(), JSON_BOOL); #ifdef JSON_CASTABLE assertEquals(test.as_string(), JSON_TEXT("true")); assertEquals(test.as_int(), 1); assertEquals(test.as_float(), 1.0f); #endif assertEquals(test.as_bool(), true); test = false; assertEquals(test.type(), JSON_BOOL); #ifdef JSON_CASTABLE assertEquals(test.as_string(), JSON_TEXT("false")); assertEquals(test.as_int(), 0); assertEquals(test.as_float(), 0.0f); #endif assertEquals(test.as_bool(), false); #ifdef JSON_CASTABLE test.cast(JSON_NODE); #else test = JSONNode(JSON_NODE); #endif assertEquals(test.type(), JSON_NODE); assertEquals(test.size(), 0); test.push_back(JSONNode(JSON_TEXT("hi"), JSON_TEXT("world"))); test.push_back(JSONNode(JSON_TEXT("hello"), JSON_TEXT("mars"))); test.push_back(JSONNode(JSON_TEXT("salut"), JSON_TEXT("france"))); assertEquals(test.size(), 3); TestSuite::testParsingItself(test); #ifdef JSON_CASTABLE JSONNode casted = test.as_array(); #ifdef JSON_UNIT_TEST assertNotEquals(casted.internal, test.internal); #endif assertEquals(casted.type(), JSON_ARRAY); assertEquals(test.type(), JSON_NODE); assertEquals(test.size(), 3); assertEquals(casted.size(), 3); TestSuite::testParsingItself(casted); #endif UnitTest::SetPrefix("TestInspectors.cpp - Location"); try { #ifdef JSON_CASTABLE assertEquals(casted.at(0), JSON_TEXT("world")); assertEquals(casted.at(1), JSON_TEXT("mars")); assertEquals(casted.at(2), JSON_TEXT("france")); assertEquals(casted.at(0).name(), JSON_TEXT("")); assertEquals(casted.at(1).name(), JSON_TEXT("")); assertEquals(casted.at(2).name(), JSON_TEXT("")); #endif assertEquals(test.at(0), JSON_TEXT("world")); assertEquals(test.at(1), JSON_TEXT("mars")); assertEquals(test.at(2), JSON_TEXT("france")); assertEquals(test.at(0).name(), JSON_TEXT("hi")); assertEquals(test.at(1).name(), JSON_TEXT("hello")); assertEquals(test.at(2).name(), JSON_TEXT("salut")); } catch (std::out_of_range){ FAIL("exception caught"); } try { assertEquals(test.at(JSON_TEXT("hi")), JSON_TEXT("world")); assertEquals(test.at(JSON_TEXT("hello")), JSON_TEXT("mars")); assertEquals(test.at(JSON_TEXT("salut")), JSON_TEXT("france")); #ifdef JSON_CASE_INSENSITIVE_FUNCTIONS assertEquals(test.at_nocase(JSON_TEXT("SALUT")), JSON_TEXT("france")); assertEquals(test.at_nocase(JSON_TEXT("HELLO")), JSON_TEXT("mars")); assertEquals(test.at_nocase(JSON_TEXT("HI")), JSON_TEXT("world")); #endif } catch (std::out_of_range){ FAIL("exception caught"); } assertException(test.at(JSON_TEXT("meh")), std::out_of_range); #ifdef JSON_CASE_INSENSITIVE_FUNCTIONS assertException(test.at_nocase(JSON_TEXT("meh")), std::out_of_range); #endif assertEquals(test[JSON_TEXT("hi")], json_string(JSON_TEXT("world"))); assertEquals(test[JSON_TEXT("hello")], json_string(JSON_TEXT("mars"))); assertEquals(test[JSON_TEXT("salut")], json_string(JSON_TEXT("france"))); assertEquals(test[0], JSON_TEXT("world")); assertEquals(test[1], JSON_TEXT("mars")); assertEquals(test[2], JSON_TEXT("france")); #ifdef JSON_ITERATORS #ifdef JSON_CASTABLE UnitTest::SetPrefix("TestInspectors.cpp - Iterators"); for(JSONNode::iterator it = casted.begin(), end = casted.end(); it != end; ++it){ assertEquals((*it).name(), JSON_TEXT("")); } #endif #endif #ifdef JSON_BINARY UnitTest::SetPrefix("TestInspectors.cpp - Binary"); test.set_binary((const unsigned char *)"Hello World", 11); assertEquals(test.type(), JSON_STRING); assertEquals(test.as_string(), JSON_TEXT("SGVsbG8gV29ybGQ=")); assertEquals(test.as_binary(), "Hello World"); assertEquals(test.as_binary().size(), 11); test = JSON_TEXT("Hello World"); assertEquals(test.type(), JSON_STRING); assertEquals(test.as_string(), JSON_TEXT("Hello World")); #ifdef JSON_SAFE assertEquals(test.as_binary(), ""); #endif #endif #ifdef JSON_READ_PRIORITY //This is a regression test for a bug in at() json_string buffer(JSON_TEXT("{ \"myValue1\" : \"foo\", \"myValue2\" : \"bar\"}")); JSONNode current = libjson::parse(buffer); try { JSONNode & value1 = current[JSON_TEXT("myValue1")]; assertEquals(value1.as_string(), JSON_TEXT("foo")); JSONNode & value2 = current[JSON_TEXT("myValue2")]; assertEquals(value2.as_string(), JSON_TEXT("bar")); } catch (...){ assertTrue(false); } #endif }
TEST_F(SerializerUnittest, Write) { Serializer serializer; serializer.Init(".", "Data", SerializerOpenModeWrite); // Create 4D field with JILK storage plus stride 2 const int isize = 6, jsize = 8, ksize = 7, lsize = 4; const int kstride = 2, lstride = kstride*ksize, istride = lstride*lsize, jstride = istride*isize; const int ibstrided = istride*sizeof(double), jbstrided = jstride*sizeof(double), kbstrided = kstride*sizeof(double), lbstrided = lstride*sizeof(double); const int ibstridef = istride*sizeof(float), jbstridef = jstride*sizeof(float), kbstridef = kstride*sizeof(float), lbstridef = lstride*sizeof(float); const int allocsize = jstride*jsize; std::vector<double> dataD(allocsize); std::vector<float> dataF(allocsize); for (int i = 0; i < isize; ++i) for (int j = 0; j < jsize; ++j) for (int k = 0; k < ksize; ++k) for (int l = 0; l < lsize; ++l) { dataD[i*istride + j*jstride + k*kstride + l*lstride] = i*12.25 + j*k*1. - 2.75 / (l+10.); dataF[i*istride + j*jstride + k*kstride + l*lstride] = i*12.25 + j*k*1. - 2.75 / (l+10.); } // Register various versions of this field serializer.RegisterField("ik" , "double", 8, isize, 1, ksize, 1, 0, 0, 0, 0, 0, 0, 0, 0); serializer.RegisterField("jk" , "float" , 4, 1, jsize, ksize, 1, 0, 0, 0, 0, 0, 0, 0, 0); serializer.RegisterField("ikl" , "double", 8, isize, 1, ksize, lsize, 0, 0, 0, 0, 0, 0, 0, 0); serializer.RegisterField("ijkl", "float" , 4, isize, jsize, ksize, lsize, 0, 0, 0, 0, 0, 0, 0, 0); // Setting a savepoint and serializing all fields Savepoint sp; sp.Init("MySavepoint"); sp.AddMetainfo("Value", 3.125); sp.AddMetainfo("ValueF", 3.625f); sp.AddMetainfo("MyName", "Andrea Arteaga"); sp.AddMetainfo("MyAge", 26); sp.AddMetainfo("ILikeThis", true); const int ilevel = 3, jlevel = 0, llevel = 2; const double* pIKData = dataD.data() + jstride*jlevel + lstride*llevel; const float* pJKData = dataF.data() + istride*ilevel + lstride*llevel; const double* pIKLData = dataD.data() + jstride*jlevel; const float* pIJKLData = dataF.data(); serializer.WriteField( "ik", sp, pIKData, ibstrided, jbstrided, kbstrided, lbstrided); serializer.WriteField( "jk", sp, pJKData, ibstridef, jbstridef, kbstridef, lbstridef); serializer.WriteField( "ikl", sp, pIKLData, ibstrided, jbstrided, kbstrided, lbstrided); serializer.WriteField("ijkl", sp, pIJKLData, ibstridef, jbstridef, kbstridef, lbstridef); // Check metainfo std::ifstream dbfs("Data.json"); std::string dbtxt((std::istreambuf_iterator<char>(dbfs)), std::istreambuf_iterator<char>()); dbfs.close(); JSONNode dbnode = libjson::parse(dbtxt); JSONNode fieldstable, offsettable, globalinfo; ASSERT_EQ(3, dbnode.size()); ASSERT_NO_THROW(fieldstable = dbnode.at("FieldsTable")); ASSERT_NO_THROW(offsettable = dbnode.at("OffsetTable")); ASSERT_NO_THROW(globalinfo = dbnode.at("GlobalMetainfo")); ASSERT_EQ(4, fieldstable.size()); ASSERT_EQ(1, offsettable.size()); ASSERT_LE(1, globalinfo.size()); ASSERT_EQ(std::string("centralized"), globalinfo.at("__format").as_string()); // Check savepoint metainfo Savepoint spload; ASSERT_EQ(std::string("MySavepoint"), offsettable[0]["__name"].as_string()); ASSERT_EQ(0, offsettable[0]["__id"].as_int()); ASSERT_EQ(3.125, offsettable[0]["Value"].as_float()); ASSERT_EQ(3.625f, offsettable[0]["ValueF"].as_float()); ASSERT_EQ(std::string("Andrea Arteaga"), offsettable[0]["MyName"].as_string()); ASSERT_EQ(26, offsettable[0]["MyAge"].as_int()); ASSERT_TRUE(offsettable[0]["ILikeThis"].as_bool()); { // Check IK // Read data std::ifstream fs("Data_ik.dat", std::ios::binary); fs.seekg(0, fs.end); int filelength = fs.tellg(); fs.seekg(0, fs.beg); ASSERT_EQ(sizeof(double)*isize*ksize, filelength); std::vector<char> rawdata(filelength); fs.read(rawdata.data(), filelength); fs.close(); // Check data const double* pNewData = reinterpret_cast<const double*>(rawdata.data()); for (int i = 0; i < isize; ++i) for (int k = 0; k < ksize; ++k) { const int j = jlevel, l = llevel; const double value = *(pNewData + k*isize + i); const double reference = dataD[i*istride + j*jstride + k*kstride + l*lstride]; ASSERT_EQ(reference, value) << "i=" << i << ", k=" << k; } } { // Check JK // Read data std::ifstream fs("Data_jk.dat", std::ios::binary); fs.seekg(0, fs.end); int filelength = fs.tellg(); fs.seekg(0, fs.beg); ASSERT_EQ(sizeof(float)*jsize*ksize, filelength); std::vector<char> rawdata(filelength); fs.read(rawdata.data(), filelength); fs.close(); // Check data const float* pNewData = reinterpret_cast<const float*>(rawdata.data()); for (int j = 0; j < jsize; ++j) for (int k = 0; k < ksize; ++k) { const int i = ilevel, l = llevel; const float value = *(pNewData + k*jsize + j); const float reference = dataF[i*istride + j*jstride + k*kstride + l*lstride]; ASSERT_EQ(reference, value) << "j=" << j << ", k=" << k; } } { // Check IKL // Read data std::ifstream fs("Data_ikl.dat", std::ios::binary); fs.seekg(0, fs.end); int filelength = fs.tellg(); fs.seekg(0, fs.beg); ASSERT_EQ(sizeof(double)*isize*ksize*lsize, filelength); std::vector<char> rawdata(filelength); fs.read(rawdata.data(), filelength); fs.close(); // Check data const double* pNewData = reinterpret_cast<const double*>(rawdata.data()); for (int i = 0; i < isize; ++i) for (int k = 0; k < ksize; ++k) for (int l = 0; l < lsize; ++l) { const int j = jlevel; const double value = *(pNewData + l*ksize*isize + k*isize + i); const double reference = dataD[i*istride + j*jstride + k*kstride + l*lstride]; ASSERT_EQ(reference, value) << "i=" << i << ", k=" << k << ", l=" << l; } } { // Check IJKL // Read data std::ifstream fs("Data_ijkl.dat", std::ios::binary); fs.seekg(0, fs.end); int filelength = fs.tellg(); fs.seekg(0, fs.beg); ASSERT_EQ(sizeof(float)*isize*jsize*ksize*lsize, filelength); std::vector<char> rawdata(filelength); fs.read(rawdata.data(), filelength); fs.close(); // Check data const float* pNewData = reinterpret_cast<const float*>(rawdata.data()); for (int i = 0; i < isize; ++i) for (int j = 0; j < jsize; ++j) for (int k = 0; k < ksize; ++k) for (int l = 0; l < lsize; ++l) { const float value = *(pNewData + l*ksize*jsize*isize + k*jsize*isize + j*isize + i); const float reference = dataF[i*istride + j*jstride + k*kstride + l*lstride]; ASSERT_EQ(reference, value) << "i=" << i << ", j=" << j << ", k=" << k << ", l=" << l; } } // Second savepoint: some fields are rewritten, others are kept the same dataD[0] += 1.; dataF[0] += 1.; // ik does not change // jk does not change // ikl changes // ijkl changes sp.Init("SecondSavepoint"); serializer.WriteField( "ik", sp, pIKData, ibstrided, jbstrided, kbstrided, lbstrided); serializer.WriteField( "jk", sp, pJKData, ibstridef, jbstridef, kbstridef, lbstridef); serializer.WriteField( "ikl", sp, pIKLData, ibstrided, jbstrided, kbstrided, lbstrided); serializer.WriteField("ijkl", sp, pIJKLData, ibstridef, jbstridef, kbstridef, lbstridef); // Load offsettable again dbfs.open("Data.json"); dbtxt = std::string((std::istreambuf_iterator<char>(dbfs)), std::istreambuf_iterator<char>()); dbfs.close(); dbnode = libjson::parse(dbtxt); ASSERT_NO_THROW(offsettable = dbnode["OffsetTable"]); ASSERT_EQ(2, offsettable.size()); ASSERT_EQ(std::string("SecondSavepoint"), offsettable[1]["__name"].as_string()); ASSERT_EQ(1, offsettable[1]["__id"].as_int()); ASSERT_EQ(4, offsettable[1]["__offsets"].size()); for (int i = 0; i < 4; ++i) { const std::string fieldname = offsettable[1]["__offsets"][i].name(); if (fieldname.size() < 3) ASSERT_EQ(0, offsettable[1]["__offsets"][i][0].as_int()); else ASSERT_LT(0, offsettable[1]["__offsets"][i][0].as_int()); } // Check binary data size for (int i = 0; i < 4; ++i) { const std::string fieldname = offsettable[1]["__offsets"][i].name(); int filelength_expect; if (fieldname == "ik") filelength_expect = 1*sizeof(double)*isize* 1 *ksize* 1 ; if (fieldname == "jk") filelength_expect = 1*sizeof(float )* 1 *jsize*ksize* 1 ; if (fieldname == "ikl") filelength_expect = 2*sizeof(double)*isize* 1 *ksize*lsize; if (fieldname == "ijkl") filelength_expect = 2*sizeof(float )*isize*jsize*ksize*lsize; std::ifstream fs(("Data_" + fieldname + ".dat").c_str(), std::ios::binary); fs.seekg(0, fs.end); int filelength = fs.tellg(); fs.close(); ASSERT_EQ(filelength_expect, filelength); } // Cleanup files std::remove("Data.json"); std::remove("Data_ik.dat"); std::remove("Data_jk.dat"); std::remove("Data_ikl.dat"); std::remove("Data_ijkl.dat"); }
bool ServerSocket::handle_json(const std::string& line) { try { JSONNode n = libjson::parse(line); string cmd = n.at("cmd").as_string(); // handle admin messages if(cmd.length() > 0 && cmd[0] == '_') { return(handle_admin(n)); } if(m_id.size() == 0 && cmd != "connect") { error("Please connect first", line); return(false); } if(m_id.size() == 0 && IrcSessionManager::get_instance().get_user_count() == Utils::get_max_clients()) { error_overload(); return(false); } IrcSession* sess = IrcSessionManager::get_instance().get_session(m_id); if(sess == NULL) { error("Couldn't retreive Irc Session", line); return(false); } m_id = sess->get_id(); if(cmd == "connect") { std::string host = GetRemoteHostname(); std::string ip = GetRemoteAddress(); if (host == "") host = ip; sess->connect(n.at("nick").as_string() , n.at("user").as_string() , n.at("name").as_string() , host, ip, n.at("device").as_string()); send_ok(); } else if(cmd == "quit") { sess->get_client().quit(n.at("msg").as_string()); IrcSessionManager::get_instance().remove_session(m_id); send_ok(); return(false); // to prevent the server from trying to retrieve responses // from non-existent session. }else if(cmd == "raw") { sess->get_client().raw(n.at("msg").as_string()); send_ok(); }else if(cmd == "update") { send_ok(); }else if(cmd == "message") { sess->get_client().message(n.at("chan").as_string() , n.at("msg").as_string()); send_ok(); }else if(cmd == "notice") { sess->get_client().notice(n.at("chan").as_string() , n.at("msg").as_string()); send_ok(); }else if(cmd == "nickchange") { sess->get_client().nick(n.at("new").as_string()); send_ok(); }else if(cmd == "emote") { sess->get_client().emote(n.at("chan").as_string() , n.at("msg").as_string()); send_ok(); }else if(cmd == "join") { sess->get_client().join(n.at("chan").as_string()); send_ok(); }else if(cmd == "part") { sess->get_client().part(n.at("chan").as_string()); send_ok(); } else if(cmd == "away") { sess->get_client().away(n.at("msg").as_string()); send_ok(); } else { error("Unsupported Command: " + cmd, line); return(false); } }catch(std::exception& ex) { string err = "Error Parsing JSON: "; err += ex.what(); error(err, line); return(false); } return(true); }
listener_ptr makeStreamListener(StreamingDevice* dev, ClientConn* client, JSONNode &n){ std::auto_ptr<WSStreamListener> listener(new WSStreamListener()); listener->id = jsonIntProp(n, "id"); listener->device = dev; listener->client = client; listener->decimateFactor = jsonIntProp(n, "decimateFactor", 1); // Prevent divide by 0 if (listener->decimateFactor == 0) listener->decimateFactor = 1; int start = jsonIntProp(n, "start", -1); if (start < 0){ // Negative indexes are relative to latest sample start = (dev->buffer_max()) + start + 1; } if (start < 0) listener->index = 0; else listener->index = start; listener->count = jsonIntProp(n, "count"); JSONNode j_streams = n.at("streams"); for(JSONNode::iterator i=j_streams.begin(); i!=j_streams.end(); i++){ listener->streams.push_back( dev->findStream( jsonStringProp(*i, "channel"), jsonStringProp(*i, "stream"))); } JSONNode::iterator t = n.find("trigger"); if (t != n.end() && (t->type()) == JSON_NODE){ JSONNode &trigger = *t; string type = jsonStringProp(trigger, "type", "in"); if (type == "in"){ listener->triggerType = INSTREAM; listener->triggerLevel = jsonFloatProp(trigger, "level"); listener->triggerStream = dev->findStream( jsonStringProp(trigger, "channel"), jsonStringProp(trigger, "stream")); }else if (type == "out"){ listener->triggerType = OUTSOURCE; listener->triggerChannel = dev->channelById(jsonStringProp(trigger, "channel")); if (!listener->triggerChannel) throw ErrorStringException("Trigger channel not found"); }else{ throw ErrorStringException("Invalid trigger type"); } listener->triggerRepeat = jsonBoolProp(trigger, "repeat", true); listener->triggerHoldoff = jsonIntProp(trigger, "holdoff", 0); listener->triggerOffset = jsonIntProp(trigger, "offset", 0); if (listener->triggerOffset<0 && -listener->triggerOffset >= listener->triggerHoldoff){ // Prevent big negative offsets that could cause infinite loops listener->triggerHoldoff = -listener->triggerOffset; } listener->triggerForce = jsonIntProp(trigger, "force", 0); listener->triggerForceIndex = listener->index + listener->triggerForce; } return listener_ptr(listener.release()); }
bool CharacterParser::Parse(std::string jsonString, GameCharacter* character) { JSONNode characterNode = libjson::parse(jsonString); character->name = characterNode.at("name").as_string(); character->SetLevel(static_cast<int>(characterNode.at("level").as_int())); const unsigned long long hitPoints = static_cast<unsigned long long>(characterNode.at("hitPoints").as_int()); character->SetMaxHitPoints(hitPoints); character->SetCurrentHitPoints(hitPoints); const unsigned long long magicPoints = static_cast<unsigned long long>(characterNode.at("magicPoints").as_int()); character->SetMaxMagicPoints(magicPoints); character->SetCurrentMagicPoints(magicPoints); character->SetStrength(static_cast<unsigned long long>(characterNode.at("strength").as_int())); character->SetDexterity(static_cast<unsigned long long>(characterNode.at("dexterity").as_int())); character->SetIntelligence(static_cast<unsigned long long>(characterNode.at("intelligence").as_int())); character->SetVitality(static_cast<unsigned long long>(characterNode.at("vitality").as_int())); character->SetStamina(static_cast<unsigned long long>(characterNode.at("stamina").as_int())); character->SetLuck(static_cast<unsigned long long>(characterNode.at("luck").as_int())); // This kinda feels out of place... character->sprite = std::make_shared<GameTexture>(characterNode.at("sprite").as_string()); character->spritesheet = std::make_shared<GameTexture>(characterNode.at("spritesheet").as_string()); character->spriteName = "characters.sprite." + character->name; character->spritesheetName = "characters.spritesheet." + character->name; Services::Locator::TextureService()->AddTexture(character->sprite, character->spriteName, nullptr); Services::Locator::TextureService()->AddTexture(character->spritesheet, character->spritesheetName, nullptr); return true; }
UINT CDropbox::RequestAccessTokenAsync(void *owner, void *param) { HWND hwndDlg = (HWND)param; CDropbox *instance = (CDropbox*)owner; EnableWindow(GetDlgItem(hwndDlg, IDC_AUTHORIZE), FALSE); SetDlgItemText(hwndDlg, IDC_AUTH_STATUS, TranslateT("in process...")); if (instance->HasAccessToken()) instance->DestroyAccessToken(); char requestToken[128]; GetDlgItemTextA(hwndDlg, IDC_REQUEST_CODE, requestToken, _countof(requestToken)); GetAccessTokenRequest request(requestToken); NLHR_PTR response(request.Send(instance->hNetlibConnection)); if (response == NULL || response->resultCode != HTTP_STATUS_OK) { Netlib_Logf(instance->hNetlibConnection, "%s: %s", MODULE, HttpStatusToText(HTTP_STATUS_ERROR)); if (hwndDlg) SetDlgItemText(hwndDlg, IDC_AUTH_STATUS, TranslateT("server does not respond")); /*else ShowNotification(TranslateT("server does not respond"), MB_ICONERROR);*/ return 0; } JSONNode root = JSONNode::parse(response->pData); if (root.empty()) { Netlib_Logf(instance->hNetlibConnection, "%s: %s", MODULE, HttpStatusToText((HTTP_STATUS)response->resultCode)); if (hwndDlg) SetDlgItemText(hwndDlg, IDC_AUTH_STATUS, TranslateT("server does not respond")); /*else ShowNotification((TCHAR*)error_description, MB_ICONERROR);*/ return 0; } JSONNode node = root.at("error_description"); if (node != JSONNULL) { ptrT error_description(mir_a2t_cp(node.as_string().c_str(), CP_UTF8)); Netlib_Logf(instance->hNetlibConnection, "%s: %s", MODULE, HttpStatusToText((HTTP_STATUS)response->resultCode)); if (hwndDlg) SetDlgItemText(hwndDlg, IDC_AUTH_STATUS, error_description); /*else ShowNotification((TCHAR*)error_description, MB_ICONERROR);*/ return 0; } node = root.at("access_token"); db_set_s(NULL, MODULE, "TokenSecret", node.as_string().c_str()); ProtoBroadcastAck(MODULE, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE)ID_STATUS_OFFLINE, (WPARAM)ID_STATUS_ONLINE); MCONTACT hContact = instance->GetDefaultContact(); if (hContact) { if (db_get_w(hContact, MODULE, "Status", ID_STATUS_OFFLINE) != ID_STATUS_ONLINE) db_set_w(hContact, MODULE, "Status", ID_STATUS_ONLINE); } try { RequestAccountInfo(instance); } catch (DropboxException &ex) { Netlib_Logf(instance->hNetlibConnection, "%s: %s", MODULE, ex.what()); return 0; } if (hwndDlg) SetDlgItemText(hwndDlg, IDC_AUTH_STATUS, TranslateT("you have been authorized")); /*else ShowNotification(TranslateT("you have been authorized"), MB_ICONINFORMATION);*/ SetDlgItemTextA(hwndDlg, IDC_REQUEST_CODE, ""); return 0; }