示例#1
0
文件: json.c 项目: darcyg/websrv
size_t json_parse( void* obj, const js_struct* desc, const char* str )
{
    const js_struct* subdesc;
    size_t i, slen, *arrsize;
    unsigned char* ptr = obj;
    const char* orig = str;
    void *sub, *memb;

    while( isspace(*str) ) { ++str; }
    if( *str!='{' ) goto fail;

    do
    {
        for( ++str; isspace(*str); ++str ) { }
        if( *str == '}' ) break;
        if( *(str++) != '"' ) goto fail;

        for( i=0; i<desc->num_members; ++i )
        {
            slen = strlen(desc->members[i].name);
            if( !strncmp(str,desc->members[i].name,slen) && str[slen]=='"' )
                break;
        }

        if( i>=desc->num_members )
            goto fail;

        for( str+=slen+1; isspace(*str); ++str ) { }
        if( *(str++)!=':' ) goto fail;
        while( isspace(*str) ) { ++str; }

        memb = ptr + desc->members[i].offset;
        arrsize = (size_t*)(ptr + desc->members[i].sizeoffset);
        subdesc = desc->members[i].desc;

        switch( desc->members[i].type )
        {
        case TYPE_OBJ:
            if( !(sub = calloc(1, subdesc->objsize)) ) goto fail;
            if( !(slen = json_parse(sub,subdesc,str)) ) { free(sub); break; }
            *((void**)memb) = sub;
            break;
        case TYPE_OBJ_ARRAY:
            slen = json_parse_array( memb, arrsize, subdesc, str );
            break;
        case TYPE_INT:    slen = parse_int( memb, str );    break;
        case TYPE_STRING: slen = parse_string( memb, str ); break;
        default:          slen = 0;                         break;
        }

        if( !slen )
            goto fail;
        for( str += slen; isspace(*str); ++str ) { }
    }
    while( *str == ',' );

    if( *str == '}' )
        return str - orig + 1;
fail:
    json_free( obj, desc );
    return 0;
}
示例#2
0
static void remove_one(void)
{
	struct json *j = json_parse(tmpctx, "['invoice']");
	json_tok_remove(&j->toks, j->toks + 1, 1);
	assert(j);
}
示例#3
0
bool parse_wd_node_function_json(char* json_data, int data_len, char** func_name, int **node_id_set, int *count)
{
	json_value *root, *value;
	char* ptr;
	int node_count = 0;
	int i;

	*node_id_set = NULL;
	*func_name = NULL;
	*count = 0;

	root = json_parse(json_data,data_len);

	/* The root node must be object */
	if (root == NULL || root->type != json_object)
	{
		json_value_free(root);
		ereport(LOG,
			(errmsg("watchdog is unable to parse node function json"),
				 errdetail("invalid json data \"%s\"",json_data)));
		return false;
	}
	ptr = json_get_string_value_for_key(root, "Function");
	if (ptr == NULL)
	{
		json_value_free(root);
		ereport(LOG,
			(errmsg("watchdog is unable to parse node function json"),
				 errdetail("function node not found in json data \"%s\"",json_data)));
		return false;
	}
	*func_name = pstrdup(ptr);
	/* If it is a node function ?*/
	if (json_get_int_value_for_key(root, "NodeCount", &node_count))
	{
		/*node count not found, But we don't care much about this*/
		json_value_free(root);
		return true;
	}
	if (node_count <= 0)
	{
		json_value_free(root);
		return true;
	}
	*count = node_count;

	value = json_get_value_for_key(root,"NodeIdList");
	if (value == NULL)
	{
		json_value_free(root);
		ereport(LOG,
			(errmsg("invalid json data"),
				 errdetail("unable to find NodeIdList node from data")));
		return false;
	}
	if (value->type != json_array)
	{
		json_value_free(root);
		ereport(WARNING,
				(errmsg("invalid json data"),
				 errdetail("NodeIdList node does not contains Array")));
		return false;
	}
	if (node_count != value->u.array.length)
	{
		json_value_free(root);
		ereport(WARNING,
				(errmsg("invalid json data"),
				 errdetail("NodeIdList array contains %d nodes while expecting %d",value->u.array.length, node_count)));
		return false;
	}

	*node_id_set = palloc(sizeof(int) * node_count);
	for (i = 0; i < node_count; i++)
	{
		*node_id_set[i] = value->u.array.values[i]->u.integer;
	}
	json_value_free(root);
	return true;
}
示例#4
0
文件: json.c 项目: xanpeng/snippets
int json_parser_value(json_parser_t *parser, json_value_t *super, json_value_t *value) {
	int i;
	int c;
	int s;

	enum {
		status_first,
		status_next,
		status_begin,
		status_value,
		status_end,
		status_ok
	};

	if (super->type != JSON_ARRAY)
		return JSON_PARSER_ERR;

	if (parser->off == super->off)
		s = status_first;
	else
		s = status_next;

	for (i = parser->off; i < parser->len; i++) {
		c = parser->buf[i];

		switch (s) {
		case status_ok:
			parser->off = i;
			return JSON_PARSER_OK;
		case status_end:
			parser->off = i;
			return JSON_PARSER_END;
		case status_first:
			switch (c) {
			CASE_BLANK:
				break;
			case '[':
				s = status_begin;
				break;
			default:
				return JSON_PARSER_ERR;
			}
			break;
		case status_next:
			switch (c) {
			CASE_BLANK:
				break;
			case ']':
				s = status_end;
				break;
			case ',':
				s = status_begin;
				break;
			default:
				return JSON_PARSER_ERR;
			}
			break;
		case status_begin:
			switch (c) {
			CASE_BLANK:
				break;
			case ']':
				s = status_end;
				break;
			case ',':
				return JSON_PARSER_ERR;
			default:
				parser->off = i;
				s = status_value;
				break;
			}
			break;
		case status_value:
			if (json_parse(parser, super, value) != JSON_PARSER_OK)
				return JSON_PARSER_ERR;
			i = parser->off - 1; /* for next round */
			s = status_ok;
			break;
		default:
			return JSON_PARSER_ERR;
		}
	}
	return JSON_PARSER_ERR;
}
示例#5
0
int main(int argc, char* argv[]) {

	puts("Program start.");

	atexit(saveData);

	//open output files (this is done now so there would be an error at the start instead of in the middle of the program)
	if (1) {
		//delete + open file for raw data writing
		outputDataFileStream = fopen(OUTPUT_DATA_FILE, "wb");

		if (outputDataFileStream == NULL) {
			puts("Could not open \"" OUTPUT_DATA_FILE "\"!");
			system("pause");
			return -1;
		}
		
		//delete + open file for raw data writing
		outputBrawlerDataFileStream = fopen(OUTPUT_BRAWLER_DATA_FILE, "wb");

		if (outputBrawlerDataFileStream == NULL) {
			puts("Could not open \"" OUTPUT_BRAWLER_DATA_FILE "\"!");
			system("pause");
			return -1;
		}
	}

	//parse static data files
	if (1) {
		char *matchIdString = 0;
		long length;
		matchIdFileStream = fopen(MATCH_ID_FILE, "rb");

		if (matchIdFileStream == NULL) {
			puts("Could not open \"" MATCH_ID_FILE "\"!");
			system("pause");
			return -1;
		}

		fseek(matchIdFileStream, 0, SEEK_END);
		length = ftell(matchIdFileStream);
		fseek(matchIdFileStream, 0, SEEK_SET);
		matchIdString = malloc(length);
		fread(matchIdString, 1, length, matchIdFileStream);
		fclose(matchIdFileStream);

		matchIdArray = json_parse(
			matchIdString,
			length
			);
		free(matchIdString);
		char *itemDataString = 0;
		length = 0;
		caughtItemData = fopen(ITEM_DATA_FILE, "rb");

		if (caughtItemData == NULL) {
			puts("Could not open \"" ITEM_DATA_FILE "\"!");
			system("pause");
			return -1;
		}

		fseek(caughtItemData, 0, SEEK_END);
		length = ftell(caughtItemData);
		fseek(caughtItemData, 0, SEEK_SET);
		itemDataString = malloc(length);
		fread(itemDataString, 1, length, caughtItemData);
		fclose(caughtItemData);

		itemDataArray = json_parse(
			itemDataString,
			length
			);

		if (itemDataArray == NULL) {
			puts("dat err");
			system("pause");
			return -1;
		}
		free(itemDataString);
	}

	PROG_BEGIN:
	printf("Working... %d\n", currentMatchId);

	//init
	if (1) {
		memset(brawlerBought, -1, 10);
		memset(championPlayed, -1, 10);
		memset(wonGame, -1, 10);
		memset(dmgDealt, -1, 10);
		memset(dmgTaken, -1, 10);
		for (int i = 0; i < 10; i++) 
			memset(itemsBought[i], -1, 10);
	}

	//get matchId and form riot api data URL
	if (1) {
		//get match id
		long long matchId = 0;
		matchId = matchIdArray->u.array.values[currentMatchId]->u.integer;

		//turn it into a string
		char matchIdString[32];
		snprintf(matchIdString, 32, "%d", matchId);
		//printf("id: / %s /\n", matchIdString);

		//form URL
		strcpy(matchDataURI, "https://na.api.pvp.net/api/lol/na/v2.2/match/");
		strcat(matchDataURI, matchIdString);
		strcat(matchDataURI, "?includeTimeline=true&api_key=" API_KEY);
	}

	//delete the temp match data file and open it for appendage
	if (1) {
		fopen_s(&matchDataFileStream, TEMP_DATA_FILE, "w"); //delete
		if (matchDataFileStream == NULL) {
			puts("Could not open \"" TEMP_DATA_FILE "\"!");
			system("pause");
			return -1;
		}
		freopen_s(&matchDataFileStream, TEMP_DATA_FILE, "ab", matchDataFileStream); //append raw binary data
	}

	//start curl and download the data into the temp match data file
	if (1) {
		tempFileStream = matchDataFileStream;
		CURL *cURLHandle = curl_easy_init();

		curl_easy_setopt(cURLHandle, CURLOPT_URL, matchDataURI);
		curl_easy_setopt(cURLHandle, CURLOPT_WRITEFUNCTION, write_data);

		curl_easy_setopt(cURLHandle, CURLOPT_SSL_VERIFYHOST, 0L);
		curl_easy_setopt(cURLHandle, CURLOPT_SSL_VERIFYPEER, 0L);

		//curl_easy_setopt(cURLHandle, CURLOPT_VERBOSE, 1L); //for debugging

		CURLcode success = curl_easy_perform(cURLHandle);
		curl_easy_cleanup(cURLHandle);

		if (success != CURLE_OK) {
			printf("cURL error\n");
			system("pause");
			return -1;
		}//else printf("Downloaded \n\t\"%s\"\n\nInto \n\t\"" TEMP_DATA_FILE "\"\n", matchDataURI);
	}

	//parse the file that was just downloaded
	if (1) {
		char *matchDataString = 0;
		long length;
		matchDataFileStream = freopen(TEMP_DATA_FILE, "rb", matchDataFileStream);

		if (matchDataFileStream == NULL) {
			puts("Could not open \"" TEMP_DATA_FILE "\"!\n");
			system("pause");
			return -1;
		}

		fseek(matchDataFileStream, 0, SEEK_END);
		length = ftell(matchDataFileStream);
		fseek(matchDataFileStream, 0, SEEK_SET);
		matchDataString = malloc(length);
		fread(matchDataString, 1, length, matchDataFileStream);
		fclose(matchDataFileStream);

		if (strstr(matchDataString, "Rate limit exceeded")) {
			puts("Request limit exceeded...\n Retrying in 5 secs...\n");
			Sleep(5000);
			goto PROG_BEGIN;
		}

		matchData = json_parse(
			matchDataString,
			length
			);

		if (matchData == NULL) {
			printf("%s\n Error: no match data---\n");
			if (strstr(matchDataString, "HTTP ERROR 429")) {
				puts("Request limit exceeded...\n Retrying in 10 secs...\n");
				puts("10");
				Sleep(2000);
				puts("8");
				Sleep(2000);
				puts("6");
				Sleep(2000);
				puts("4");
				Sleep(2000);
				puts("2");
				Sleep(1000);
				puts("1");
				Sleep(1000);
				goto PROG_BEGIN;
			}else {
				printf("Unknown error. Retrying program after match #%d", currentMatchId);
				goto PROG_BEGIN;
			}
		}
		free(matchDataString);
	}

	//find the participant data and the timeline
	if (1) {
		for (int i = 0; i < matchData->u.object.length; i++) {
			if (!strcmp(matchData->u.object.values[i].name, "participants")) {
				participants = matchData->u.object.values[i].value;
				//printf("participants located @ %d\n", i);
				break;
			}
		}
		if (participants == NULL) {
			puts("Could not find participants!");
			system("pause");
			return -1;
		}

		for (int i = 0; i < matchData->u.object.length; i++) {
			if (!strcmp(matchData->u.object.values[i].name, "timeline")) {
				timeline = matchData->u.object.values[i].value->u.object.values[0].value;
				//printf("timeline located @ %d\n", i);
				break;
			}
		}
		if (timeline == NULL) {
			puts("Could not find timeline!");
			system("pause");
			return -1;
		}
	}

	//find what champion each participant played/if they won or not/which items they ended with
	if (1) {
		if (participants->u.array.length != 10) {
			printf("10 players were not present in match #%d! %d were. Retrying match...", currentMatchId, participants->u.array.length);
			goto PROG_BEGIN;
		}

		//for each participant
		for (int i = 0; i < 10; i++) {

			//for every piece of data about that participant
			for (int j = 0; j < participants->u.array.values[i]->u.object.length; j++) {
				//if this piece of data is the champion ID, save it
				if (!strcmp(participants->u.array.values[i]->u.object.values[j].name, "championId")) {
					//                  participants->      participant->        championId.value
					championPlayed[i] = participants->u.array.values[i]->u.object.values[j].value->u.integer;
					break; //next participant
				}
			}

			//for every piece of data about that participant
			for (int j = 0; j < participants->u.array.values[i]->u.object.length; j++) {
				//if this piece of data is about stats,
				if (!strcmp(participants->u.array.values[i]->u.object.values[j].name, "stats")) {
					for (int k = 0; k < participants->u.array.values[i]->u.object.values[j].value->u.object.length; k++) {
						//          participants        participant               stats                      stat.name
						if (!strcmp(participants->u.array.values[i]->u.object.values[j].value->u.object.values[k].name, "item0")) {
							
							//the next 5 are the other items, save all
							for (int l = 0; l < 6; l++) 
								itemsBought[i][l] = participants->u.array.values[i]->u.object.values[j].value->u.object.values[k + l].value->u.integer;
						}

					}
				}
			}

			//for every piece of data about that participant
			for (int j = 0; j < participants->u.array.values[i]->u.object.length; j++) {
				//if this piece of data is about stats,
				if (!strcmp(participants->u.array.values[i]->u.object.values[j].name, "stats")) {
					for (int k = 0; k < participants->u.array.values[i]->u.object.values[j].value->u.object.length; k++) {
						//          participants        participant               stats                      stat.name
						if (!strcmp(participants->u.array.values[i]->u.object.values[j].value->u.object.values[k].name, "totalDamageDealt")) {

							dmgDealt[i] = participants->u.array.values[i]->u.object.values[j].value->u.object.values[k].value->u.integer;
						}
						
					}
				}
			}

			//for every piece of data about that participant
			for (int j = 0; j < participants->u.array.values[i]->u.object.length; j++) {
				//if this piece of data is about stats,
				if (!strcmp(participants->u.array.values[i]->u.object.values[j].name, "stats")) {
					for (int k = 0; k < participants->u.array.values[i]->u.object.values[j].value->u.object.length; k++) {
						//          participants        participant               stats                      stat.name
						if (!strcmp(participants->u.array.values[i]->u.object.values[j].value->u.object.values[k].name, "totalDamageTaken")) {

							dmgTaken[i] = participants->u.array.values[i]->u.object.values[j].value->u.object.values[k].value->u.integer;
						}

					}
				}
			}

			//for every piece of data about that participant
			for (int j = 0; j < participants->u.array.values[i]->u.object.length; j++) {
				//if this piece of data is about items,
				if (!strcmp(participants->u.array.values[i]->u.object.values[j].name, "stats")) {
					for (int k = 0; k < participants->u.array.values[i]->u.object.values[j].value->u.object.length; k++) {
						//          participants        participant               stats                      stat.name
						if (!strcmp(participants->u.array.values[i]->u.object.values[j].value->u.object.values[k].name, "winner")) {
							wonGame[i] = participants->u.array.values[i]->u.object.values[j].value->u.object.values[k].value->u.boolean;
						}

					}
				}
			}

		}
	}

	//find which brawler each participant bought (searches throught every item bought in the game bc brawlers dont go into inventory)
	if (1) {
		//for every set of info in timeline
		for (int i = 0; i < timeline->u.array.length; i++) {

			//for every piece of info in this set, preferably Frame
			for (int j = 0; j < timeline->u.array.values[i]->u.object.length; j++) {

				//if this info set is Frame, it will have the data set "events". check for that
				if (!strcmp(timeline->u.array.values[i]->u.object.values[j].name, "events")) {
					json_value *event = timeline->u.array.values[i]->u.object.values[j].value;

					//for every data packet from the set of events (in the set Frame, (in the set timeline))
					for (int k = 0; k < event->u.array.length; k++) {

						//data for the current participant that im looking at
						//i dont know who the participant is yet, but that data will be collected, and noted
						int itemBought = -1; //more of a status than an ID
						int brawlerBought_ = -1; //ID
						int currentParticipant = -1; //ID

						//collect neccesary data
						if (1) {
							//for every descriptor in this data packet
							for (int l = 0; l < event->u.array.values[k]->u.object.length; l++) {
								//if we're looking at the event type
								if (!strcmp(event->u.array.values[k]->u.object.values[l].name, "eventType")) {

									if (!strcmp(event->u.array.values[k]->u.object.values[l].value->u.string.ptr, "ITEM_PURCHASED"))
										itemBought = 1;

									if (!strcmp(event->u.array.values[k]->u.object.values[l].value->u.string.ptr, "ITEM_SOLD"))
										itemBought = 2;

									if (!strcmp(event->u.array.values[k]->u.object.values[l].value->u.string.ptr, "ITEM_UNDO"))
										itemBought = 3;

									if (!strcmp(event->u.array.values[k]->u.object.values[l].value->u.string.ptr, "ITEM_DESTROYED"))
										itemBought = 4;

								}
							}

							//for every descriptor in this data packet
							for (int l = 0; l < event->u.array.values[k]->u.object.length; l++) {

								//if we're looking at the participant id
								if (!strcmp(event->u.array.values[k]->u.object.values[l].name, "participantId")) {

									currentParticipant = event->u.array.values[k]->u.object.values[l].value->u.integer - 1;
								}
							}

							//for every descriptor in this data packet
							for (int l = 0; l < event->u.array.values[k]->u.object.length; l++) {

								//if were looking at the item id
								if (!strcmp(event->u.array.values[k]->u.object.values[l].name, "itemId")) {

									//if the itemid is one of a brawler, note that
									for (int m = 0; m < 4; m++) {
										if (event->u.array.values[k]->u.object.values[l].value->u.integer == brawlerItemIds[m]) {
											brawlerBought_ = m;
										}
									}
								}
							}
						}

						//if a brawler was bought
						if (brawlerBought_ != -1) {
							switch (itemBought) {
							case 1: //brawler bought
								brawlerBought[currentParticipant] = brawlerBought_;
								break;
							case 2: //brawler sold
								brawlerBought[currentParticipant] = -1;
								printf("participant %d sold  a %s\n", currentParticipant, brawlerNames[brawlerBought_]);
								break;
							case 3: //brawler undone
								brawlerBought[currentParticipant] = -1;
								printf("participant %d undid a %s\n", currentParticipant, brawlerNames[brawlerBought_]);
								break;
							case 4: //brawler destroyed: this happens when they buy it so no print...
								//brawlerBought[currentParticipant] = -1;
								//printf("participant %d destroyed a %s\n", currentParticipant, brawlerNames[brawlerBought_]);
								break;
							default:
								break;
							}
						}
						//processed one event in "events"
					}
					//processed "events", in Frame
				}
				//processed something that may or may not have been "events", in Frame
			}
			//processed all data in this data set
		}
		//processed all data sets in the timeline
		//ignored all but Frame, which contains "events"
	}

	//update data structure
	for (int i = 0; i < 10; i++) {
		//printf("participant #%d played champion #%d and bought a %s\n", i, championPlayed[i], brawlerNames[brawlerBought[i]]);

		outputData[championPlayed[i]].wins += wonGame[i];
		outputData[championPlayed[i]].totalDamageDealt += dmgDealt[i];
		outputData[championPlayed[i]].totalDamageTaken += dmgTaken[i];
		outputData[championPlayed[i]].picks++;


		//analyze items
		for (int j = 0; j < 6; j++) {

			if (itemsBought[i][j] < 8) continue;
			char itemIdString[32];
			//form url
			if (1) {
				//get item id
				long long itemId = itemsBought[i][j];

				//turn it into a string
				snprintf(itemIdString, 32, "%d", itemId);
				//printf("id: / %s /\n", matchIdString);
			}
			
			long long length = 0;
			json_value *itemObject;
			char* item = 0;
			int found = 0;

			//json-parser
			if (1) {

				//SEARCH FOR ITEM AND SET itemObject TO THAT ITEM'S ARRAY

				for (int k = 0; k < itemDataArray->u.object.length; k++) {
					if (!strcmp(itemDataArray->u.object.values[k].name, "data")) {
						for (int l = 0; l < itemDataArray->u.object.values[k].value->u.object.length; l++) {
							if (!strcmp(itemDataArray->u.object.values[k].value->u.object.values[l].name, itemIdString)) {
								itemObject = itemDataArray->u.object.values[k].value->u.object.values[l].value;
								found = 1;
								break;
							}
						}
					}
					if (found)break;
				}

				if (!found) {
					printf("Error: no item data.\n");
					system("pause");
					return -1;
				}
			}

			//find the desc and analyze it for its stats
			int descIndex = 0;
			for (int k = 0; k < itemObject->u.object.length; k++) {
				if (!strcmp(itemObject->u.object.values[k].name, "description")) {
					descIndex = k;
					break;
				}
			}

			int *stat_type = stat_tell(itemObject->u.object.values[descIndex].value->u.string.ptr);

			//update info
			outputData[championPlayed[i]].offensiveBuilds += stat_type[0];
			outputData[championPlayed[i]].defensiveBuilds += stat_type[1];

			if (brawlerBought[i] > -1 && brawlerBought[i] < 4) {
				outputBrawlerData[brawlerBought[i]].defensiveBuilds += stat_type[0];
				outputBrawlerData[brawlerBought[i]].offensiveBuilds += stat_type[1];
			}
			
		}
		
		switch (brawlerBought[i]) {
		case 0:
			outputData[championPlayed[i]].razorfinsBought++;
			break;
		case 1:
			outputData[championPlayed[i]].ironbacksBought++;
			break;
		case 2:
			outputData[championPlayed[i]].plundercrabsBought++;
			break;
		case 3:
			outputData[championPlayed[i]].ocklepodsBought++;
			break;
		default:
			printf("data anomaly: participant #%d bought brawler #%d (-1 == no brawler)\n", i, brawlerBought[i]);
			continue;
		}

		outputBrawlerData[brawlerBought[i]].wins += wonGame[i];
		outputBrawlerData[brawlerBought[i]].totalDamageDealtByBuyers += dmgDealt[i];
		outputBrawlerData[brawlerBought[i]].totalDamageTakenByBuyers += dmgTaken[i];
		outputBrawlerData[brawlerBought[i]].picks++;
		for (int j = 0; j < 6; j++)
			outputBrawlerData[brawlerBought[i]].itemsBought[itemsBought[i][j]]++;
		
	}
	
	//maintenance before starting again or exiting
	if (1) {
		//json_value_free(matchData);
		++currentMatchId;
	}
	
	//if all data has been processed, exit
	if (currentMatchId > 999) {
		exit(0);
	}

	goto PROG_BEGIN;

	return 0;
}
示例#6
0
文件: cast.cpp 项目: Adatan/vlc
/**
 * @brief Process a message received from the Chromecast
 * @param p_stream the sout_stream_t structure
 * @param msg the CastMessage to process
 * @return 0 if the message has been successfuly processed else -1
 */
