Esempio n. 1
0
void api_hdd_handler(const shared_ptr<restbed::Session> session)
{
  Hdd *hdd;
  JSONArray devices;
  JSONObject obj;
  JSONObject deviceData;
  JSONValue *output;
  double hddTotal;
  double hddUsage;
  vector<string> hddDevices;

  hdd = Hdd::getInstance();
  hddTotal = hdd->getTotalCapacity();
  hddUsage = hdd->getUsedCapacity();
  hddDevices = hdd->getListHardDrive();
  obj[L"total"] = new JSONValue(hddTotal);
  obj[L"usage"] = new JSONValue(hddUsage);
  for (vector<string>::iterator it = hddDevices.begin(); it != hddDevices.end(); ++it)
  {
    deviceData[L"name"] = new JSONValue(s2ws(*it));
    devices.push_back(new JSONValue(deviceData));
  }
  obj[L"devices"] = new JSONValue(devices);
  output = new JSONValue(obj);
  session->close(restbed::OK, ws2s(output->Stringify()), { { "Content-Type", "application/json" } });
}
Esempio n. 2
0
void api_os_handler(const shared_ptr<restbed::Session> session)
{
  Os *os;
  JSONObject obj;
  JSONValue *output;
  wstring osName;
  double osArchitecture;

  os = Os::getInstance();
  osName = s2ws(os->getName());
  osArchitecture = os->getArchitecture();
  obj[L"name"] = new JSONValue(osName);
  obj[L"architecture"] = new JSONValue(osArchitecture);
  output = new JSONValue(obj);
  session->close(restbed::OK, ws2s(output->Stringify()), { { "Content-Type", "application/json" } });
}
Esempio n. 3
0
void printStatus(char* expId, char* format, const wchar_t* ip, int type, int port, int isConnected ){
	JSONObject root_out;
	wchar_t expId_t[256];
	char_to_wchar(expId_t, expId);
	wchar_t format_t[256];
	char_to_wchar(format_t, format);
			
	root_out[L"expId"] = new JSONValue(expId_t);
	root_out[L"isConnected"] = new JSONValue((double)isConnected);
	root_out[L"format"] = new JSONValue(format_t);
	root_out[L"type"] = new JSONValue((double)type);
	root_out[L"ip"] = new JSONValue(ip);
	root_out[L"port"] = new JSONValue((double)port);
	
	JSONValue *value = new JSONValue(root_out);
	std::wcout << value->Stringify().c_str() << std::endl;
}
Esempio n. 4
0
/*
{
"contents": [{
"Test": "Test,Obj"
},
"HelloWorld,cswuyg",
"Good Good Studey,Day Day Up"],
"result": "no_way"
}
*/
std::wstring CTestJSON::GetJsonStr()
{
	JSONArray jsArray;
	JSONObject jsObj;
	jsObj[L"Test"] = new(std::nothrow)JSONValue(L"Test,Obj");
	jsArray.push_back(new(std::nothrow)JSONValue(jsObj));
	jsArray.push_back(new(std::nothrow)JSONValue(L"HelloWorld,cswuyg"));
	jsArray.push_back(new(std::nothrow)JSONValue(L"Good Good Studey,Day Day Up"));
	jsArray.push_back(new(std::nothrow)JSONValue((double)1988));

	JSONObject jsObjNew;
	jsObjNew[L"contents"] = new(std::nothrow)JSONValue(jsArray);
	jsObjNew[L"result"] = new(std::nothrow)JSONValue(L"no_way");

	JSONValue jsValue = jsObjNew;
	std::wstring strRet = jsValue.Stringify().c_str();
	return strRet;
}
Esempio n. 5
0
std::string serialize_data(data_t *data) {
    std::lock_guard<std::mutex> lk(data->m);

    JSONObject root;

    JSONObject states;
    states[L"isBlink"] = new JSONValue(data->isBlink);
    states[L"isLeftWink"] = new JSONValue(data->isLeftWink);
    states[L"isRightWink"] = new JSONValue(data->isRightWink);
    states[L"isLookingLeft"] = new JSONValue(data->isLookingLeft);
    states[L"isLookingRight"] = new JSONValue(data->isLookingRight);

    JSONObject expressiv;

    expressiv[L"lowerFaceActionName"] = new JSONValue(s2w(data->lowerFaceActionName));
    expressiv[L"lowerFaceAction"] = new JSONValue((double) data->lowerFaceAction);
    expressiv[L"lowerFaceActionPower"] = new JSONValue(data->lowerFaceActionPower);
    expressiv[L"upperFaceActionName"] = new JSONValue(s2w(data->upperFaceActionName));
    expressiv[L"upperFaceAction"] = new JSONValue((double) data->upperFaceAction);
    expressiv[L"upperFaceActionPower"] = new JSONValue(data->upperFaceActionPower);

    root[L"time"] = new JSONValue(data->timestamp);
    root[L"battery"] =  new JSONValue(data->battery);
    root[L"wirelessSignal"] = new JSONValue((double)(data->wireless_signal));
    root[L"states"] = new JSONValue(states);
    root[L"expressiv"] = new JSONValue(expressiv);

    JSONArray array;
    for (int i = 0; i < data->cq.size(); i++) {
        array.push_back(new JSONValue((double) data->cq[i]));
    }
    root[L"contactQuality"] = new JSONValue(array);

    JSONValue *value = new JSONValue(root);
    std::wstring out = value->Stringify();


    std::string ss;
    ss.assign(out.begin(), out.end());

    delete value;

    return ss;
}
Esempio n. 6
0
void api_ram_handler(const shared_ptr<restbed::Session> session)
{
  Memory *memory;
  JSONObject obj;
  JSONValue *output;
  double memoryFreeSpace;
  double memoryTotalSpace;
  double memoryUsage;

  memory = Memory::getInstance();
  memoryFreeSpace = memory->getFreeRam();
  memoryTotalSpace = memory->getTotalRam();
  memoryUsage = memory->getPourcentRam();
  obj[L"free"] = new JSONValue(memoryFreeSpace);
  obj[L"total"] = new JSONValue(memoryTotalSpace);
  obj[L"usage"] = new JSONValue(memoryUsage);
  output = new JSONValue(obj);
  session->close(restbed::OK, ws2s(output->Stringify()), { { "Content-Type", "application/json" } });
}
Esempio n. 7
0
void api_cpu_handler(const shared_ptr<restbed::Session> session)
{
  Cpu *cpu;
  JSONObject obj;
  JSONValue *output;
  wstring cpuModel;
  double cpuCount;
  double cpuFrequency;

  cpu = Cpu::getInstance();
  cpuModel = s2ws(cpu->getCpuInfo());
  cpuCount = cpu->getCoresCount();
  cpuFrequency = cpu->getFreq();
  obj[L"model"] = new JSONValue(cpuModel);
  obj[L"count"] = new JSONValue(cpuCount);
  obj[L"frequency"] = new JSONValue(cpuFrequency);
  output = new JSONValue(obj);
  session->close(restbed::OK, ws2s(output->Stringify()), { { "Content-Type", "application/json" } });
}
Esempio n. 8
0
std::wstring CTestJSON::AddJsonStr( const std::wstring& strJsonStr )
{
	/*
	SimpleJson 库插入是非常麻烦的事情。
	JSONValue对象有智能指针的功能,会给你析构掉它所包含的JSON对象
	而JSON的as....函数,返回的是const类型的引用,如果是array类型,那么是JSONValue*的浅拷贝
	对Parse的返回值实行delete之后,JSONValue又会再delete一次,于是出现多次析构的错误
	所以必须保证,要么只有JSONValue对象去执行析构,要么只有主动的delete Parse的返回值。
	对于插入来说,这种逻辑会带来麻烦。定义了一个JSONValue,浅拷贝了parse返回值的一部分json对象,
	然后JSONValue析构了浅拷贝的JSONValue*,先对Parse的返回值则很难做处理,如果delete,则多析构了JSON对象,
	如果不delete,则Parse内部new的map内存没有被析构。

	解决办法有两种:
	1、不要定义JSONValue对象,而是定义JSONValue引用,因为我要往JSONValue里插值,所以必须用到const_cast。
	2、递归拷贝出JSONValue*里的字符串格式的JSON对象,然后再Parse之后进入新JSONObj,
	保证新、旧对象分离。
	*/
	JSONValue* jsInput = JSON::Parse(strJsonStr.c_str());
	if (jsInput == NULL || !jsInput->IsObject())
	{
		return L"";
	}

	std::wstring strRet;
	JSONObject jsObjNew;
	JSONObject::const_iterator it = jsInput->AsObject().begin();
	JSONObject::const_iterator itEnd = jsInput->AsObject().end();
	for (; it != itEnd; ++it)
	{
		std::wstring strFirst = it->first.c_str();
		std::wstring strSecond = it->second->Stringify().c_str();
		JSONValue* pTemp = JSON::Parse(strSecond.c_str());
		jsObjNew[strFirst] = pTemp;
	}
	jsObjNew[L"Love"] = new(std::nothrow)JSONValue(L"is Happiness");
	JSONValue jsValueNew = jsObjNew;
	strRet = jsValueNew.Stringify();
	return strRet;
}
Esempio n. 9
0
// Dialog proc for the Windows window
int CALLBACK DialogProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg)
	{
		case WM_INITDIALOG:
			hDlg = hWnd;
			break;

		case WM_CLOSE:
			EndDialog(hWnd, 0);
			break;

		case WM_DESTROY:
			PostQuitMessage(0);
			break;

		case WM_COMMAND:
		{
			if (HIWORD(wParam) != BN_CLICKED)
				break;

			SetWindowText(GetDlgItem(hWnd, IDC_OUTPUT), L"");

			switch (LOWORD(wParam))
			{
				case IDC_VERIFY:
				case IDC_ECHO:
				{
					int size = GetWindowTextLength(GetDlgItem(hWnd, IDC_INPUT));
					wchar_t* text = new wchar_t[size + 1];
					GetWindowText(GetDlgItem(hWnd, IDC_INPUT), text, size + 1);

					JSONValue *value = JSON::Parse(text);

					if (value == NULL)
					{
						SetWindowText(GetDlgItem(hWnd, IDC_OUTPUT), L"The JSON text *is not* valid");
					}
					else
					{
						if (LOWORD(wParam) == IDC_ECHO)
							SetWindowText(GetDlgItem(hWnd, IDC_OUTPUT), value->Stringify().c_str());
						else
							SetWindowText(GetDlgItem(hWnd, IDC_OUTPUT), L"The JSON text *is* valid");
						delete value;
					}

					delete text;
					break;
				}

				case IDC_EX1:
					extern const wchar_t *EXAMPLE;
					SetWindowText(GetDlgItem(hDlg, IDC_INPUT), EXAMPLE);
					example1();
					break;

				case IDC_EX2:
					SetWindowText(GetDlgItem(hDlg, IDC_INPUT), L"Example 2:\r\n\r\nKey 'test_string' has a value 'hello world'\r\nKey 'sample_array' is an array of 10 random numbers");
					example2();
					break;

				case IDC_TESTCASES:
					SetWindowText(GetDlgItem(hWnd, IDC_INPUT), L"");
					run_tests();
					break;
			}

			break;
		}
	}

	return 0;
}
const char* WebModelUnified::website_search(const char* req){
    JSONObject root;
    JSONArray jsarray;
    Connection* conn = connect();
    Query query = conn->query();

    string reqstr(req);
    string reqstr_spaced = replaceChar(reqstr, '+', ' ');
    vector<string> splittedstr;
    split(splittedstr, reqstr_spaced, boost::algorithm::is_any_of(" "));

    int titleForce = 10;
    int descriptionForce = 1;
    int urlForce = 3;

    query << "SELECT * , ";
    //Occurences total
    for(size_t i1 = 0; i1 < splittedstr.size(); i1++)
    {
        string s = splittedstr[i1];
        if(i1 != 0){
            query << " + ";
        }

        query << "((" <<
          titleForce << " * (char_length(title) - char_length(replace(title,'" << s << "',''))) + " <<
          descriptionForce << " * (char_length(description) - char_length(replace(description,'" << s << "',''))) + " <<
          urlForce << " * (char_length(url) - char_length(replace(url,'" << s << "','')))" <<
        ") / char_length('" << s << "'))";
    }
    query << " as Occurances " << " FROM website ";

    //Where clause
    for(size_t i1 = 0; i1 < splittedstr.size(); i1++)
    {
        string s = splittedstr[i1];
        if(i1 == 0) {
            query << "WHERE ";
        } else {
            query << "OR ";
        }
        query << "(url LIKE '%" << s << "%' or title LIKE '%" << s << "%' or description LIKE '%" << s << "%') ";
    }

    query << " ORDER BY " << "Occurances desc, title ASC ";

    StoreQueryResult ares = query.store();
    unsigned int numrow = ares.num_rows();

    for(unsigned int i = 0; i < numrow; i++)
    {
        JSONObject result;

        result[L"title"] = new JSONValue(wchartFromChar(ares[i]["title"]));
        result[L"description"] = new JSONValue(wchartFromChar(ares[i]["description"]));
        result[L"url"] = new JSONValue(wchartFromChar(ares[i]["url"]));
        JSONValue* resultVal = new JSONValue(result);

        jsarray.push_back(resultVal);
    }

    root[L"results"] = new JSONValue(jsarray);

    JSONValue* jvalue = new JSONValue(root);

    const char* returnStr = fromWString(jvalue->Stringify());
    delete jvalue;
    return returnStr;
}
	void addChildFromJSON(
		JSONValue* jv,
		UIComponent* curParent,
		bool isFloating = false
	) {
		int i;
		int j;
		int curIcon = 0;
		
		JSONValue* curTempl = NULL;
		
		
	
		if (
			jv->HasChild("template")
		) {
			if (
				jvTemplates->HasChild(jv->Child("template")->string_value)
			) {
				
				curTempl = jvTemplates->Child(jv->Child("template")->string_value);
			}
			else {
				cout << "invalid template \n";// << jv->Child("template")->string_value << "\n";
			}
		}
		
		
		for (i = 0; i < E_GST_LENGTH; i++) {
			guiStringValues[i] = "";
		}
		for (i = 0; i < E_GFT_LENGTH; i++) {
			guiFloatValues[i] = 0.0f;
		}
		
		guiFloatValues[E_GFT_HASBACKGROUND] = 1.0;
		guiFloatValues[E_GFT_SINGLELINE] = 1.0;
		guiStringValues[E_GST_SS] = "defaultSS";
		
		
		for (j = 0; j < 2; j++) {
			if (curTempl != NULL) {
				for (i = 0; i < E_GST_LENGTH; i++) {
					if (
						curTempl->HasChild(guiStringTypes[i])
					) {
						guiStringValues[i] = curTempl->Child(guiStringTypes[i])->string_value;
					}
				}
				for (i = 0; i < E_GFT_LENGTH; i++) {
					if (
						curTempl->HasChild(guiFloatTypes[i])
					) {
						guiFloatValues[i] = curTempl->Child(guiFloatTypes[i])->number_value;
					}
				}
			}
			curTempl = jv;
		}
		
		
		guiFloatValues[E_GFT_LAYER] = max(guiFloatValues[E_GFT_LAYER],(float)(curParent->layer));
		
		UIComponent* newParent = curParent->addChild(
			curParent->nodeId,
			nodeCount,
			guiStringValues,
			guiFloatValues,
			isFloating,
			jv
		);
		nodeCount++;
		
		
		int numChildren = 0;
		int numFloatingChildren = 0;
		int numDataChildren = 0;
		int numFilters = 0;
		JSONValue* jvChildren = NULL;
		JSONValue* jvFloatingChildren = NULL;
		JSONValue* jvChildTemplate = NULL;
		JSONValue* jvFilter = NULL;
		JSONValue* curFilter = NULL;
		
		JSONValue* jvData = NULL;
		JSONValue* jvDataRoot = NULL;
		JSONValue* curData = NULL;
		
		
		if (jv->HasChild("children")) {
			jvChildren = jv->Child("children");
			numChildren = jvChildren->CountChildren();
		}
		for (i = 0; i < numChildren; i++) {
			addChildFromJSON(jvChildren->Child(i),newParent, false);
		}
		
		
		if (jv->HasChild("floatingChildren")) {
			jvFloatingChildren = jv->Child("floatingChildren");
			numFloatingChildren = jvFloatingChildren->CountChildren();
		}
		for (i = 0; i < numFloatingChildren; i++) {
			addChildFromJSON(jvFloatingChildren->Child(i),newParent,true);
		}
		
		
		bool doProc = false;
		bool isInternal = false;
		int totCount = 0;
		E_GUI_CHILD_TYPES curCT = E_GCT_LENGTH;;
		
		
		if (jv->HasChild("childType")) {
			tempStrings[E_GDS_CHILD_TYPE] = jv->Child("childType")->string_value;
			
			
			if (jv->HasChild("isInternal")) {
				if (jv->Child("isInternal")->number_value != 0 ) {
					// use an internally generated JSON node
					isInternal = true;
				}
				else {
					// todo: load JSON file
				}
			}
			
			if (jv->HasChild("whereAllEqual")) {
				jvFilter = jv->Child("whereAllEqual");
				numFilters = jvFilter->CountChildren();
			}
			else {
				jvFilter = NULL;
				numFilters = 0;
			}
				
			
			
			if (jv->HasChild("dataSource")) {
				tempStrings[E_GDS_DATA_SOURCE] = jv->Child("dataSource")->string_value;
				
				if (isInternal) {
					if (jv->HasChild("dataFile")) {
						tempStrings[E_GDS_DATA_FILE] = jv->Child("dataFile")->string_value;
						jvDataRoot = (singleton->internalJSON[tempStrings[E_GDS_DATA_FILE]]).jv;
					}
					
					
				}
				else {
					jvDataRoot = jvRoot;
				}
				
				if (jvDataRoot != NULL) {
					getJVNodeByString(jvDataRoot, &jvData, tempStrings[E_GDS_DATA_SOURCE]);
					
					numDataChildren = jvData->CountChildren();
					if (jv->HasChild("childTemplate")) {
						jvChildTemplate = jv->Child("childTemplate");
					}
				}
			}
			
			
			if ((jvData != NULL)&&(jvChildTemplate != NULL)) {
				
				
				if (compChildStr("inventoryItem")) {
					curCT = E_GCT_INV_ITEM;
				}
				if (compChildStr("shaderParams")) {
					curCT = E_GCT_SHADER_PARAM;
				}
				
				//////////////////////////////////////////////////////////////////////
				//////////////////////////////////////////////////////////////////////
				
				
				
				
				for (i = 0; i < numDataChildren; i++) {
					
					curData = jvData->Child(i);
					
					doProc = true;
					if (jvFilter != NULL) {
						
						
						for (j = 0; j < numFilters; j++) {
							curFilter = jvFilter->Child(j);
							
							if ( curData->Child(curFilter->Child(0)->string_value)->IsNumber() ) {
								if (
									curData->Child(curFilter->Child(0)->string_value)->number_value !=
									curFilter->Child(1)->number_value
								) {
									doProc = false;
								}
							}
							else {
								// todo: string support
							}
						}
						
						
					}
					
					if (doProc) {
						switch (curCT) {
							case E_GCT_INV_ITEM:
								tempStrings[E_GDS_CHILD_NAME] = curData->Child("name")->string_value;
								
								curIcon = jvRoot->
									Child("itemDefs")->
									Child(tempStrings[E_GDS_CHILD_NAME])->
									Child("iconNum")->
									number_value;
								
								jvChildTemplate->
									Child("floatingChildren")->
									Child(0)->
									Child("children")->
									Child(0)->
									Child("label")->
									string_value = 
										jvRoot->
										Child("itemDefs")->
										Child(tempStrings[E_GDS_CHILD_NAME])->
										Child("class")->
										string_value;
								
								tempStrings[E_GDS_MATERIAL] = curData->Child("mat")->string_value;
								if (tempStrings[E_GDS_MATERIAL].compare("none") == 0) {
									tempStrings[E_GDS_MATERIAL] = "";
								}
								
								jvChildTemplate->Child("label")->string_value = 
									i__s(curIcon) +
									"& " +
									tempStrings[E_GDS_MATERIAL] +
									" " +
									tempStrings[E_GDS_CHILD_NAME];
							break;
							case E_GCT_SHADER_PARAM:
									
								jvChildTemplate->Child("label")->string_value = 
									curData->Child("shaderName")->string_value +
									"." +
									curData->Child("paramName")->string_value;
								
								jvChildTemplate->Child("uid")->string_value = curData->Child("uid")->string_value;
									
								jvChildTemplate->Child("callbackData")->Child("shaderName")->string_value = 
									curData->Child("shaderName")->string_value;
								jvChildTemplate->Child("callbackData")->Child("paramName")->string_value = 
									curData->Child("paramName")->string_value;
									
							break;
							case E_GCT_LENGTH:
								
							break;
						}
						
						
						
						
						
						// copy template to new child
						jv->Child("children")->array_value.push_back(
							JSON::Parse(jvChildTemplate->Stringify().c_str())
						);
						
						
						//PROBLEM
						
						addChildFromJSON(jv->Child("children")->Child(totCount),newParent,false); //jvChildTemplate //jv->Child("children")->Child(i)
						
						totCount++;
						
						
					}
					
					
				
				}
			}
			
			
			
			
			
			
		}
		
		
	}