static int processMessage(sout_stream_t *p_stream, const castchannel::CastMessage &msg)
{
    int i_ret = 0;
    sout_stream_sys_t *p_sys = p_stream->p_sys;
    std::string namespace_ = msg.namespace_();

    if (namespace_ == "urn:x-cast:com.google.cast.tp.deviceauth")
    {
        castchannel::DeviceAuthMessage authMessage;
        authMessage.ParseFromString(msg.payload_binary());

        if (authMessage.has_error())
        {
            msg_Err(p_stream, "Authentification error: %d", authMessage.error().error_type());
            i_ret = -1;
        }
        else if (!authMessage.has_response())
        {
            msg_Err(p_stream, "Authentification message has no response field");
            i_ret = -1;
        }
        else
        {
            vlc_mutex_locker locker(&p_sys->lock);
            p_sys->i_status = CHROMECAST_AUTHENTICATED;
            msgConnect(p_stream, "receiver-0");
            msgLaunch(p_stream);
        }
    }
    else if (namespace_ == "urn:x-cast:com.google.cast.tp.heartbeat")
    {
        json_value *p_data = json_parse(msg.payload_utf8().c_str());
        std::string type((*p_data)["type"]);

        if (type == "PING")
        {
            msg_Dbg(p_stream, "PING received from the Chromecast");
            msgPong(p_stream);
        }
        else if (type == "PONG")
        {
            msg_Dbg(p_stream, "PONG received from the Chromecast");
        }
        else
        {
            msg_Err(p_stream, "Heartbeat command not supported");
            i_ret = -1;
        }

        json_value_free(p_data);
    }
    else if (namespace_ == "urn:x-cast:com.google.cast.receiver")
    {
        json_value *p_data = json_parse(msg.payload_utf8().c_str());
        std::string type((*p_data)["type"]);

        if (type == "RECEIVER_STATUS")
        {
            json_value applications = (*p_data)["status"]["applications"];
            const json_value *p_app = NULL;
            for (unsigned i = 0; i < applications.u.array.length; ++i)
            {
                std::string appId(applications[i]["appId"]);
                if (appId == APP_ID)
                {
                    p_app = &applications[i];
                    vlc_mutex_lock(&p_sys->lock);
                    if (p_sys->appTransportId.empty())
                        p_sys->appTransportId = std::string(applications[i]["transportId"]);
                    vlc_mutex_unlock(&p_sys->lock);
                    break;
                }
            }

            vlc_mutex_lock(&p_sys->lock);
            if ( p_app )
            {
                if (!p_sys->appTransportId.empty()
                        && p_sys->i_status == CHROMECAST_AUTHENTICATED)
                {
                    p_sys->i_status = CHROMECAST_APP_STARTED;
                    msgConnect(p_stream, p_sys->appTransportId);
                    msgLoad(p_stream);
                    p_sys->i_status = CHROMECAST_MEDIA_LOAD_SENT;
                    vlc_cond_signal(&p_sys->loadCommandCond);
                }
            }
            else
            {
                switch(p_sys->i_status)
                {
                /* If the app is no longer present */
                case CHROMECAST_APP_STARTED:
                case CHROMECAST_MEDIA_LOAD_SENT:
                    msg_Warn(p_stream, "app is no longer present. closing");
                    msgClose(p_stream, p_sys->appTransportId);
                    p_sys->i_status = CHROMECAST_CONNECTION_DEAD;
                    // ft
                default:
                    break;
                }

            }
            vlc_mutex_unlock(&p_sys->lock);
        }
        else
        {
            msg_Err(p_stream, "Receiver command not supported: %s",
                    msg.payload_utf8().c_str());
            i_ret = -1;
        }

        json_value_free(p_data);
    }
    else if (namespace_ == "urn:x-cast:com.google.cast.media")
    {
        json_value *p_data = json_parse(msg.payload_utf8().c_str());
        std::string type((*p_data)["type"]);

        if (type == "MEDIA_STATUS")
        {
            json_value status = (*p_data)["status"];
            msg_Dbg(p_stream, "Player state: %s",
                    status[0]["playerState"].operator const char *());
        }
        else if (type == "LOAD_FAILED")
        {
            msg_Err(p_stream, "Media load failed");
            atomic_store(&p_sys->ab_error, true);
            msgClose(p_stream, p_sys->appTransportId);
            vlc_mutex_lock(&p_sys->lock);
            p_sys->i_status = CHROMECAST_CONNECTION_DEAD;
            vlc_mutex_unlock(&p_sys->lock);
        }
        else
        {
            msg_Err(p_stream, "Media command not supported: %s",
                    msg.payload_utf8().c_str());
            i_ret = -1;
        }

        json_value_free(p_data);
    }
    else if (namespace_ == "urn:x-cast:com.google.cast.tp.connection")
    {
        json_value *p_data = json_parse(msg.payload_utf8().c_str());
        std::string type((*p_data)["type"]);
        json_value_free(p_data);

        if (type == "CLOSE")
        {
            msg_Warn(p_stream, "received close message");
            vlc_mutex_lock(&p_sys->lock);
            p_sys->i_status = CHROMECAST_CONNECTION_DEAD;
            vlc_mutex_unlock(&p_sys->lock);
        }
    }
    else
    {
        msg_Err(p_stream, "Unknown namespace: %s", msg.namespace_().c_str());
        i_ret = -1;
    }

    return i_ret;
}
示例#7
0
void Vizi3DWorld::load( const std::string& name ) {

    // @see http://code.google.com/p/vjson
    FILE *fp = fopen( name.c_str(), "rb" );
    if ( !fp ) {
        throw "Can't open file '" + name + "'";
    }

    fseek( fp, 0, SEEK_END );
    const auto size = ftell( fp );
    fseek( fp, 0, SEEK_SET );

    block_allocator allocator( 1024 );
    char* source = (char*)allocator.malloc( size + 1 );
    fread( source, 1, size, fp );
    source[size] = 0;

    fclose(fp);

    char *errorPos = 0;
    char *errorDesc = 0;
    int errorLine = 0;
    json_value* root = json_parse(
        source,
        &errorPos, &errorDesc, &errorLine,
        &allocator
    );
    if ( !root ) {
        std::cerr << "Position: " << errorPos << std::endl;
        std::cerr << "Description: " << errorDesc << std::endl;
        std::cerr << "Line: " << errorLine << std::endl;
        throw "File corrupt.";
    }

    // Заполняем структуры из JSON-файла

    //std::cout <<  "Parse json-map:" << std::endl;
    for (json_value* itr = root->first_child; itr; itr = itr->next_sibling) {
        if ( itr->name ) {
            //std::cout << "    " << itr->name << std::endl;
        }

        if ( (std::string)itr->name == "name" ) {
            assert( itr->type == JSON_STRING );
            mAbout.name = (std::string)itr->string_value;
            continue;
        }

        if ( (std::string)itr->name == "scale" ) {
            assert( (itr->type == JSON_FLOAT) || (itr->type == JSON_INT) );
            mAbout.scale = (itr->type == JSON_FLOAT) ? itr->float_value : (float)itr->int_value;
            continue;
        }

        if ( (std::string)itr->name == "path-to-image" ) {
            assert( itr->type == JSON_OBJECT );
            for (json_value* child = itr->first_child; child; child = child->next_sibling) {
                assert( child->type == JSON_STRING );
                mAbout.pathToImage[ (std::string)child->name ] = (std::string)child->string_value;
            }
            assert( (mAbout.pathToImage.find( "form" ) != mAbout.pathToImage.cend())
                && (mAbout.pathToImage.find( "material" ) != mAbout.pathToImage.cend())
                && "Ждём как минимум путь к формам и материалам." );
            continue;
        }

        if ( boost::starts_with( (std::string)itr->name, "map-" ) ) {
            assert( itr->type == JSON_OBJECT );
            // В этом ключе хранится и название участка карты
            const std::string tinyMapName = parseTinyMapName( (std::string)itr->name);
            auto tm = mAbout.tinyMap.find( tinyMapName );
            assert( (tm == mAbout.tinyMap.cend()) && "Каждый участок карты должен обладать уникальным именем." );
            assert( (mAbout.scale > 0.0f) && "Масштаб 'scale' должен быть определён и определён до 'map-'." );
            mAbout.tinyMap[ tinyMapName ] = parseTinyMap( itr, mAbout.scale );
            continue;
        }

        if ( (std::string)itr->name == "note" ) {
            assert( itr->type == JSON_OBJECT );
            mAbout.noteMap = parseNoteMap( itr );
            continue;
        }

        /* - @example http://code.google.com/p/vjson
        switch ( itr->type ) {
            case JSON_ARRAY:
                printf( "start array\n" );
                break;
            case JSON_BOOL:
                printf(itr->int_value ? "true\n" : "false\n");
                break;
            case JSON_INT:
                printf("%d\n", itr->int_value);
                break;
            case JSON_FLOAT:
                printf("%f\n", itr->float_value);
                break;
            case JSON_NULL:
                printf("null\n");
                break;
            case JSON_OBJECT:
                printf( "start object\n" );
                break;
            case JSON_STRING:
                printf("\"%s\"\n", itr->string_value);
                break;
        }
        */
    }


    // Если в файле не декларирован пустой элемент (пробел),
    // исправляем это
    if ( mAbout.noteMap.find( ' ' ) == mAbout.noteMap.cend() ) {
        mAbout.noteMap[' '] = noteElement_t();
    }


    // Подготавливаем битовые образы для оптимизации отрисовки карты
    prepareVisualBitImage();


    // Инициализируем указатель для отрисовки
    drawItr = cbegin();
}
示例#8
0
static void test_json_fetch(void *p)
{
	struct JsonContext *ctx;
	struct JsonValue *list, *dict, *dict2, *obj;
	const char *json = "{\"intk\": 16, \"fk\": 1.1, \"sk\": \"qwe\", \"tk\": true, \"nk\": null, \"lst\":[], \"obj\": {}}";
	bool bval;
	const char *sval;
	size_t slen;
	int64_t ival;
	double fval;

	ctx = json_new_context(NULL, 128);
	tt_assert(ctx);
	dict = json_parse(ctx, json, strlen(json));
	tt_assert(dict);

	bval = false;
	tt_assert(json_dict_get_bool(dict, "tk", &bval)); tt_assert(bval == true);
	tt_assert(!json_dict_get_bool(dict, "nk", &bval)); tt_assert(bval == true);
	tt_assert(!json_dict_get_bool(dict, "missing", &bval)); tt_assert(bval == true);
	tt_assert(json_dict_get_opt_bool(dict, "nk", &bval)); tt_assert(bval == true);
	tt_assert(json_dict_get_opt_bool(dict, "missing", &bval)); tt_assert(bval == true);
	tt_assert(!json_dict_get_opt_bool(dict, "sk", &bval)); tt_assert(bval == true);

	ival = 8;
	tt_assert(json_dict_get_int(dict, "intk", &ival)); tt_assert(ival == 16);
	tt_assert(!json_dict_get_int(dict, "nk", &ival)); tt_assert(ival == 16);
	tt_assert(!json_dict_get_int(dict, "missing", &ival)); tt_assert(ival == 16);
	tt_assert(json_dict_get_opt_int(dict, "nk", &ival)); tt_assert(ival == 16);
	tt_assert(json_dict_get_opt_int(dict, "missing", &ival)); tt_assert(ival == 16);
	tt_assert(!json_dict_get_opt_int(dict, "sk", &ival)); tt_assert(ival == 16);

	fval = -9;
	tt_assert(json_dict_get_float(dict, "fk", &fval)); tt_assert(fval == 1.1);
	tt_assert(!json_dict_get_float(dict, "nk", &fval)); tt_assert(fval == 1.1);
	tt_assert(!json_dict_get_float(dict, "missing", &fval)); tt_assert(fval == 1.1);
	fval = -7;
	tt_assert(json_dict_get_opt_float(dict, "fk", &fval)); tt_assert(fval == 1.1);
	tt_assert(json_dict_get_opt_float(dict, "missing", &fval)); tt_assert(fval == 1.1);
	tt_assert(!json_dict_get_opt_float(dict, "obj", &fval)); tt_assert(fval == 1.1);

	sval = "x"; slen = 1;
	tt_assert(json_dict_get_string(dict, "sk", &sval, NULL)); str_check(sval, "qwe");
	tt_assert(json_dict_get_string(dict, "sk", &sval, &slen)); tt_assert(slen == 3);
	tt_assert(!json_dict_get_string(dict, "nk", &sval, &slen)); str_check(sval, "qwe");
	tt_assert(!json_dict_get_string(dict, "missing", &sval, NULL)); str_check(sval, "qwe");
	sval = "z"; slen = 1;
	tt_assert(json_dict_get_opt_string(dict, "sk", &sval, NULL)); str_check(sval, "qwe");
	tt_assert(json_dict_get_opt_string(dict, "sk", &sval, &slen)); tt_assert(slen == 3);
	tt_assert(json_dict_get_opt_string(dict, "missing", &sval, NULL)); str_check(sval, "qwe");
	tt_assert(!json_dict_get_opt_string(dict, "fk", &sval, NULL)); str_check(sval, "qwe");

	list = NULL;
	tt_assert(!json_dict_get_list(dict, "sk", &list)); tt_assert(list == NULL);
	tt_assert(json_dict_get_list(dict, "lst", &list)); tt_assert(list);
	tt_assert(json_value_type(list) == JSON_LIST);
	list = NULL;
	tt_assert(!json_dict_get_opt_list(dict, "fk", &list)); tt_assert(!list);
	tt_assert(json_dict_get_opt_list(dict, "lst", &list)); tt_assert(list);
	tt_assert(json_value_type(list) == JSON_LIST);
	tt_assert(json_dict_get_opt_list(dict, "nk", &list)); tt_assert(list);
	tt_assert(json_value_type(list) == JSON_LIST);

	dict2 = NULL;
	tt_assert(!json_dict_get_dict(dict, "sk", &dict2)); tt_assert(dict2 == NULL);
	tt_assert(json_dict_get_dict(dict, "obj", &dict2)); tt_assert(dict2);
	tt_assert(json_value_type(dict2) == JSON_DICT);
	dict2 = NULL;
	tt_assert(!json_dict_get_opt_dict(dict, "fk", &dict2)); tt_assert(!dict2);
	tt_assert(json_dict_get_opt_dict(dict, "obj", &dict2)); tt_assert(dict2);
	tt_assert(json_value_type(dict2) == JSON_DICT);
	tt_assert(json_dict_get_opt_dict(dict, "nk", &dict2)); tt_assert(dict2);
	tt_assert(json_value_type(dict2) == JSON_DICT);

	obj = NULL;
	tt_assert(!json_dict_get_value(dict, "missing", &obj)); tt_assert(obj == NULL);
	tt_assert(json_dict_get_value(dict, "nk", &obj));
	tt_assert(obj); tt_assert(json_value_type(obj) == JSON_NULL);
	tt_assert(json_dict_get_value(dict, "obj", &obj));
	tt_assert(obj); tt_assert(json_value_type(obj) == JSON_DICT);
end:
	json_free_context(ctx);
}
示例#9
0
static const char *simple_value(const char *json)
{
	struct JsonContext *ctx;
	struct JsonValue *obj;
	static char buf[128];
	const char *res;

	ctx = json_new_context(NULL, 128);
	obj = json_parse(ctx, json, strlen(json));
	if (!obj) {
		snprintf(buf, sizeof(buf), "EPARSE: %s", json_strerror(ctx));
		json_free_context(ctx);
		return buf;
	} else if (json_value_is_null(obj)) {
		res = "NULL";
	} else if (json_value_is_bool(obj)) {
		bool val;
		if (!json_value_as_bool(obj, &val)) {
			res = "EBOOL";
		} else {
			res = val ? "TRUE" : "FALSE";
		}
	} else if (json_value_is_int(obj)) {
		int64_t val;
		if (!json_value_as_int(obj, &val)) {
			res = "ELONG";
		} else {
			snprintf(buf, sizeof(buf), "INT:%lld", (long long)val);
			res = buf;
		}
	} else if (json_value_is_float(obj)) {
		double val;
		int i, j;
		if (!json_value_as_float(obj, &val)) {
			res = "EDBL";
		} else {
			snprintf(buf, sizeof(buf), "FLOAT:%.17g", val);
			for (i = 0; buf[i]; i++) {
				if (!buf[i]) break;
				if (buf[i] >= '0' && buf[i] <= '9') continue;
				if (buf[i] == '+' || buf[i] == '-') continue;
				if (buf[i] == 'e' || buf[i] == 'E') continue;
				if (buf[i] == '.') continue;
				if (buf[i] == ',') buf[i] = '.';
				else if (buf[i] & 0x80) {
					j = i;
					while (buf[j] & 0x80) j++;
					buf[i++] = '.';
					memmove(buf + i, buf + j, strlen(buf + j) + 1);
				}
			}
			res = buf;
		}
	} else if (json_value_is_string(obj)) {
		const char *val;
		if (!json_value_as_string(obj, &val, NULL)) {
			res = "ESTR";
		} else {
			snprintf(buf, sizeof(buf), "STR:%s", val);
			res = buf;
		}
	} else {
		res = "ENOSIMPLE";
	}
	json_free_context(ctx);
	return res;
}
示例#10
0
json_value *socket_nextjson(YAAMP_SOCKET *s, YAAMP_CLIENT *client)
{
	while(!strchr(s->buffer, '}') && s->buflen<YAAMP_SOCKET_BUFSIZE-1)
	{
	//	pthread_mutex_unlock(&s->mutex);

		int len = recv(s->sock, s->buffer+s->buflen, YAAMP_SOCKET_BUFSIZE-s->buflen-1, 0);
		if(len <= 0) return NULL;

		s->last_read = time(NULL);
		s->total_read += len;

		s->buflen += len;
		s->buffer[s->buflen] = 0;

//		if(client && client->logtraffic)
//			stratumlog("recv: %s\n", s->buffer);

	//	pthread_mutex_lock(&s->mutex);
	}

	char *p = strchr(s->buffer, '}');
	if(!p)
	{
		if(client)
			clientlog(client, "bad json");

		debuglog("%s\n", s->buffer);
		return NULL;
	}

	p++;

	char saved = *p;
	*p = 0;

	if(client && client->logtraffic)
		stratumlog("%s, %s, %s, %s, recv: %s\n", client->sock->ip, client->username, client->password, g_current_algo->name, s->buffer);

	int bytes = strlen(s->buffer);

	json_value *json = json_parse(s->buffer, bytes);
	if(!json)
	{
		if(client)
			clientlog(client, "bad json parse");

		debuglog("%s\n", s->buffer);
		return NULL;
	}

	*p = saved;
	while(*p && *p != '{')
		p++;

	if(*p == '{')
	{
		memmove(s->buffer, p, s->buflen - (p - s->buffer));

		s->buflen = s->buflen - (p - s->buffer);
		s->buffer[s->buflen] = 0;

//		if(client && client->logtraffic)
//			stratumlog("still: %s\n", s->buffer);
	}
	else
	{
		memset(s->buffer, 0, YAAMP_SOCKET_BUFSIZE);
		s->buflen = 0;
	}

	return json;
}
示例#11
0
static struct host
parseHost
(json_value *hostObj, int *ret)
{
  json_value *jName = json_find(hostObj, "name", json_string);
  json_value *jMac  = json_find(hostObj, "mac",  json_string);

  if ((NULL == jName) || (NULL == jMac))
    return (*ret = 1), (struct host) {0};

  struct host result = {
    .name       = utilStringDup(jName->u.string.ptr),
    .macAddress = utilStringDup(jMac->u.string.ptr)
  };

  return result;
}

static struct host *
parseHosts
(json_value *root, size_t *numHosts)
{
  json_value *jHosts = json_find(root, "hosts", json_array);
  if (NULL == jHosts)
    return NULL;

  const size_t numJHosts     = jHosts->u.array.length;
  struct host *result = calloc(numJHosts, sizeof(*result));

  for (size_t i=0; i<numJHosts; i++)
  {
    json_value *jHostObj = jHosts->u.array.values[i];

    int ret   = 0;
    result[i] = parseHost(jHostObj, &ret);
    
    if (ret)
    {
      free(result);
      return NULL;
    }
  }

  *numHosts = numJHosts;
  return result;
}

static struct resource
parseResource
(json_value *jResource, int *ret)
{
  json_value *jName = json_find(jResource, "name", json_string);
  json_value *jHost = json_find(jResource, "host", json_string);
  json_value *jVars = json_find(jResource, "vars", json_array);
  
  if ((NULL == jName) || (NULL == jHost) || (NULL == jVars))
    return (*ret = 1), (struct resource) {0};

  const size_t numVars = jVars->u.array.length;
  char **keyMap = calloc(numVars, sizeof(char *));
  char **valMap = calloc(numVars, sizeof(char *));

  for (size_t i=0; i<numVars; i++)
  {
    json_value *jVar = jVars->u.array.values[i];
    if (jVar->type != json_array)
      return (*ret = 1), (struct resource) {0};

    if (jVar->u.array.length != 2)
      return (*ret = 1), (struct resource) {0};

    json_value *jKey = jVar->u.array.values[0];
    json_value *jVal = jVar->u.array.values[1];

    if (jKey->type != json_string)
      return (*ret = 1), (struct resource) {0};

    if (jVal->type != json_string)
      return (*ret = 1), (struct resource) {0};

    keyMap[i] = utilStringDup(jKey->u.string.ptr);
    valMap[i] = utilStringDup(jVal->u.string.ptr);
  }

  struct resource result = {
    .name     = utilStringDup(jName->u.string.ptr),
    .host     = utilStringDup(jHost->u.string.ptr),
    .numVars  = numVars,
    .keyMap   = keyMap,
    .valMap   = valMap,
  };

  return result;
}