Esempio n. 12
0
void Utility::writecfg(const char *name)
{
    JSONObject root, vars, aliases, complet, bnds, crossh; // clientinfo;
    vector<var::cvar*> varv;
    stream *f = openfile(path(name && name[0] ? name : game::savedconfig(), true), "w");
    if(!f) return;

    //clientinfo = game::writeclientinfo();
    //root[L"clientinfo"] = new JSONValue(clientinfo);

    crossh = writecrosshairs();
    if (!crossh.empty()) root[L"crosshairs"] = new JSONValue(crossh);

    enumerate(*var::vars, var::cvar*, v, varv.add(v));
    varv.sort(sortvars);
    loopv(varv)
    {
        var::cvar *v = varv[i];
        if (v->ispersistent()) switch(v->gt())
        {
            case var::VAR_I:
            {
                vars[towstring(v->gn())] = new JSONValue((double)v->gi());
                break;
            }
            case var::VAR_F:
            {
                vars[towstring(v->gn())] = new JSONValue(v->gf());
                break;
            }
            case var::VAR_S:
            {
                char *wval = (char*)malloc(1);
                const char *p = v->gs();
                for (int i = 0; *p; i++)
                {
                    switch(*p)
                    {
                        case '\n':
                        {
                            wval = (char*)realloc(wval, i + 3);
                            strcat(wval, "^n"); i++;
                            break;
                        }
                        case '\t':
                        {
                            wval = (char*)realloc(wval, i + 3);
                            strcat(wval, "^t"); i++;
                            break;
                        }
                        case '\f':
                        {
                            wval = (char*)realloc(wval, i + 3);
                            strcat(wval, "^f"); i++;
                            break;
                        }
                        case '"':
                        {
                            wval = (char*)realloc(wval, i + 3);
                            strcat(wval, "^\""); i++;
                            break;
                        }
                        default:
                        {
                            wval = (char*)realloc(wval, i + 2);
                            wval[i] = *p; wval[i+1] = '\0';
                            break;
                        }
                    }
                    p++;
                }
                vars[towstring(v->gn())] = new JSONValue(towstring(wval ? wval : ""));
                wval = NULL; free(wval);
                break;
            }
        }
    }
    if (!vars.empty()) root[L"variables"] = new JSONValue(vars);

    bnds = writebinds();
    if (!bnds.empty()) root[L"binds"] = new JSONValue(bnds);

    loopv(varv)
    {
        var::cvar *v = varv[i];
        if (v->isalias() && v->ispersistent() && !v->isoverriden() && v->gs()[0])
        {
            if (strstr(v->gn(), "new_entity_gui_field")) continue;
            aliases[towstring(v->gn())] = new JSONValue(towstring(v->gs()));
        }
    }
    if (!aliases.empty()) root[L"aliases"] = new JSONValue(aliases);

    complet = writecompletions();
    if (!complet.empty()) root[L"completions"] = new JSONValue(complet);

    JSONValue *value = new JSONValue(root);
    f->printf("%ls", value->Stringify().c_str());
    delete value;
    delete f;
}