struct resource *
parseResources
(json_value *root, size_t *numResources)
{
  json_value *jResources = json_find(root, "resources", json_array);
  if (NULL == jResources)
    return NULL;

  const size_t numJResources  = jResources->u.array.length;
  struct resource *result     = calloc(numJResources, sizeof(*result));
  
  for (size_t i=0; i<numJResources; i++)
  {
    json_value *jResource = jResources->u.array.values[i];

    int ret       = 0;
    result[i]     = parseResource(jResource, &ret);
    result[i].id  = i;

    #if defined(CLUSTERD_BUILD)
      result[i].mutex = calloc(1, sizeof(pthread_mutex_t));
      result[i].inUse = calloc(1, sizeof(bool));
      pthread_mutex_init(result[i].mutex, NULL);
    #endif
  }

  *numResources = numJResources;
  return result;
}

configuration *
parseConfiguration
(void)
{
  char *jsonConfig = readFile(_configPath);
  if (NULL == jsonConfig)
  {
    fprintf(stderr, "Error: Unable to read configuration file\n");
    fprintf(stderr, "Does %s exist?\n", _configPath);
    return NULL;
  }

  json_value *root = json_parse(jsonConfig, strlen(jsonConfig));
  free(jsonConfig);
  if (NULL == root)
  {
    fprintf(stderr, "Error: Configuration file %s is malformed\n", _configPath);
    fprintf(stderr, "Unable to parse json\n");
    return NULL;
  }

  configuration *result = calloc(1, sizeof(configuration));
  result->hosts = parseHosts(root, &result->numHosts);
  if (NULL == result->hosts)
  {
    fprintf(stderr, "Error: Configuration file %s is malformed\n", _configPath);
    fprintf(stderr, "Unable to parse hosts\n");
    return NULL;
  }

  result->resources = parseResources(root, &result->numResources);
  if (NULL == result->hosts)
  {
    fprintf(stderr, "Error: Configuration file %s is malformed\n", _configPath);
    fprintf(stderr, "Unable to parse resources\n");
    return NULL;
  }

  json_value *jMaster = json_find(root, "master", json_string);
  if (NULL == jMaster)
  {
    fprintf(stderr, "Error: No master hostname set\n");
    return NULL;
  }

  if (jMaster->type != json_string)
  {
    fprintf(stderr, "Error: Master feild is not a string\n");
    return NULL;
  }

  result->master = utilStringDup(jMaster->u.string.ptr);

  json_value_free(root);

  return result;
}
示例#12
0
void CServerBrowser::LoadDDNet()
{
	// reset servers / countries
	m_NumDDNetCountries = 0;
	m_NumDDNetTypes = 0;

	// load ddnet server list
	IStorage *pStorage = Kernel()->RequestInterface<IStorage>();
	IOHANDLE File = pStorage->OpenFile("ddnet-servers.json", IOFLAG_READ, IStorage::TYPE_ALL);

	if(File)
	{
		char aBuf[4096*4];
		mem_zero(aBuf, sizeof(aBuf));

		io_read(File, aBuf, sizeof(aBuf));
		io_close(File);


		// parse JSON
		json_value *pCountries = json_parse(aBuf);

		if (pCountries && pCountries->type == json_array)
		{
			for (int i = 0; i < json_array_length(pCountries) && m_NumDDNetCountries < MAX_DDNET_COUNTRIES; i++)
			{
				// pSrv - { name, flagId, servers }
				const json_value *pSrv = json_array_get(pCountries, i);
				const json_value *pTypes = json_object_get(pSrv, "servers");
				const json_value *pName = json_object_get(pSrv, "name");
				const json_value *pFlagID = json_object_get(pSrv, "flagId");

				if (pSrv->type != json_object || pTypes->type != json_object || pName->type != json_string || pFlagID->type != json_integer)
				{
					dbg_msg("client_srvbrowse", "invalid attributes");
					continue;
				}

				// build structure
				CDDNetCountry *pCntr = &m_aDDNetCountries[m_NumDDNetCountries];

				pCntr->Reset();

				str_copy(pCntr->m_aName, json_string_get(pName), sizeof(pCntr->m_aName));
				pCntr->m_FlagID = json_int_get(pFlagID);

				// add country
				for (unsigned int t = 0; t < pTypes->u.object.length; t++)
				{
					const char *pType = pTypes->u.object.values[t].name;
					const json_value *pAddrs = pTypes->u.object.values[t].value;

					// add type
					if(json_array_length(pAddrs) > 0 && m_NumDDNetTypes < MAX_DDNET_TYPES)
					{
						int pos;
						for(pos = 0; pos < m_NumDDNetTypes; pos++)
						{
							if(!str_comp(m_aDDNetTypes[pos], pType))
								break;
						}
						if(pos == m_NumDDNetTypes)
						{
							str_copy(m_aDDNetTypes[m_NumDDNetTypes], pType, sizeof(m_aDDNetTypes[m_NumDDNetTypes]));
							m_NumDDNetTypes++;
						}
					}

					// add addresses
					for (int g = 0; g < json_array_length(pAddrs); g++, pCntr->m_NumServers++)
					{
						const json_value *pAddr = json_array_get(pAddrs, g);
						const char* pStr = json_string_get(pAddr);
						net_addr_from_str(&pCntr->m_aServers[pCntr->m_NumServers], pStr);
						str_copy(pCntr->m_aTypes[pCntr->m_NumServers], pType, sizeof(pCntr->m_aTypes[pCntr->m_NumServers]));
					}
				}

				m_NumDDNetCountries++;
			}
		}

		if (pCountries)
			json_value_free(pCountries);
	}
}
示例#13
0
    void TestSuite::TestWriter(void){
	   UnitTest::SetPrefix("Writing");
	   #ifdef JSON_LIBRARY	   
		  #define assertWrite(node, func, expected)\
			 {\
				json_char * _temp = func(node);\
				assertCStringSame(_temp, expected);\
				json_free(_temp);\
			 }
		  
		  JSONNODE * test1 = json_new(JSON_NODE);
		  assertWrite(test1, json_write, JSON_TEXT("{}"));
		  json_push_back(test1, json_new_a(JSON_TEXT("Hello"), JSON_TEXT("World")));
		  json_push_back(test1, json_new_b(JSON_TEXT("libjson"), true));
		  assertWrite(test1, json_write, JSON_TEXT("{\"Hello\":\"World\",\"libjson\":true}"));
		  #ifdef JSON_NEWLINE
			 assertEquals(JSON_NEWLINE, JSON_TEXT("\r\n"));
			 #ifdef JSON_INDENT
				assertEquals(JSON_INDENT, JSON_TEXT("    "))
				assertWrite(test1, json_write_formatted, JSON_TEXT("{\r\n    \"Hello\" : \"World\",\r\n    \"libjson\" : true\r\n}"));
			 #else
				assertWrite(test1, json_write_formatted, JSON_TEXT("{\r\n\t\"Hello\" : \"World\",\r\n\t\"libjson\" : true\r\n}"));
			 #endif
		  #else
			 #ifdef JSON_INDENT
				assertEquals(JSON_INDENT, JSON_TEXT("    "))
				assertWrite(test1, json_write_formatted, JSON_TEXT("{\n    \"Hello\" : \"World\",\n    \"libjson\" : true\n}"));
			 #else
				assertWrite(test1, json_write_formatted, JSON_TEXT("{\n\t\"Hello\" : \"World\",\n\t\"libjson\" : true\n}"));
			 #endif
		  #endif
		  json_delete(test1);
		  
		  JSONNODE * test2 = json_new(JSON_ARRAY);
		  assertWrite(test2, json_write, JSON_TEXT("[]"));
		  json_delete(test2);
	   
	   
	   JSONNODE * card = json_new(JSON_ARRAY);
	   
	   
	   
	   
	   JSONNODE *c = json_new(JSON_ARRAY);
	   json_push_back(c, json_new_a(JSON_TEXT("name"), JSON_TEXT("Entrée Audio Intégrée 1")));
	   json_push_back(c, json_new_i(NULL, 0));
	   json_push_back(card, c);
	   #ifdef JSON_UNICODE
		  assertWrite(card, json_write, JSON_TEXT("[[\"Entr\\u00E9e Audio Int\\u00E9gr\\u00E9e 1\",0]]"))
		  JSONNODE * ass = json_parse(JSON_TEXT("[[\"Entr\\u00E9e Audio Int\\u00E9gr\\u00E9e 1\",0]]"));
		  JSONNODE * item = json_at(json_at(ass, 0), 0);
		  assertWrite(item, json_as_string, JSON_TEXT("Entrée Audio Intégrée 1"));
	   #else
		  assertWrite(card, json_write, JSON_TEXT("[[\"Entr\\u00C3\\u00A9e Audio Int\\u00C3\\u00A9gr\\u00C3\\u00A9e 1\",0]]"))
		  JSONNODE * ass = json_parse(JSON_TEXT("[[\"Entr\\u00C3\\u00A9e Audio Int\\u00C3\\u00A9gr\\u00C3\\u00A9e 1\",0]]"));
		  JSONNODE * item = json_at(json_at(ass, 0), 0);
		  assertWrite(item, json_as_string, JSON_TEXT("Entrée Audio Intégrée 1"));
	   #endif
	   json_delete(card);
	   json_delete(ass);
	   
	   
	   
		  
		  #ifdef JSON_COMMENTS
			 JSONNODE * test3 = json_new(JSON_NODE);
			 json_push_back(test3, json_new_a(JSON_TEXT("Hi"), JSON_TEXT("There")));
			 json_push_back(test3, json_new_a(JSON_TEXT("Hello"), JSON_TEXT("World")));
			 json_set_comment(json_at(test3, 0), JSON_TEXT("Testing stuff"));
			 json_set_comment(json_at(test3, 1), JSON_TEXT("Multi\r\nLine\nUnix and Windows"));
			 assertWrite(test3, json_write, JSON_TEXT("{\"Hi\":\"There\",\"Hello\":\"World\"}"));
			 #if !defined( JSON_INDENT) && !defined(JSON_NEWLINE)
				#ifdef JSON_WRITE_BASH_COMMENTS
				    assertWrite(test3, json_write_formatted, JSON_TEXT("{\n\t\n\t#Testing stuff\n\t\"Hi\" : \"There\",\n\t\n\t#Multi\n\t#Line\n\t#Unix and Windows\n\t\"Hello\" : \"World\"\n}"));
				#elif defined(JSON_WRITE_SINGLE_LINE_COMMENTS)
				    assertWrite(test3, json_write_formatted, JSON_TEXT("{\n\t\n\t//Testing stuff\n\t\"Hi\" : \"There\",\n\t\n\t//Multi\n\t//Line\n\t//Unix and Windows\n\t\"Hello\" : \"World\"\n}"));
				#else
				    assertWrite(test3, json_write_formatted, JSON_TEXT("{\n\t\n\t//Testing stuff\n\t\"Hi\" : \"There\",\n\t\n\t/*\n\t\tMulti\n\t\tLine\n\t\tUnix and Windows\n\t*/\n\t\"Hello\" : \"World\"\n}"));
				#endif
			 #endif
			 json_delete(test3);
		  #endif
		  
		  
	   #else
		  JSONNode test1(JSON_NODE);
		  assertEquals(test1.write(), JSON_TEXT("{}"));
		  test1.push_back(JSONNode(JSON_TEXT("Hello"), JSON_TEXT("World")));
		  test1.push_back(JSONNode(JSON_TEXT("libjson"), true));
		  assertEquals(test1.write(), JSON_TEXT("{\"Hello\":\"World\",\"libjson\":true}"));
		  #ifdef JSON_NEWLINE
			 assertEquals(JSON_NEWLINE, JSON_TEXT("\r\n"));
			 #ifdef JSON_INDENT
				assertEquals(JSON_INDENT, JSON_TEXT("    "))
				assertEquals(test1.write_formatted(), JSON_TEXT("{\r\n    \"Hello\" : \"World\",\r\n    \"libjson\" : true\r\n}"));
			 #else
				assertEquals(test1.write_formatted(), JSON_TEXT("{\r\n\t\"Hello\" : \"World\",\r\n\t\"libjson\" : true\r\n}"));
			 #endif
		  #else
			 #ifdef JSON_INDENT
				assertEquals(JSON_INDENT, JSON_TEXT("    "))
				assertEquals(test1.write_formatted(), JSON_TEXT("{\n    \"Hello\" : \"World\",\n    \"libjson\" : true\n}"));
			 #else
				assertEquals(test1.write_formatted(), JSON_TEXT("{\n\t\"Hello\" : \"World\",\n\t\"libjson\" : true\n}"));
			 #endif
		  #endif
		  
		  JSONNode test2(JSON_ARRAY);
		  assertEquals(test2.write(), JSON_TEXT("[]"));
		  
		  #ifdef JSON_COMMENTS
			 JSONNode test3(JSON_NODE);
			 test3.push_back(JSONNode(JSON_TEXT("Hi"), JSON_TEXT("There")));
			 test3.push_back(JSONNode(JSON_TEXT("Hello"), JSON_TEXT("World")));
			 test3[0].set_comment(JSON_TEXT("Testing stuff"));
			 test3[1].set_comment(JSON_TEXT("Multi\r\nLine\nUnix and Windows"));
			 assertEquals(test3.write(), JSON_TEXT("{\"Hi\":\"There\",\"Hello\":\"World\"}"));
			 #if !defined( JSON_INDENT) && !defined(JSON_NEWLINE)
				#ifdef JSON_WRITE_BASH_COMMENTS
				    assertEquals(test3.write_formatted(), JSON_TEXT("{\n\t\n\t#Testing stuff\n\t\"Hi\" : \"There\",\n\t\n\t#Multi\n\t#Line\n\t#Unix and Windows\n\t\"Hello\" : \"World\"\n}"));
				#elif defined(JSON_WRITE_SINGLE_LINE_COMMENTS)
				    assertEquals(test3.write_formatted(), JSON_TEXT("{\n\t\n\t//Testing stuff\n\t\"Hi\" : \"There\",\n\t\n\t//Multi\n\t//Line\n\t//Unix and Windows\n\t\"Hello\" : \"World\"\n}"));
				#else
				    assertEquals(test3.write_formatted(), JSON_TEXT("{\n\t\n\t//Testing stuff\n\t\"Hi\" : \"There\",\n\t\n\t/*\n\t\tMulti\n\t\tLine\n\t\tUnix and Windows\n\t*/\n\t\"Hello\" : \"World\"\n}"));
				#endif
			 #endif
			 
		  #endif
	   #endif
    }
static json_t *fan_put(struct rest_uri_param *param)
{
	json_t *req;
	json_t *TachoMeterThreshold;
	result_t rs = RESULT_OK;
	put_fan_t put_fan_info = { {0} };
	uint32 value;
	json_t *elem = NULL;
	json_t *obj = NULL;
	int32 i = 0;
	int32 array_size;
	int32 tzone_idx, fan_idx = 0;

	tzone_idx = get_asset_idx(param, "zone_id", MC_TYPE_TZONE);
	if (tzone_idx == -1) {
		HTTPD_ERR("get cooling zone index fail\n");
		return NULL;
	}

	fan_idx = get_asset_idx(param, "fan_id", MC_TYPE_FAN);
	if (fan_idx == -1) {
		HTTPD_ERR("get fan index fail\n");
		return NULL;
	}

	rs = libwrap_pre_put_fan(tzone_idx, fan_idx, &put_fan_info);
	if (rs != RESULT_OK) {
		HTTPD_ERR("fan pre put fail, result is %d\n", rs);
		return NULL;
	}

	req = json_parse(param->json_data);
	put_prepare_str(req, put_fan_info.descr, DESCRIPTION_LEN, RMM_JSON_DESC);
	put_prepare_str(req, put_fan_info.asset_tag, REST_ASSET_TAG_LEN, RMM_JSON_ASSET_TAG);
	TachoMeterThreshold = json_object_get(req, RMM_JSON_THRESHOLD);
	if (TachoMeterThreshold != NULL) {
		array_size = json_array_size(TachoMeterThreshold);
		for (i = 0; i < array_size; i++) {
			elem = NULL;
			elem = json_array_get(TachoMeterThreshold, i);
			if (elem == NULL) {
				HTTPD_ERR("tacho meter thresh get error\n");
				return NULL;
			}
			put_prepare_int(elem, &(put_fan_info.threshold.lower_non_critical), RMM_JSON_LOWER_NON_CRITICAL);
			put_prepare_int(elem, &(put_fan_info.threshold.upper_non_critical), RMM_JSON_UPPER_NON_CRITICAL);
			put_prepare_int(elem, &(put_fan_info.threshold.lower_critical), RMM_JSON_LOWER_CRITICAL);
			put_prepare_int(elem, &(put_fan_info.threshold.upper_critical), RMM_JSON_UPPER_CRITICAL);
		}
	}
	
	rs = libwrap_put_fan(tzone_idx, fan_idx, put_fan_info);
	if (rs != RESULT_OK) {
		HTTPD_ERR("fan put fail, result is %d\n", rs);
		return NULL;
	}
	json_free(req);

	int8 buff[128] = {};
	snprintf(buff, sizeof(buff), "%d", ((tzone_idx - 1) * MAX_PWM_NUM + fan_idx));
	rf_log(INFO, MSGFanUpdate, buff);
	return fan_get(param);
}
示例#15
0
文件: array.c 项目: qute/json
int
main (void) {
  const char *file = "test/fixtures/array.json";
  const char *src = NULL;
  json_value_t *arr = NULL;
  json_value_t *value = NULL;

  src = fs_read(file);
  assert(src);

  arr = json_parse(file, src);
  assert(arr);
  assert(arr->size);
  ok("json_parse");

  value = json_get(arr, "0");
  assert(value);
  assert(EQ("kinkajou", value->as.string));
  ok("json_get");

  value = json_get(arr, "1");
  assert(value);
  assert(EQ("bradley", value->as.string));
  ok("json_get");

  value = json_get(arr, "2");
  assert(value);
  assert(EQ("4", value->as.string));
  assert(4 == (int) value->as.number);
  ok("json_get");

  value = json_get(arr, "0");
  assert(value);
  ok("json_get");

  json_destroy(value);
  assert(0 == value->errno);
  assert(2 == arr->size);
  value = NULL;
  ok("json_destroy");

  value = json_get(arr, "0");
  assert(value);
  ok("json_get");
  assert(EQ("bradley", value->as.string));

  json_destroy(value);
  assert(0 == value->errno);
  assert(1 == arr->size);
  value = NULL;
  ok("json_destroy");

  value = json_get(arr, "0");
  assert(value);
  ok("json_get");
  assert(EQ("4", value->as.string));
  assert(4 == (int) value->as.number);

  json_destroy(value);
  assert(0 == value->errno);
  assert(0 == arr->size);
  value = NULL;
  ok("json_destroy");

  ok_done();
  return 0;
}
示例#16
0
static const char *test_errors(void) {
  /* clang-format off */
  static const char *invalid_tests[] = {
      "1",        "a:3",           "\x01",         "{:",
      " { 1",     "{a:\"\n\"}",    "{a:1x}",       "{a:1e}",
      "{a:.1}",   "{a:0.}",        "{a:0.e}",      "{a:0.e1}",
      "{a:0.1e}", "{a:\"\\u\" } ", "{a:\"\\yx\"}", "{a:\"\\u111r\"}",
      NULL};
  static const char *incomplete_tests[] = {"",
                                           " \r\n\t",
                                           "{",
                                           " { a",
                                           "{a:",
                                           "{a:\"",
                                           " { a : \"xx",
                                           "{a:12",
                                           "{a:\"\\uf",
                                           "{a:\"\\uff",
                                           "{a:\"\\ufff",
                                           "{a:\"\\uffff",
                                           "{a:\"\\uffff\"",
                                           "{a:\"\\uffff\" ,",
                                           "{a:n",
                                           "{a:nu",
                                           "{a:nul",
                                           "{a:null",
                                           NULL};
  /* clang-format on */
  static const struct {
    const char *str;
    int expected_len;
  } success_tests[] = {{"{}", 2},
                       /* 2, 3, 4 byte utf-8 chars */
                       {"{a:\"\xd0\xb1\xe3\x81\xaf\xf0\xa2\xb3\x82\"}", 15},
                       {"{a:\"\\u0006\"}", 12},
                       {" { } ", 4},
                       {"{a:1}", 5},
                       {"{a:1.23}", 8},
                       {"{a:1e23}", 8},
                       {"{a:1.23e2}", 10},
                       {"{a:-123}", 8},
                       {"{a:-1.3}", 8},
                       {"{a:-1.3e-2}", 11},
                       {"{a:\"\"}", 6},
                       {"{a:\" \\n\\t\\r\"}", 13},
                       {" {a:[1]} 123456", 8},
                       {" {a:[]} 123456", 7},
                       {" {a:[1,2]} 123456", 10},
                       {"{a:1,b:2} xxxx", 9},
                       {"{a:1,b:{},c:[{}]} xxxx", 17},
                       {"{a:true,b:[false,null]} xxxx", 23},
                       {"[1.23, 3, 5]", 12},
                       {"[13, {\"a\":\"hi there\"}, 5]", 25},
                       {NULL, 0}};
  const char *s1 =
      " { a: 1, b: \"hi there\", c: true, d: false, "
      " e : null, f: [ 1, -2, 3], g: { \"1\": [], h: [ 7 ] } } ";
  int i;

  ASSERT(json_parse(NULL, 0, NULL, 0) == JSON_STRING_INVALID);
  for (i = 0; invalid_tests[i] != NULL; i++) {
    ASSERT(json_parse(invalid_tests[i], strlen(invalid_tests[i]), NULL,
                      NULL) == JSON_STRING_INVALID);
  }

  for (i = 0; incomplete_tests[i] != NULL; i++) {
    ASSERT(json_parse(incomplete_tests[i], strlen(incomplete_tests[i]), NULL,
                      NULL) == JSON_STRING_INCOMPLETE);
  }

  for (i = 0; success_tests[i].str != NULL; i++) {
    ASSERT(json_parse(success_tests[i].str, strlen(success_tests[i].str), NULL,
                      NULL) == success_tests[i].expected_len);
  }

  ASSERT(json_parse("{}", 2, NULL, NULL) == 2);
  ASSERT(json_parse(s1, strlen(s1), NULL, 0) > 0);

  return NULL;
}
示例#17
0
int pv_set_json (struct sip_msg* msg,  pv_param_t* pvp, int flag ,
		pv_value_t* val)
{

	json_t * obj;
	enum json_tokener_error parse_status;


	if( expand_tag_list( msg, ((json_name *)pvp->pvn.u.dname)->tags ) < 0)
	{
		LM_ERR("Cannot expand variables in path\n");
		return -1;
	}

	/* delete value */
	if( val == NULL)
	{
		return pv_add_json(pvp,NULL);
	}


	/* If we want the value to be interpreted prepare the object */
	if( flag == COLONEQ_T )
	{

		if( ! (val->flags & PV_VAL_STR) )
		{
			LM_ERR("Trying to interpret a non-string value\n");
			return -1;
		}

		obj = json_parse( val->rs.s, val->rs.len,&parse_status);

		if (obj == NULL)
		{
			LM_ERR("Error parsing json: %s\n",
#if JSON_LIB_VERSION >= 10
				json_tokener_error_desc(parse_status)
#else
				json_tokener_errors[(unsigned long)obj]
#endif
			);

			pv_add_json(pvp, NULL);
			return -1;

		}

	}
	else
	{
		if( val->flags & PV_VAL_INT )
		{
			obj = json_object_new_int(val->ri);
		}
		else
		{
			obj = json_object_new_string_len( val->rs.s, val->rs.len);
		}

	}



	return pv_add_json(pvp,obj);
}
示例#18
0
/**
 * Called by serial_eventloop, this calls the relevant commands.
 *
 * This calls the next command in the stack. By default, the command
 * is cmd_main_menu.
 *
 * New in 12.17 onwards: we accept json-formatted commands as well. Those
 * commands are parsed & dispatched below.
 *
 * Important remark: the CLI does not support multiple commands in one
 * line. For instance { "get": "guid", "get": "rtc" } will not work.
 *
 * JSON commands are as follow:
 *
 * Settings not linked to setting keys
 * "set" {
 *      "rtc": integer (Unix timestamp)
 *      "devicetag": string (device tag)
 *      }
 *
 *  Get/set settings keys (Work in progress not implemented yet):
 * "setkey" { "name": string, "value": value }
 * "getkey": "name"
 *
 *  Getting values not linked to setting keys
 * "get":
 *    - "guid"
 *    - "rtc"
 *    - "devicetag"
 *    - "settings"
 *    - "cpm"
 *
 */
void serial_process_command(char *line) {

  JSONNODE *n = json_parse(line);
  if (n == NULL) {
    // Old style commands
    (*command_stack[command_stack_size-1])(line);
  } else {
    // Dispatch:
    int err = true;
    /////
    // get
    /////
    JSONNODE *cmd = json_get_nocase(n,"get");
    if (cmd != 0 && json_type(cmd) == JSON_STRING) {
      json_char *val = json_as_string(cmd);
      if (strcmp(val, "cpm") == 0) {
        err = false;
        cmd_cpm(0);
      } else
      if (strcmp(val, "guid") == 0) {
        err = false;
        cmd_guid(0);
      } else
      if (strcmp(val,"rtc") == 0) {
        err = false;
        cmd_getrtc();
      } else
      if (strcmp(val,"devicetag") == 0) {
        err = false;
        cmd_getdevicetag(0);
      } else
      if (strcmp(val, "settings") == 0) {
        err = false;
        cmd_keyvaldump(0);
      } else
      if (strcmp(val, "version") == 0) {
        err = false;
        cmd_version(0);
      } else
      if (strcmp(val,"logstatus") == 0) {
         err = false;
         cmd_logstatus(0);
      }
      json_free(val);
    }
    /////
    // set
    /////
    cmd = json_get_nocase(n,"set");
    if (cmd !=0 && json_type(cmd) == JSON_NODE) {
      // Find what set operation we wanted:
      JSONNODE *op = json_get_nocase(cmd, "devicetag");
      if (op != 0 && json_type(op) == JSON_STRING) {
        err = false;
        json_char *tag = json_as_string(op);
        flashstorage_keyval_set("DEVICETAG",tag);
        json_keyval("ok", "devicetag");
      }
      op = json_get_nocase(cmd, "rtc");
      if (op != 0 && json_type(op) == JSON_NUMBER) {
        err = false;
        uint32_t  time = json_as_int(op);
        if (time != 0) {
          realtime_set_unixtime(time);
          json_keyval("ok", "rtc");
        }
      }
    }
    if (err) {
      json_keyval("error", "unknown command");
    }
  }
  json_delete(n);
}
示例#19
0
  TEST_ASSERT(tokens[0].length == 0);
  TEST_ASSERT(tokens[0].child == 0);
  TEST_ASSERT(tokens[0].next == 0);
  return 0;
}

static int test_single_element(void)
{
  wchar_t input[] = L"[1]";
  size_t ntok = 2, i;
  struct json_token tokens[ntok];
  struct json_token expected[] = {
    {.type = JSON_ARRAY, .start = 0, .end = 2, .length=1, .child = 1, .next = 0},
    {.type = JSON_NUMBER, .start = 1, .end = 1, .length=0, .child = 0, .next = 0},
  };
  struct json_parser p = json_parse(input, tokens, ntok);
  TEST_ASSERT(p.error == JSONERR_NO_ERROR);
  TEST_ASSERT(p.tokenidx == ntok);
  TEST_ASSERT(p.textidx == sizeof(input)/sizeof(wchar_t) - 1);
  for (i = 0; i < ntok; i++) {
    TEST_ASSERT(tokens[i].type == expected[i].type);
    TEST_ASSERT(tokens[i].start == expected[i].start);
    TEST_ASSERT(tokens[i].end == expected[i].end);
    TEST_ASSERT(tokens[i].child == expected[i].child);
    TEST_ASSERT(tokens[i].next == expected[i].next);
  }
  return 0;
}

static int test_multiple_elements(void)
{
示例#20
0
ProjectStats *KickStats::GetProjectStats()
{
	
	JSONNODE *n = json_parse(m_sContent.c_str());

	if (n == NULL)
	{
		KickLog(L"Invalid JSON Node");
		return NULL;
	}

	//	{"project":{"id":375955643, "state_changed_at" : 1452521021, "state" : "live", "backers_count" : 239, "pledged" : "5307.0", "comments_count" : 6}}
	JSONNODE *n_pro = json_get_nocase(n, "project");

	if (n_pro == NULL && json_type(n_pro) != JSON_NODE)
	{
		KickLog(L"Invalid JSON structure (project not found)");
		return NULL;
	}

	JSONNODE *n_backers = json_get_nocase(n_pro, "backers_count");
	long backers = -1;

	if (n_backers == NULL)
	{
		KickLog(L"Invalid JSON structure (backers_count not found)");
		return NULL;
	}

	if (json_type(n_backers) == JSON_NUMBER)
	{
		backers = json_as_int(n_backers);
	}

	JSONNODE *n_comments = json_get_nocase(n_pro, "comments_count");
	long comments = -1;

	if (n_comments == NULL)
	{
		KickLog(L"Invalid JSON structure (comments_count not found)");
		return NULL;
	}

	if (json_type(n_comments) == JSON_NUMBER)
	{
		comments = json_as_int(n_comments);
	}

	JSONNODE *n_pledged = json_get_nocase(n_pro, "pledged");
	double pledged = -2.0;

	if (n_pledged == NULL)
	{
		KickLog(L"Invalid JSON structure (pledged not found)");
		return NULL;
	}

	if (json_type(n_pledged) == JSON_STRING)
	{
		pledged = atof(json_as_string(n_pledged));
	}


	ProjectStats *stats = new ProjectStats;
	stats->nBackers = backers;
	stats->nComments = comments;
	stats->fPledged = pledged;
	return stats;
}
示例#21
0
文件: pcp.c 项目: pgpool/pgpool2
static void
process_watchdog_info_response(PCPConnInfo * pcpConn, char *buf, int len)
{
	char	   *json_data = NULL;
	PCPWDClusterInfo *wd_cluster_info = NULL;
	int			clusterDataSize = 0;

	if (strcmp(buf, "CommandComplete") == 0)
	{
		int			tempVal;
		char	   *ptr;

		json_data = (char *) memchr(buf, '\0', len);
		if (json_data == NULL)
			goto INVALID_RESPONSE;
		json_data += 1;

		json_value *root;
		json_value *value;
		int			i,
					nodeCount;

		root = json_parse(json_data, len);

		/* The root node must be object */
		if (root == NULL || root->type != json_object)
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}

		if (json_get_int_value_for_key(root, "NodeCount", &nodeCount))
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}

		/* find the WatchdogNodes array */
		value = json_get_value_for_key(root, "WatchdogNodes");
		if (value == NULL)
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}
		if (value->type != json_array)
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}
		if (nodeCount != value->u.array.length)
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}

		/* create the cluster object */
		clusterDataSize = sizeof(PCPWDClusterInfo) + (sizeof(PCPWDNodeInfo) * nodeCount);
		wd_cluster_info = malloc(clusterDataSize);

		wd_cluster_info->nodeCount = nodeCount;

		if (json_get_int_value_for_key(root, "RemoteNodeCount", &wd_cluster_info->remoteNodeCount))
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}
		if (json_get_int_value_for_key(root, "QuorumStatus", &wd_cluster_info->quorumStatus))
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}
		if (json_get_int_value_for_key(root, "AliveNodeCount", &wd_cluster_info->aliveNodeCount))
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}
		if (json_get_int_value_for_key(root, "Escalated", &tempVal))
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}
		wd_cluster_info->escalated = tempVal == 0 ? false : true;

		ptr = json_get_string_value_for_key(root, "MasterNodeName");
		if (ptr == NULL)
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}
		strncpy(wd_cluster_info->masterNodeName, ptr, sizeof(wd_cluster_info->masterNodeName) - 1);

		ptr = json_get_string_value_for_key(root, "MasterHostName");
		if (ptr == NULL)
		{
			json_value_free(root);
			goto INVALID_RESPONSE;
		}
		strncpy(wd_cluster_info->masterHostName, ptr, sizeof(wd_cluster_info->masterHostName) - 1);

		/* Get watchdog nodes data */
		for (i = 0; i < nodeCount; i++)
		{
			char	   *ptr;
			json_value *nodeInfoValue = value->u.array.values[i];
			PCPWDNodeInfo *wdNodeInfo = &wd_cluster_info->nodeList[i];

			if (nodeInfoValue->type != json_object)
			{
				json_value_free(root);
				goto INVALID_RESPONSE;
			}

			if (json_get_int_value_for_key(nodeInfoValue, "ID", &wdNodeInfo->id))
			{
				json_value_free(root);
				goto INVALID_RESPONSE;
			}

			ptr = json_get_string_value_for_key(nodeInfoValue, "NodeName");
			if (ptr == NULL)
			{
				json_value_free(root);
				goto INVALID_RESPONSE;
			}
			strncpy(wdNodeInfo->nodeName, ptr, sizeof(wdNodeInfo->nodeName) - 1);

			ptr = json_get_string_value_for_key(nodeInfoValue, "HostName");
			if (ptr == NULL)
			{
				json_value_free(root);
				goto INVALID_RESPONSE;
			}
			strncpy(wdNodeInfo->hostName, ptr, sizeof(wdNodeInfo->hostName) - 1);

			ptr = json_get_string_value_for_key(nodeInfoValue, "DelegateIP");
			if (ptr == NULL)
			{
				json_value_free(root);
				goto INVALID_RESPONSE;
			}
			strncpy(wdNodeInfo->delegate_ip, ptr, sizeof(wdNodeInfo->delegate_ip) - 1);

			if (json_get_int_value_for_key(nodeInfoValue, "WdPort", &wdNodeInfo->wd_port))
			{
				json_value_free(root);
				goto INVALID_RESPONSE;
			}

			if (json_get_int_value_for_key(nodeInfoValue, "PgpoolPort", &wdNodeInfo->pgpool_port))
			{
				json_value_free(root);
				goto INVALID_RESPONSE;
			}

			if (json_get_int_value_for_key(nodeInfoValue, "State", &wdNodeInfo->state))
			{
				json_value_free(root);
				goto INVALID_RESPONSE;
			}

			ptr = json_get_string_value_for_key(nodeInfoValue, "StateName");
			if (ptr == NULL)
			{
				json_value_free(root);
				goto INVALID_RESPONSE;
			}
			strncpy(wdNodeInfo->stateName, ptr, sizeof(wdNodeInfo->stateName) - 1);

			if (json_get_int_value_for_key(nodeInfoValue, "Priority", &wdNodeInfo->wd_priority))
			{
				json_value_free(root);
				goto INVALID_RESPONSE;
			}

		}
		json_value_free(root);

		if (setNextResultBinaryData(pcpConn->pcpResInfo, (void *) wd_cluster_info, clusterDataSize, NULL) < 0)
			goto INVALID_RESPONSE;

		setCommandSuccessful(pcpConn);
	}
	else
	{
		pcp_internal_error(pcpConn,
						   "command failed with reason: \"%s\"\n", buf);
		setResultStatus(pcpConn, PCP_RES_BAD_RESPONSE);
	}
	return;

INVALID_RESPONSE:

	if (wd_cluster_info)
		pfree(wd_cluster_info);
	pcp_internal_error(pcpConn,
					   "command failed. invalid response\n");
	setResultStatus(pcpConn, PCP_RES_BAD_RESPONSE);
}
示例#22
0
文件: config.cpp 项目: chenbk85/tps5
int config_put_json(DB_OBJECT *object, unsigned char *json, size_t len)
{
	char *ptr;

	error_ptr = no_error;
	error_len = sizeof(no_error) - 1;

	if (json_parse(json, len, keys, KEYS_COUNT)) {

		unsigned char *err = json_get_error(json, len);

		error_buf[sizeof(error_buf) - 1] = '\0';
		strncpy((char *)error_buf, (char *)err, sizeof(error_buf) - 1);
		error_len = strlen((char *)error_buf);

		error_ptr = error_buf;

		json_free_error(err);

		return -1;
	}

	BLOB_RECORD *config = (BLOB_RECORD *)object->module_data;

	if ((config == NULL)||(object->module_data_size != sizeof(BLOB_RECORD))) {
		strncpy((char *)error_buf, "Invalid config blob", sizeof(error_buf) - 1);
		error_ptr = error_buf;
		error_len = 19;
		return -1;
	}

	for (int i = 0; i < KEYS_COUNT; i++) {
		switch (fields[i].type) {

		case VALUE_TYPE_NUMERIC:

			switch (fields[i].size) {
			case sizeof(unsigned char):
				*(unsigned char *)((unsigned char*)config + fields[i].offset) = keys[i].int_val;
				break;
			case sizeof(unsigned short):
				*(unsigned short *)((unsigned char*)config + fields[i].offset) = keys[i].int_val;
				break;
			case sizeof(unsigned int):
				*(unsigned int *)((unsigned char*)config + fields[i].offset) = keys[i].int_val;
				break;
			}

			break;

		case VALUE_TYPE_FLOAT:

			*(float *)((unsigned char*)config + fields[i].offset) = keys[i].float_val;

			break;

		case VALUE_TYPE_BOOL:

			*(bool *)((unsigned char*)config + fields[i].offset) = keys[i].bool_val;

			break;

		case VALUE_TYPE_STRING:

			ptr = (char*)config + fields[i].offset;

			ptr[fields[i].size - 1] = '\0';

			strncpy(ptr, keys[i].string_val.c_str(), fields[i].size - 1);

			break;

		case VALUE_TYPE_NULL:
		case VALUE_TYPE_OBJECT:
		case VALUE_TYPE_ARRAY:
			break;
		}
	}

	config->need_profile = true;
	config->timestamp = time(NULL);

	if (memcmp(config->fw, "default", 8)) {
		char *p = config->fw;
		while ((*p != '\0')&&((*p < '0')||(*p > '9')))
			p++;
		config->requested_fw_ver = strtoul(p, NULL, 10);
	}
	else
		config->requested_fw_ver = 0;

	if (api_db_update_object_blob(object) != 0) {

		error_buf[sizeof(error_buf) - 1] = '\0';
		strncpy((char *)error_buf, (char *)api_db_get_error(), sizeof(error_buf) - 1);
		error_len = strlen((char *)error_buf);
		error_ptr = error_buf;
				
		return -1;
	}

	return 0;
}
示例#23
0
文件: json.c 项目: xanpeng/snippets
int json_parser_pair(json_parser_t *parser, json_value_t *super, json_value_t *name, json_value_t *value) {
	int i;
	int c;
	int s;

	enum {
		status_first,
		status_next,
		status_begin,
		status_name,
		status_colon,
		status_value,
		status_end,
		status_ok
	};

	if (super->type != JSON_OBJECT)
		return JSON_PARSER_ERR;

	if (parser->off == super->off)
		s = status_first;
	else
		s = status_next;

	for (i = parser->off; i < parser->len; i++) {
		c = parser->buf[i];

		switch (s) {
		case status_ok:
			parser->off = i;
			return JSON_PARSER_OK;
		case status_end:
			parser->off = i;
			return JSON_PARSER_END;
		case status_first:
			switch (c) {
			CASE_BLANK:
				break;
			case '{':
				s = status_begin;
				break;
			default:
				return JSON_PARSER_ERR;
			}
			break;
		case status_next:
			switch (c) {
			CASE_BLANK:
				break;
			case '}':
				s = status_end;
				break;
			case ',':
				s = status_begin;
				break;
			default:
				return JSON_PARSER_ERR;
			}
			break;
		case status_begin:
			switch (c) {
			CASE_BLANK:
				break;
			case '\"':
				s = status_name;
				parser->off = i;
				break;
			case '}':
				s = status_end;
				break;
			default:
				return JSON_PARSER_ERR;
			}
			break;
		case status_name:
			if (json_parse_string(parser, super, name) != JSON_PARSER_OK)
				return JSON_PARSER_ERR;
			i = parser->off - 1; /* for next round */
			s = status_colon;
			break;
		case status_colon:
			switch (c) {
			CASE_BLANK:
				break;
			case ':':
				s = status_value;
				parser->off = i + 1;
				break;
			default:
				return JSON_PARSER_ERR;
			}
			break;
		case status_value:
			if (json_parse(parser, super, value) != JSON_PARSER_OK) {
				return JSON_PARSER_ERR;
			}
			i = parser->off - 1; /* for next round */
			s = status_ok;
			break;
		default:
			return JSON_PARSER_ERR;
		}
	}

	return JSON_PARSER_ERR;
}
示例#24
0
文件: main.c 项目: qute/json
int
main (int argc, char **argv) {
  json_value_t *value = NULL;
  json_value_t *root = NULL;
  char *filename = NULL;
  char *key = NULL;
  char *src = NULL;
  int i = 0;

#define usage() printf("usage: %s <file> [key]\n", argv[0]);

  if (argc < 2) {
    usage();
    return 1;
  }

  // parse opts
  for (i = 1; i < argc; ++i) {
    if (EQ(argv[i], "--each")) {
      each = 1;
    } else if (EQ(argv[i], "--stream")) {
      stream = 1;
    } else if (EQ(argv[i], "--help")) {
      usage();
      return 0;
    }
  }

  if (ferror(stdin)) {
    return 1;
  } else if (0 == isatty(0)) {
    filename = "<stdin>";
    tty = 1;
    if (argc > 1 && '-' != argv[1][0]) {
      key = argv[1];
    }
  } else {
    filename = argv[1];
    if (0 != fs_exists(filename)) {
      printf("E: not found - `%s'\n", filename);
      return 1;
    }

    src = fs_read(filename);
    if (NULL == src) {
      return 1;
    }

    if (argc > 2 && '-' !=  argv[2][0]) {
      key = argv[2];
    }
  }

  do {
    if (tty) {
      src = read_stdin();
    }

    if (NULL == src || 0 == strlen(src)) {
      break;
    }

    // proxy source if just streaming stdin
    // without a key lookup
    if (NULL == key && stream) {
      printf("%s", src);
      continue;
    }

    root = json_parse(filename, src);

    if (NULL == root) {
      return 1;
    } else if (root->errno) {
      json_perror(root);
      return 1;
    }

    if (NULL != key) {
      value = json_get(root, key);
      if (NULL == value) {
        return 1;
      }

      free(root);
      root = value;
    } else {
      value = root;
    }

    if (1 == each && JSON_ARRAY == value->type) {
      value = value->values[0];
      while (value) {
        printf("%s\n", json_stringify(value));
        value = value->next;
      }
    } else {
      printf("%s\n", json_stringify(value));
    }

    json_destroy(root);
    free(src);
    value = NULL;
    root = NULL;
    src = NULL;

  } while (tty);

  return 0;
}
示例#25
0
static void sanity(void)
{
	struct json *j = json_parse(tmpctx, "[]");
	json_tok_remove(&j->toks, j->toks, 0);
	assert(j);
}
void *GetStructureFromJSON( ULONG *descr, const char *jsondata )
{
	char tmpQuery[ 1024 ];
	void *firstObject = NULL;
	void *lastObject = NULL;
	
	DEBUG("[GetStructureFromJSON] Load\n");
	
	if( jsondata == NULL  )
	{
		ERROR("Cannot parse NULL!\n");
		return NULL;
	}
	
	if( descr == NULL  )
	{
		ERROR("Data description was not provided!\n");
		return NULL;
	}
	
	if( descr[ 0 ] != SQLT_TABNAME )
	{
		ERROR("SQLT_TABNAME was not provided!\n");
		return NULL;
	}
	
	INFO("Start\n");
	
	int j = 0;
	json_char* json;
	json_value* value;
	MinNode *node = NULL;
	
		//[{'ID'= '1' , 'Name'= 'testowa' , 'API'= '11' , 'Version'= '1' , 'Author'= 'stefanek' , 'Email'= '1' , 'Description'= '*****@*****.**' , 'PEGI'= '0' , 'DateCreated'= '18' , 'DateInstalled'= '2015' }]
	//json = (json_char*)"{ \"applications\" :  [  {\"ID\": \"1\" , \"Name\": \"testowa\" , \"API\": \"11\" , \"Version\": \"1\" , \"Author\": \"stefanek\" , \"Email\": \"1\" , \"Description\": \"[email protected]\" , \"PEGI\": \"0\" , \"DateCreated\": \"18\" , \"DateInstalled\": \"2015\" }] }";

	json = (json_char*)jsondata;
	
	//DEBUG("[GetStructureFromJSON] Before parse  -> '%s' \n", json );

	value = json_parse( json, strlen( json ) );

	if (value == NULL) 
	{
		ERROR("Cannot parse string to object\n");
		return NULL;
	}
	
	if( value->type == json_object || value->type == json_array )			// ''main object"
	{
		//DEBUG("OBJECT NAME = %s value array length %d\n", value->u.object.values[0].name, value->array.length );
		
		json_value* arrval;
		
		
		DEBUG("Parse arrval type %d value type %d \n", value->type, value->type );
		
		if( value->type == json_object )
		{
			void *data = calloc( 1, descr[ SQL_DATA_STRUCTURE_SIZE ] );
		
			UBYTE *strptr = (UBYTE *)data;	// pointer to structure to which will will insert data
			ULONG *dptr = &descr[ SQL_DATA_STRUCT_START ];		// first 2 entries inform about table and size, rest information provided is about columns
				
			unsigned int i;
			
			lastObject = data;
			
			for( i=0 ; i < value->u.object.length ; i++ )
			{
				//printf("------%d ---- %s\n", i, value->u.object.values[ i ].name );
			}
			
			//DEBUG("Found obejct\n");
			
			while( dptr[0] != SQLT_END )
			{
				switch( dptr[ 0 ] )
				{
					case SQLT_NODE:
					{
					}
					break;
					
					case SQLT_IDINT:	// primary key
					case SQLT_INT:
					{
						int retPos = -1;
						//DEBUG("FIND INT!\n");
						
						for( i = 0; i <  value->u.object.length; i++) 
						{
							//DEBUG("aaaaaaaaaaobject[%d].name = %s\n", i, locaval->u.object.values[i].name);
							if( strcmp( value->u.object.values[i].name, (char *) dptr[1] ) == 0 )
							{
								retPos = i;
							}
						}
						
						json_value*mval = NULL;
						if( retPos >= 0 )
						{
							mval = value->u.object.values[retPos].value;
						}
						
						if( retPos >= 0 && mval->type == json_integer )
						{
							//DEBUG("ENTRY FOUND %s  int val %d\n",(char *) dptr[ 1 ], mval->u.integer );
							memcpy( strptr + dptr[ 2 ], &(mval->u.integer), sizeof( int ) );
						}
					}
					break;
						
					case SQLT_STR:
					case SQLT_TIMESTAMP:
					{
						int retPos = -1;
						for( i = 0; i <  value->u.object.length; i++) 
						{
							//DEBUG("aaaaaaaaaaobject[%d].name = %s\n", i, value->u.object.values[i].name);
							if( strcmp( value->u.object.values[i].name, (char *)dptr[1] ) == 0 )
							{
								retPos = i;
							}
						}
						
						json_value*mval = NULL;
						
						if( retPos >= 0 )
						{
							mval = value->u.object.values[retPos].value;
						}
						
						if( retPos >= 0  && mval->type == json_string && mval->u.string.ptr != NULL )
						{
							//DEBUG("STRENTRY FOUND %s data %s\n", (char *)dptr[ 1 ], mval->u.string.ptr );
							
							// this is date
							if( strlen( mval->u.string.ptr ) == 19 && mval->u.string.ptr[ 5 ] == '-' && mval->u.string.ptr[ 8 ] == '-' )
							{
								char *ptr = NULL;
								struct tm ltm;
							
								//DEBUG("TIMESTAMP load\n");
							
								//ptr = strptime( row[ i ], "%C%y-%m-%d %H:%M:%S", &ltm );
								if( ptr != NULL )
								{
									// REMEMBER, data fix
								
									ltm.tm_year += 1900;
									ltm.tm_mon ++;
								
									memcpy( strptr+ dptr[ 2 ], &ltm, sizeof( struct tm) );
								
									//DEBUG("Year %d  month %d  day %d\n", ltm.tm_year, ltm.tm_mon, ltm.tm_mday );
								}
							}
							else		// this is string
							{
								char *tmpval = StringDuplicate( mval->u.string.ptr );
								memcpy( strptr+ dptr[ 2 ], &tmpval, sizeof( char *) );
							}
						}
					}
					break;
				}
				i++;
				dptr += 3;
			}
		}
		else if( value->type == json_array )		// object contain our objects
		{
			arrval = value;
			
			int length = value->u.array.length;
			int x;
			for (x = 0; x < length; x++) // get object from array
			{
				json_value*locaval = value->u.array.values[x]; 
				
				void *data = calloc( 1, descr[ SQL_DATA_STRUCTURE_SIZE ] );
				if( firstObject == NULL )
				{
					firstObject = data;
				}
		
				UBYTE *strptr = (UBYTE *)data;	// pointer to structure to which will will insert data
				ULONG *dptr = &descr[ SQL_DATA_STRUCT_START ];		// first 2 entries inform about table and size, rest information provided is about columns
				
				int intlength = locaval->u.object.length;
				int i;
				
				while( dptr[0] != SQLT_END )
				{
					switch( dptr[ 0 ] )
					{
						case SQLT_NODE:
						{
							//DEBUG("Node found\n");
							MinNode *locnode = (MinNode *)(data + dptr[ 2 ]);
							locnode->mln_Succ = (MinNode *)lastObject;
							
							//DEBUG("\n\nlastObject %x currobject %x\n\n", lastObject, data );
						}
						break;
					
						case SQLT_IDINT:	// primary key
						case SQLT_INT:
						{
							int retPos = -1;
							for( i = 0; i < intlength; i++) 
							{
								//DEBUG("aaaaaaaaaaobject[%d].name = %s\n", i, locaval->u.object.values[i].name);
								if( strcmp( locaval->u.object.values[i].name, (char *) dptr[1] ) == 0 )
								{
									retPos = i;
								}
							}
							json_value*mval = locaval->u.object.values[retPos].value;
							
							if( retPos >= 0 && mval->type == json_integer )
							{
								//DEBUG("ENTRY FOUND %s  int val %d\n",(char *) dptr[ 1 ], mval->u.integer );
								memcpy( strptr + dptr[ 2 ], &(mval->u.integer), sizeof( int ) );
							}
						}
						break;
						
						case SQLT_STR:
						case SQLT_TIMESTAMP:
						{
							int retPos = -1;
							for( i = 0; i < intlength; i++) 
							{
								//DEBUG("aaaaaaaaaaobject[%d].name = %s\n", i, locaval->u.object.values[i].name);
								if( strcmp( locaval->u.object.values[i].name, (char *)dptr[1] ) == 0 )
								{
									retPos = i;
								}
							}
							
							json_value*mval = locaval->u.object.values[retPos].value;
							
							if( retPos >= 0  && mval->type == json_string && mval->u.string.ptr != NULL )
							{
								//DEBUG("STRENTRY FOUND %s data %s\n", (char *)dptr[ 1 ], mval->u.string.ptr );
								
								// this is date
								if( strlen( mval->u.string.ptr ) == 19 && mval->u.string.ptr[ 5 ] == '-' && mval->u.string.ptr[ 8 ] == '-' )
								{
									char *ptr = NULL;
									struct tm ltm;
							
									//DEBUG("TIMESTAMP load\n");
							
									//ptr = strptime( row[ i ], "%C%y-%m-%d %H:%M:%S", &ltm );
									if( ptr != NULL )
									{
										// REMEMBER, data fix
								
										ltm.tm_year += 1900;
										ltm.tm_mon ++;
								
										memcpy( strptr+ dptr[ 2 ], &ltm, sizeof( struct tm) );
								
										//DEBUG("Year %d  month %d  day %d\n", ltm.tm_year, ltm.tm_mon, ltm.tm_mday );
									}
								}
								else		// this is string
								{
									char *tmpval = StringDuplicate( mval->u.string.ptr );
									memcpy( strptr+ dptr[ 2 ], &tmpval, sizeof( char *) );
								}
							}
						}
						break;
					}
					i++;
					dptr += 3;
				}
				
				lastObject = data;
			}
		}
	}
	firstObject = lastObject;

	json_value_free( value );
	
	return firstObject;
}
示例#27
0
POOL_CONFIG* get_pool_config_from_json(char* json_data, int data_len)
{
	int i;
	json_value *root = NULL;
	json_value *value = NULL;
	POOL_CONFIG *config = palloc0(sizeof(POOL_CONFIG));
	config->backend_desc = palloc0(sizeof(BackendDesc));

	root = json_parse(json_data,data_len);
	/* The root node must be object */
	if (root == NULL || root->type != json_object)
		goto ERROR_EXIT;

	if (json_get_int_value_for_key(root, "num_init_children", &config->num_init_children))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "listen_backlog_multiplier", &config->listen_backlog_multiplier))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "child_life_time", &config->child_life_time))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "connection_life_time", &config->connection_life_time))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "child_max_connections", &config->child_max_connections))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "client_idle_limit", &config->client_idle_limit))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "max_pool", &config->max_pool))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "replication_mode", &config->replication_mode))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "enable_pool_hba", &config->enable_pool_hba))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "load_balance_mode", &config->load_balance_mode))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "replication_stop_on_mismatch", &config->replication_stop_on_mismatch))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "failover_if_affected_tuples_mismatch", &config->failover_if_affected_tuples_mismatch))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "replicate_select", &config->replicate_select))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "master_slave_mode", &config->master_slave_mode))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "connection_cache", &config->connection_cache))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "health_check_timeout", &config->health_check_timeout))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "health_check_period", &config->health_check_period))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "health_check_max_retries", &config->health_check_max_retries))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "health_check_retry_delay", &config->health_check_retry_delay))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "fail_over_on_backend_error", &config->fail_over_on_backend_error))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "recovery_timeout", &config->recovery_timeout))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "search_primary_node_timeout", &config->search_primary_node_timeout))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "client_idle_limit_in_recovery", &config->client_idle_limit_in_recovery))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "insert_lock", &config->insert_lock))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "memory_cache_enabled", &config->memory_cache_enabled))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "use_watchdog", &config->use_watchdog))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "clear_memqcache_on_escalation", &config->clear_memqcache_on_escalation))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "wd_port", &config->wd_port))
		goto ERROR_EXIT;
	if (json_get_int_value_for_key(root, "wd_priority", &config->wd_priority))
		goto ERROR_EXIT;

	config->master_slave_sub_mode = json_get_string_value_for_key(root, "master_slave_sub_mode");
	if (config->master_slave_sub_mode == NULL)
		goto ERROR_EXIT;
	config->master_slave_sub_mode = pstrdup(config->master_slave_sub_mode);


	/* backend_desc array */
	value = json_get_value_for_key(root,"backend_desc");
	if (value == NULL || value->type != json_array)
		goto ERROR_EXIT;

	config->backend_desc->num_backends = value->u.array.length;
	for (i = 0; i < config->backend_desc->num_backends; i++)
	{
		json_value *arr_value = value->u.array.values[i];
		char *ptr;
		if (json_get_int_value_for_key(arr_value, "backend_port", &config->backend_desc->backend_info[i].backend_port))
			goto ERROR_EXIT;
		ptr = json_get_string_value_for_key(arr_value, "backend_hostname");
		if (ptr == NULL)
			goto ERROR_EXIT;
		strncpy(config->backend_desc->backend_info[i].backend_hostname, ptr,sizeof(config->backend_desc->backend_info[i].backend_hostname) -1);
	}

	/* wd_remote_nodes array */
	value = json_get_value_for_key(root,"wd_remote_nodes");
	if (value == NULL || value->type != json_array)
		goto ERROR_EXIT;
	
	config->wd_remote_nodes.num_wd = value->u.array.length;
	for (i = 0; i < config->wd_remote_nodes.num_wd; i++)
	{
		json_value *arr_value = value->u.array.values[i];
		char *ptr;
		if (json_get_int_value_for_key(arr_value, "wd_port", &config->wd_remote_nodes.wd_remote_node_info[i].wd_port))
			goto ERROR_EXIT;
		if (json_get_int_value_for_key(arr_value, "pgpool_port", &config->wd_remote_nodes.wd_remote_node_info[i].pgpool_port))
			goto ERROR_EXIT;
		ptr = json_get_string_value_for_key(arr_value, "hostname");
		if (ptr == NULL)
			goto ERROR_EXIT;
		strncpy(config->wd_remote_nodes.wd_remote_node_info[i].hostname, ptr,sizeof(config->wd_remote_nodes.wd_remote_node_info[i].hostname) -1);
	}

	json_value_free(root);
	return config;

ERROR_EXIT:
	if (root)
		json_value_free(root);
	if (config->backend_desc)
		pfree(config->backend_desc);
	if (config->master_slave_sub_mode)
		pfree(config->master_slave_sub_mode);
	pfree(config);
	return NULL;
}
示例#28
0
STATUS load_module_init(char *file_name)
{
	char tmp_dir[256];

	FILE *file;
	CONFIG_DATA_T *root;
	long len;
	char *data;
	UINT8	module_id;
	int  	flag=0;

	STATUS ret_all,ret = OK;

	printf(".........................start user module .....................\r\n\r\n");



	sprintf(tmp_dir,"%s/%s",CONFI_DIR,file_name);



	if((file=fopen(tmp_dir,"rb"))==NULL)
	{
		root =NULL;
		flag = 1;
	}
	else
	{
	
		fseek(file,0,SEEK_END);
		len=ftell(file);
		fseek(file,0,SEEK_SET);
		data=(char*)malloc(len+1);
		fread(data,1,len,file);
		fclose(file);
		flag = 0;

		root = json_parse(data);
	}

	
	for(module_id=NULL_MODULE;module_id<MODULE_NUM;module_id++)
	{
		if(usr_module_arr[module_id] ==NULL ||usr_module_arr[module_id]->name ==NULL \
			||usr_module_arr[module_id]->module_init ==NULL)
		{
			continue;
		}

		printf("Init %-38s    .........",usr_module_arr[module_id]->name);
		/*init ALL user  init  function*/
		if(usr_module_arr[module_id]->module_init !=NULL)
			ret = (*(usr_module_arr[module_id]->module_init))(root);

		printf("[ %s ] \r\n",ret==OK ? "OK":"fail");

		/*if load config error  default it*/
		if(ret !=OK && usr_module_arr[module_id]->module_default !=NULL)
			ret |=(*(usr_module_arr[module_id]->module_default))();

		ret_all |=ret;
		
		
	}

	
	json_delete(root);

	if(flag==0)
		free(data);

	//if(ret_all !=OK)
	//	save_module();
	
	return ret_all;
}
示例#29
0
/**
 * @brief Process a message received from the Chromecast
 * @param msg the CastMessage to process
 * @return 0 if the message has been successfuly processed else -1
 */
void intf_sys_t::processMessage(const castchannel::CastMessage &msg)
{
    const std::string & namespace_ = msg.namespace_();

#ifndef NDEBUG
    msg_Dbg(p_stream,"processMessage: %s->%s %s", namespace_.c_str(), msg.destination_id().c_str(), msg.payload_utf8().c_str());
#endif

    if (namespace_ == NAMESPACE_DEVICEAUTH)
    {
        castchannel::DeviceAuthMessage authMessage;
        authMessage.ParseFromString(msg.payload_binary());

        if (authMessage.has_error())
        {
            msg_Err(p_stream, "Authentification error: %d", authMessage.error().error_type());
        }
        else if (!authMessage.has_response())
        {
            msg_Err(p_stream, "Authentification message has no response field");
        }
        else
        {
            vlc_mutex_locker locker(&lock);
            setConnectionStatus(CHROMECAST_AUTHENTICATED);
            msgConnect(DEFAULT_CHOMECAST_RECEIVER);
            msgReceiverLaunchApp();
        }
    }
    else if (namespace_ == NAMESPACE_HEARTBEAT)
    {
        json_value *p_data = json_parse(msg.payload_utf8().c_str());
        std::string type((*p_data)["type"]);

        if (type == "PING")
        {
            msg_Dbg(p_stream, "PING received from the Chromecast");
            msgPong();
        }
        else if (type == "PONG")
        {
            msg_Dbg(p_stream, "PONG received from the Chromecast");
        }
        else
        {
            msg_Warn(p_stream, "Heartbeat command not supported: %s", type.c_str());
        }

        json_value_free(p_data);
    }
    else if (namespace_ == NAMESPACE_RECEIVER)
    {
        json_value *p_data = json_parse(msg.payload_utf8().c_str());
        std::string type((*p_data)["type"]);

        if (type == "RECEIVER_STATUS")
        {
            json_value applications = (*p_data)["status"]["applications"];
            const json_value *p_app = NULL;

            vlc_mutex_locker locker(&lock);
            for (unsigned i = 0; i < applications.u.array.length; ++i)
            {
                std::string appId(applications[i]["appId"]);
                if (appId == APP_ID)
                {
                    const char *pz_transportId = applications[i]["transportId"];
                    if (pz_transportId != NULL)
                    {
                        appTransportId = std::string(pz_transportId);
                        p_app = &applications[i];
                    }
                    break;
                }
            }

            if ( p_app )
            {
                if (!appTransportId.empty()
                        && getConnectionStatus() == CHROMECAST_AUTHENTICATED)
                {
                    msgConnect(appTransportId);
                    setConnectionStatus(CHROMECAST_APP_STARTED);
                    msgPlayerLoad();
                    setConnectionStatus(CHROMECAST_MEDIA_LOAD_SENT);
                    vlc_cond_signal(&loadCommandCond);
                }
            }
            else
            {
                switch(getConnectionStatus())
                {
                /* If the app is no longer present */
                case CHROMECAST_APP_STARTED:
                case CHROMECAST_MEDIA_LOAD_SENT:
                    msg_Warn(p_stream, "app is no longer present. closing");
                    msgReceiverClose(appTransportId);
                    setConnectionStatus(CHROMECAST_CONNECTION_DEAD);
                    break;

                case CHROMECAST_AUTHENTICATED:
                    msg_Dbg(p_stream, "Chromecast was running no app, launch media_app");
                    appTransportId = "";
                    msgReceiverLaunchApp();
                    break;

                default:
                    break;
                }

            }
        }
        else if (type == "LAUNCH_ERROR")
        {
            json_value reason = (*p_data)["reason"];
            msg_Err(p_stream, "Failed to start the MediaPlayer: %s",
                    (const char *)reason);
        }
        else
        {
            msg_Warn(p_stream, "Receiver command not supported: %s",
                    msg.payload_utf8().c_str());
        }

        json_value_free(p_data);
    }
    else if (namespace_ == NAMESPACE_MEDIA)
    {
        json_value *p_data = json_parse(msg.payload_utf8().c_str());
        std::string type((*p_data)["type"]);

        if (type == "MEDIA_STATUS")
        {
            json_value status = (*p_data)["status"];
            msg_Dbg(p_stream, "Player state: %s sessionId:%d",
                    status[0]["playerState"].operator const char *(),
                    (int)(json_int_t) status[0]["mediaSessionId"]);
        }
        else if (type == "LOAD_FAILED")
        {
            msg_Err(p_stream, "Media load failed");
            msgReceiverClose(appTransportId);
            vlc_mutex_locker locker(&lock);
            setConnectionStatus(CHROMECAST_CONNECTION_DEAD);
        }
        else if (type == "INVALID_REQUEST")
        {
            msg_Dbg(p_stream, "We sent an invalid request reason:%s", (*p_data)["reason"].operator const char *());
        }
        else
        {
            msg_Warn(p_stream, "Media command not supported: %s",
                    msg.payload_utf8().c_str());
        }

        json_value_free(p_data);
    }
    else if (namespace_ == NAMESPACE_CONNECTION)
    {
        json_value *p_data = json_parse(msg.payload_utf8().c_str());
        std::string type((*p_data)["type"]);
        json_value_free(p_data);

        if (type == "CLOSE")
        {
            msg_Warn(p_stream, "received close message");
            vlc_mutex_locker locker(&lock);
            setConnectionStatus(CHROMECAST_CONNECTION_DEAD);
        }
        else
        {
            msg_Warn(p_stream, "Connection command not supported: %s",
                    type.c_str());
        }
    }
    else
    {
        msg_Err(p_stream, "Unknown namespace: %s", msg.namespace_().c_str());
    }
}
示例#30
0
void SdkHandler::registFinished(char *bufferchar)
{
	CCLOG("in function:[%s], buff:[%s]", __FUNCTION__, bufferchar);
	
	
    int state = 0;
    int userId = 0;
    int flag = 0;
    const char* loginKey = NULL;
    JSONNODE *n = json_parse(bufferchar);
    if (n == NULL){
        return;
    }
    JSONNODE_ITERATOR i = json_begin(n);
    while (i != json_end(n)){
		CCLOG("Start Parse Json in [%s]", __FUNCTION__);
        if (*i == NULL){
            break;
        }
        
        // recursively call ourselves to dig deeper into the tree
        if (json_type(*i) == JSON_ARRAY || json_type(*i) == JSON_NODE){
            break;
        }
        
        // get the node name and value as a string
        json_char *node_name = json_name(*i);
        
        // find out where to store the values
        if (strcmp(node_name, "STATE") == 0){
            json_int_t node_value = json_as_int(*i);
            state = node_value;
        }
        else if (strcmp(node_name, "USER_ID") == 0){
            json_int_t node_value = json_as_int(*i);
            userId = node_value;
            
        }
        else if (strcmp(node_name, "LOGIN_KEY") == 0){
            json_char *node_value = json_as_string(*i);
            loginKey = node_value;
            
        }
        else if (strcmp(node_name, "ERROR_TYPE") == 0){
            json_int_t node_value = json_as_int(*i);
            flag = node_value;
            
        }
        // cleanup and increment the iterator
        json_free(node_name);
        ++i;
    }
	
	//这里做状态判定
	if (flag == 10)
	{
        SGNotificationCenter::sharedNotificationCenter()->postNotification(INVALID_INFO_TIP,new CCInteger(10),false);
		return ;
	}
	else if (flag == 11)
	{
        SGNotificationCenter::sharedNotificationCenter()->postNotification(INVALID_INFO_TIP,new CCInteger(11),false);
		return ;
	}
	else if (flag == 12)
	{
        SGNotificationCenter::sharedNotificationCenter()->postNotification(INVALID_INFO_TIP,new CCInteger(12),false);
		return ;
	}
	
	
	CCLOG("Json parse completed! in fun : [%s]", __FUNCTION__);
	
    SdkInfoData *sdkLoginData = new SdkInfoData();
    sdkLoginData->state = state;
    sdkLoginData->accountId = userId;
    sdkLoginData->flag = flag;
    sdkLoginData->loginKey = std::string(loginKey);
	sdkLoginData->userName = userName;
	sdkLoginData->password = password;
	sdkLoginData->isEx = true;
	
	
	CCLOG("####state:[%d]m accountId : [%d], flag : [%d], loginKey:[%s]####", state, userId, flag, loginKey);
    SGNotificationCenter::sharedNotificationCenter()->postNotification(REREGISTFLAG,sdkLoginData,false);

}