Example #1
0
static void runtest_encdec(const char *json_base_fn)
{
	char *json_fn = test_filename(json_base_fn);
	cJSON *tests = read_json(json_fn);
	assert((tests->type & 0xFF) == cJSON_Array);

	unsigned int idx;

	for (idx = 0; idx < cJSON_GetArraySize(tests); idx++) {

	    cJSON *test = cJSON_GetArrayItem(tests, idx);
	    assert((test->type & 0xFF) == cJSON_Array);
	    assert(cJSON_GetArraySize(test) == 2);

            cJSON *j_raw = cJSON_GetArrayItem(test, 0);
            cJSON *j_enc = cJSON_GetArrayItem(test, 1);
            assert((j_raw->type & 0xFF) == cJSON_String);
            assert((j_enc->type & 0xFF) == cJSON_String);

            test_encode(j_raw->valuestring,
                        j_enc->valuestring);
            test_decode(j_raw->valuestring,
                        j_enc->valuestring);
	}

	free(json_fn);
	cJSON_Delete(tests);
}
Example #2
0
 void JsonSchema::readItemAllOf(cJSON *allofValues, ItemsPtr item)
 {
     int size = cJSON_GetArraySize(allofValues);
     int index = 0;
     do
     {
         cJSON *childAllOf = cJSON_GetArrayItem(allofValues, index);
         cJSON *itemReference = cJSON_GetObjectItem(childAllOf, "$ref");
         if (itemReference)
         {
             readItemRef(itemReference, item);
         }
         cJSON *itemRequiredValues = cJSON_GetObjectItem(allofValues, "required");
         if (itemRequiredValues)
         {
             int len = cJSON_GetArraySize(itemRequiredValues);
             int idx = 0;
             do
             {
                 item->setRequiredValue(cJSON_GetArrayItem(itemRequiredValues, idx)->valuestring);
             }
             while ( ++idx < len);
         }
     }
     while ( ++index < size);
 }
int ret_value(cJSON *json, char ***dst){
    if(item_exist(json, "web"))return -1;
    cJSON *array = cJSON_GetObjectItem(json, "web");
    int size_1 = cJSON_GetArraySize(array);
    if(size_1 == 0)return -1;
    int i,j,size_2;
    cJSON *obj, *array_1;
    char *str;
    for(i=0;i<size_1;++i){
        obj = cJSON_GetArrayItem(array, i);
        if(item_exist(obj, "value")){
            memcpy(**(dst+i), "None", 5);
            **(*(dst+i)+1) = '\0';
            continue;
        }
        array_1 = cJSON_GetObjectItem(obj, "value");
        size_2 = cJSON_GetArraySize(array_1);
        if(size_2 == 0){
            memcpy(**(dst+i),"None",5);
        }
        else{
            for(j=0;j<size_2;++j){
                str = cJSON_GetArrayItem(array_1, j)->valuestring;
                memcpy(*(*(dst+i)+j), str, strlen(str)+1);
            }
            **(*(dst+i)+j) = '\0';
        }
    }
    ***(dst+i) = '\0';
    return 0;
}
Example #4
0
 void JsonSchema::readDefAllOf(cJSON *allofValues, DefinitionsPtr definition)
 {
     int size = cJSON_GetArraySize(allofValues);
     int index = 0;
     do
     {
         cJSON *childAllOf = cJSON_GetArrayItem(allofValues, index);
         cJSON *defReference = cJSON_GetObjectItem(childAllOf, "$ref");
         if (defReference)
         {
             readDefRef(defReference , definition);
         }
         cJSON *defRequiredValues = cJSON_GetObjectItem(allofValues, "required");
         if (defRequiredValues)
         {
             int len = cJSON_GetArraySize(defRequiredValues);
             int idx = 0;
             do
             {
                 definition->setRequiredValue(cJSON_GetArrayItem(defRequiredValues, idx)->valuestring);
             }
             while ( ++idx < len);
         }
     }
     while ( ++index < size);
 }
Example #5
0
/*
 * Set the opponents for the game
 * game: the gamestate to set the opponents for
 * players: cJSON representing the players at the table
 */
static
void SetGameOpponents(GameState *game, cJSON *players)
{
    int playing = 0;
    char *name;
    int initial_stack;
    int stack;
    int current_bet;
    bool folded;

    for (int i = 0; i < cJSON_GetArraySize(players) && i < MAX_OPPONENTS; i++)
    {
        cJSON *player = JSON_ARRAY_ELEM(players, i);
        name = JSON_STRING(player, "player_name");
        initial_stack = JSON_INT(player, "initial_stack");
        stack = JSON_INT(player, "stack");
        current_bet = JSON_INT(player, "current_bet");
        folded = JSON_INT(player, "folded");

        strncpy(game->opponents[i].name, name, MAX_NAME_LEN);
        game->opponents[i].initial_stack = initial_stack;
        game->opponents[i].stack = stack;
        game->opponents[i].current_bet = current_bet;
        game->opponents[i].folded = folded;

        if (!folded)
        {
            playing++;
        }
    }

    game->num_opponents = cJSON_GetArraySize(players);
    game->num_playing = playing;
}
Example #6
0
static void runtest_keys_valid(const char *json_base_fn)
{
	char *json_fn = test_filename(json_base_fn);
	cJSON *tests = read_json(json_fn);
	assert((tests->type & 0xFF) == cJSON_Array);

	unsigned int idx;

	for (idx = 0; idx < cJSON_GetArraySize(tests); idx++) {

	    cJSON *test = cJSON_GetArrayItem(tests, idx);
	    assert((test->type & 0xFF) == cJSON_Array);
	    assert(cJSON_GetArraySize(test) == 3);

		cJSON *j_base58 = cJSON_GetArrayItem(test, 0);
		cJSON *j_payload = cJSON_GetArrayItem(test, 1);
		assert((j_base58->type & 0xFF) == cJSON_String);
		assert((j_payload->type & 0xFF) == cJSON_String);

		cJSON *j_meta = cJSON_GetArrayItem(test, 2);
		assert((j_meta->type & 0xFF) == cJSON_Object);

		cJSON *j_addrtype = cJSON_GetObjectItem(j_meta, "addrType");
		assert(!j_addrtype || ((j_addrtype->type & 0xFF) == cJSON_String));

		cJSON *j_compress = cJSON_GetObjectItem(j_meta, "isCompressed");
		assert(!j_compress || ((j_compress->type & 0xFF) == cJSON_True) ||
		       ((j_compress->type & 0xFF) == cJSON_False));

		bool is_privkey = ((cJSON_GetObjectItem(j_meta, "isPrivkey")->type & 0xFF) == cJSON_True);
		bool is_testnet = ((cJSON_GetObjectItem(j_meta, "isTestnet")->type & 0xFF) == cJSON_True);

		if (is_privkey) {
			test_privkey_valid_enc(
			    j_base58->valuestring,
				hex2str(j_payload->valuestring),
				((j_compress->type & 0xFF) == cJSON_True),
				is_testnet);
			test_privkey_valid_dec(
				j_base58->valuestring,
				hex2str(j_payload->valuestring),
				((j_compress->type & 0xFF) == cJSON_True),
				is_testnet);
		} else {
			test_pubkey_valid_enc(
				j_base58->valuestring,
				hex2str(j_payload->valuestring),
				j_addrtype->valuestring,
				is_testnet);
			test_pubkey_valid_dec(
				j_base58->valuestring,
				hex2str(j_payload->valuestring),
				j_addrtype->valuestring,
				is_testnet);
		}
	}

	free(json_fn);
	cJSON_Delete(tests);
}
Example #7
0
/*-------------------------------------------------------------------
Function: GenerateOutData();
Purpose: 通过比较现有数据跟原有数据,产生要输出的字符串.
Parameters: 
Return: 0 --- successful, -1 --- failed
-------------------------------------------------------------------*/
int CRedWoodDataParse::GenerateOutData(void)
{
    int iRet = 0;

    if (!oldDataJson) 
        return GenerateOutDataFromJson(updatedDataJson);
    else {
        assert(updatedDataJson);

        cJSON* outJson = NULL;
        outJson = cJSON_Duplicate(updatedDataJson, 1);
        if (!outJson)
            return -1;

        cJSON* newJsonFixture = NULL;
        cJSON* oldJsonFixture = NULL;

        newJsonFixture = cJSON_GetObjectItem(outJson, "fixture");
        oldJsonFixture = cJSON_GetObjectItem(oldDataJson, "fixture");

        if (!newJsonFixture || !oldJsonFixture) {
            cJSON_Delete(outJson);
            return -1;
        }        

        int iDataLen = 0;
        iDataLen = cJSON_GetArraySize(newJsonFixture); 

        assert(iDataLen == cJSON_GetArraySize(oldJsonFixture));

        //比较 fixture 节点的 每个子节点,如果相同,则从输出中删除
        for (int i = iDataLen - 1; i >= 0; i--) {
            cJSON* oldJsonTemp = cJSON_GetArrayItem(oldJsonFixture, i);
            cJSON* newJsonTemp = cJSON_GetArrayItem(newJsonFixture, i);

            char* pOldDataTemp = cJSON_Print(oldJsonTemp);
            char* pNewDataTemp = cJSON_Print(newJsonTemp);

            if (strcmp(pOldDataTemp, pNewDataTemp) == 0)
                cJSON_DeleteItemFromArray(newJsonFixture, i);

            free(pOldDataTemp);
            free(pNewDataTemp);
        }

        //改变输出的数据个数
        if (iDataLen != cJSON_GetArraySize(newJsonFixture)) {
            iDataLen = cJSON_GetArraySize(newJsonFixture); 
            cJSON_ReplaceItemInObject(outJson, "data length", cJSON_CreateNumber(iDataLen));
        }

        //生成目标字符串,以便输出
        iRet = GenerateOutDataFromJson(outJson);
        cJSON_Delete(outJson);
    }

    return iRet;
}
Example #8
0
/**
 * @brief Help function. FC15, FC16 request handler
 *
 * @fc Function code 15 and 16 only.
 * @param handle Mbtcp handle.
 * @param req cJSON request object.
 * @return Modbus response string in JSON format.
 */
static char * mbtcp_multi_write_req(int fc, mbtcp_handle_s *handle, cJSON *req)
{
    BEGIN(enable_syslog);
    int addr = json_get_int(req, "addr");
    int len  = json_get_int(req, "len");
    int tid  = json_get_int(req, "tid");
    
    uint8_t *bits;      // FC15
    uint16_t *regs;     // FC16
    cJSON * data = NULL;
    int ret = 0;

    switch (fc)
    {
        case 15:
            // memory reset for variable length array
            bits = (uint8_t *) malloc(len * sizeof(uint8_t));
            memset(bits, 0, len * sizeof(uint8_t));
            // handle uint8_t array
            data = cJSON_GetObjectItem(req, "data");
            for (int i = 0 ; i < cJSON_GetArraySize(data) ; i++)
            {
                uint8_t subitem = cJSON_GetArrayItem(data, i)->valueint;
                bits[i] = subitem;
                LOG(enable_syslog, "[%d]=%d", i, bits[i]);
            }
            ret = modbus_write_bits(handle->ctx, addr, len, bits);
            free(bits);
            break;
        case 16:
            
            // memory reset for variable length array
            regs = (uint16_t *) malloc(len * sizeof(uint16_t));
            memset(regs, 0, len * sizeof(uint16_t));
            // handle uint16_t array
            data = cJSON_GetObjectItem(req, "data");
            for (int i = 0 ; i < cJSON_GetArraySize(data) ; i++)
            {
                uint16_t subitem = cJSON_GetArrayItem(data, i)->valueint;
                regs[i] = subitem;
                LOG(enable_syslog, "[%d]=%d", i, regs[i]);
            }
            ret = modbus_write_registers(handle->ctx, addr, len, regs);
            free(regs);
            break;
        default:
            return set_modbus_error_resp(tid, "Wrong function code");
    }

    if (ret < 0) 
    {
        return set_modbus_errno_resp(tid, handle, errno);
    } 
    else
    {
        return set_modbus_no_data_ok_resp(tid);         
    }
}
Example #9
0
void Conference::LoadList(){
	CListCtrl *conf= (CListCtrl*)GetDlgItem(IDC_CONFLIST);
	conf->DeleteAllItems();

	std::string header = "/oneworld/conf_list?api_token=";
	header+=((CmicrosipDlg*)GetParent())->getToken();
	CInternetSession session;
	CHttpConnection *pConnection = session.GetHttpConnection(_T("89.163.142.253"));
	char result[500];
	CString request(header.c_str());
	CHttpFile *pFile = pConnection->OpenRequest(1,request);
	if(!pFile->SendRequest())
		return;
	pFile->Read((void*)result,500);
	char* status = strchr(result,']'); //checking if data is receive and is parseable
	char* eom = strchr(result,'}');
#ifdef _DEBUG
	_cprintf("Size: %p, %p, %d\n",result, status, (status-result));
#endif
	if(status==NULL)
		result[eom-result+1]='\0';
	else if(status - result < 4998)
		result[status - result +2]='\0';
#ifdef _DEBUG
	_cprintf("Result: %s\n",result);
#endif

	cJSON *root = cJSON_Parse(result);
	cJSON *msg = cJSON_GetObjectItem(root,"msg");
	if((status==NULL && msg == NULL) || status-result >= 4999 )
		return;
	else if(status==NULL)
		return;
	cJSON *data = cJSON_GetObjectItem(root,"data");
	int size=cJSON_GetArraySize(root); 
	
#ifdef _DEBUG
	_cprintf("Size: %d\n",size);
#endif
	size=cJSON_GetArraySize(data); 
	
#ifdef _DEBUG
	_cprintf("Size: %d\n",size);
#endif
	for(int i=0;i<size;i++){
		cJSON* item= cJSON_GetArrayItem(data,i);
		CString confNum(cJSON_GetObjectItem(item,"confno")->valuestring);
		CString pin(cJSON_GetObjectItem(item,"pin")->valuestring);
#ifdef _DEBUG
		_cprintf("Item: %s\n",(CT2CA)confNum);
		_cprintf("Pin: %s\n",(CT2CA)pin);
#endif
		int index = conf->InsertItem(i, confNum);
		conf->SetItemText(index, 1, pin);
		//conf->SetItemData(i, &confNum);
	}
}
Example #10
0
/*
 * Set the card array to the given JSON array
 * cards: the int array of where to place the results
 * json: a JSON array of card strings
 * return: the number of cards in the array
 */
int GetCardArray(int *cards, cJSON *json)
{
    int i;

    for (i = 0; i < cJSON_GetArraySize(json); i++)
    {
        cards[i] = StringToCard(
                JSON_ARRAY_ELEM(json, i)->valuestring);
    }

    return cJSON_GetArraySize(json);
}
Example #11
0
void Anim_loadFromFile( Anim *a, const char *file ) {
    char *file_contents = NULL;
    cJSON *root = NULL;

    Byte_ReadFile( &file_contents, file );
    check( file_contents, " " );

    root = cJSON_Parse( file_contents );
    check( root, "JSON parse error [%s] before :\n%s\n", file, cJSON_GetErrorPtr() );

    cJSON *frames = cJSON_GetObjectItem( root, "frames" );
    check( frames, "Animation '%s' does not have any frame!\n", file );

    cJSON *frame_times = cJSON_GetObjectItem( root, "frame_times" );
    check( frame_times, "Animation '%s' does not have any frame times!\n", file );

    a->frame_n = cJSON_GetArraySize( frames );
    int frame_t_n = cJSON_GetArraySize( frame_times );
    check( a->frame_n > 0, "Animation '%s' does not have any frame!\n", file );
    check( a->frame_n == frame_t_n, "Animation '%s' : entries 'frames' and 'frame_times' must have the same size!\n", file );

    a->frames = byte_alloc( a->frame_n * sizeof(vec2) );
    a->frame_t = byte_alloc( a->frame_n * sizeof(f32) );

    for( int i = 0; i < a->frame_n; ++i ) {
        cJSON *frame = cJSON_GetArrayItem( frames, i );
        cJSON *frame_t = cJSON_GetArrayItem( frame_times, i );

        // frames positions are position on a 2048^2 texture. find their relative pos to it :
        if( frame ) {
            a->frames[i] = (vec2){ cJSON_GetArrayItem( frame, 0 )->valuedouble / 2048.f,
                                   cJSON_GetArrayItem( frame, 1 )->valuedouble / 2048.f };

            a->frame_t[i] = frame_t->valuedouble;
        }
    }

    a->curr_t = 0.f;
    a->curr_n = 0;
    a->running = false;


    DEL_PTR( file_contents );
    if( root ) cJSON_Delete( root );

    return;

error:
    Anim_destroy( a );
    DEL_PTR( file_contents );
    if( root ) cJSON_Delete( root );
}
void DataFileHelper::parseDataFile()
{
    
    std::string fullPath = CCFileUtils::sharedFileUtils()->fullPathForFilename("data.json");
    unsigned char* fileContent = NULL;
    unsigned long bufferSize = 0;
    fileContent = CCFileUtils::sharedFileUtils()->getFileData(fullPath.c_str(), "r", &bufferSize);
    cocos2d::CCString *ccStr = cocos2d::CCString::createWithData( fileContent, bufferSize );
    //printf("%s\n",ccStr->getCString());
    free(fileContent);
    
    cJSON *pRoot = cJSON_Parse(ccStr->getCString());
    int numItems = cJSON_GetArraySize(pRoot);
    
    m_Categories = new CCArray();
    m_Categories->initWithCapacity(numItems);
    
    for (int i = 0; i < numItems; i++)
    {
        Category *pCat = new Category();
        
        cJSON * item = cJSON_GetArrayItem(pRoot, i);
        pCat->setID(cJSON_GetObjectItem(item, "id")->valueint);
        pCat->setName(strdup(cJSON_GetObjectItem(item, "name")->valuestring));
        
        cJSON *pResponses = cJSON_GetObjectItem(item, "answers");
        
        CCArray *responses = CCArray::create();
        
        int numResponses = cJSON_GetArraySize(pResponses);
        for (int j = 0; j < numResponses; j++) {
            cJSON * response = cJSON_GetArrayItem(pResponses, j);
            Response *pRes = new Response();
            pRes->setID(cJSON_GetObjectItem(response, "id")->valueint);
            pRes->setName(strdup(cJSON_GetObjectItem(response, "name")->valuestring));
            pRes->setValid(cJSON_GetObjectItem(response, "valid")->valueint);
            pRes->setOption1(strdup(cJSON_GetObjectItem(response, "option1")->valuestring));
            pRes->setOption2(strdup(cJSON_GetObjectItem(response, "option2")->valuestring));
            pRes->setOption3(strdup(cJSON_GetObjectItem(response, "option3")->valuestring));
            pRes->setOption4(strdup(cJSON_GetObjectItem(response, "option4")->valuestring));
            responses->addObject(pRes);
            pRes->release();
        }
        
        pCat->setResponses(responses);
        m_Categories->addObject(pCat);
        pCat->release();
    }
    
    cJSON_Delete(pRoot);
    
}
Example #13
0
/******************************************************************************
 ******************************************************************************
 ** Core Parsing Routines                                                    **
 ******************************************************************************
 ******************************************************************************/
static lcbvb_VBUCKET *
build_vbmap(lcbvb_CONFIG *cfg, cJSON *cj, unsigned *nitems)
{
    lcbvb_VBUCKET *vblist = NULL;
    cJSON *jvb;
    unsigned ii, nalloc;

    /** FIXME: Realloc dynamically when too small */
    if (!(nalloc = cJSON_GetArraySize(cj))) {
        goto GT_ERR;
    }

    if (!(vblist = calloc(nalloc, sizeof(*vblist)))) {
        goto GT_ERR;
    }

    /* Iterate over all the vbuckets */
    jvb = cj->child;
    for (ii = 0; ii < nalloc && jvb; ++ii, jvb = jvb->next) {
        cJSON *jsix;
        lcbvb_VBUCKET *cvb;
        unsigned jj, nservers;

        if (jvb->type != cJSON_Array) {
            goto GT_ERR;
        }

        nservers = cJSON_GetArraySize(jvb);
        jsix = jvb->child;
        cvb = vblist + ii;

        /* Iterate over each index in the vbucket */
        for (jj = 0; jj < nservers && jsix; ++jj, jsix = jsix->next) {
            if (jsix->type != cJSON_Number) {
                goto GT_ERR;
            }
            cvb->servers[jj] = jsix->valueint;
            if (cvb->servers[jj] > (int)cfg->nsrv-1) {
                SET_ERRSTR(cfg, "Invalid vBucket map received from server. Above-bounds vBucket target found");
                goto GT_ERR;
            }
        }
    }

    *nitems = nalloc;
    return vblist;

    GT_ERR:
    free(vblist);
    return NULL;
}
Example #14
0
void parse(char * text, admin ** p)
{
	cJSON * jList = cJSON_Parse(text);
	if (!jList) {
		printf("Error before[%s]\n", cJSON_GetErrorPtr());
		return 1;

	}
   else{
    int count = cJSON_GetArraySize(jList);
   for (int i = 0; i < count; i++) {
        cJSON * jItem = cJSON_GetArrayItem(jList, i);
        char * name = cJSON_GetObjectItem(jItem, "name")->valuestring;
        char * surname = cJSON_GetObjectItem(jItem, "surname")->valuestring;
        char * birthdate = cJSON_GetObjectItem(jItem, "birthdate")->valuestring;
        cJSON * jGroup = cJSON_GetObjectItem(jItem, "company");
        char * companyName = cJSON_GetObjectItem(jGroup, "Network")->valuestring;
        char * language = cJSON_GetObjectItem(jGroup, "language")->valuestring;
        int  release = cJSON_GetObjectItem(jGroup, "release")->valueint;
        printf("Admin%i :\nName: %s\tSurnm:%s\t birthdate %s\t Working :\n Company :%s Language:%s Release %i  \n",i + 1, name, surname, birthdate, companyName, language, release);
// set_admin(p[i,name,surname,birthdate,company,hours);


}
   }
    cJSON_Delete(jList);

}
Example #15
0
static gn_error parse_phonebook(char *text)
{
    cJSON *root;
	
	root = cJSON_Parse(text);
	if (!root) {
        LOGMSG(LOG_LEVEL_CRIT, "Error before: [%s]\n",cJSON_GetErrorPtr());
        return GN_ERR_FAILED;
    }
    cJSON* phonebook = cJSON_GetObjectItem(root,"phonebook");
    if (!phonebook) {
        LOGMSG(LOG_LEVEL_CRIT, "Error: could not read phonebook object\n");
        return GN_ERR_FAILED;
    }
    int i; 
    for (i = 0;i < cJSON_GetArraySize(phonebook);i++)
    {
        cJSON *phoneItem = cJSON_GetArrayItem(phonebook,i);
        // handle subitem.	
        LOGMSG(LOG_LEVEL_DEBUG, "item #%d: name=%s phone=%s\n",i, 
                cJSON_GetObjectItem(phoneItem, "name")->valuestring,
                cJSON_GetObjectItem(phoneItem, "phone")->valuestring);
        _add_phone(cJSON_GetObjectItem(phoneItem, "name")->valuestring,
                cJSON_GetObjectItem(phoneItem, "phone")->valuestring);
    }
    cJSON_Delete(root);
    return GN_ERR_NONE;
}
// 将json文本反序列化为 url 队列
queue<url *> communication::decoding(const char * decoding_text)
{
	assert(decoding_text!=NULL);
	cJSON * json_arr;
	cJSON * json_item;
	cJSON * host , * file ,*  port ,*  priority ,* depth;

	queue<url *> urlqueue;

	json_arr=cJSON_Parse(decoding_text);
	int size = cJSON_GetArraySize(json_arr);
	for( int i=0;i<size;i++)
	{
		json_item = cJSON_GetArrayItem(json_arr,i);
		if (!json_item) {
			printf("Error before: [%s]\n",cJSON_GetErrorPtr());
		}
		else
		{
			//解析json item ,拼装成url, Add to urlQueue
			host = cJSON_GetObjectItem(json_item,"HOST");
			file = cJSON_GetObjectItem(json_item,"FILE");
			port = cJSON_GetObjectItem(json_item,"PORT");
			priority = cJSON_GetObjectItem(json_item,"PRIORITY");
			depth = cJSON_GetObjectItem(json_item,"DEPTH");
			url * u = new url(host->valuestring , port->valueint ,file->valuestring , depth->valueint ,priority->valueint);
			urlqueue.push(u);
		}
	}
	cJSON_Delete(json_arr);
	return urlqueue;
}
Example #17
0
static void get_disk_stats (cJSON* root, unsigned long* write_val, unsigned long* read_val, enum disk_switch data_type) {
	cJSON* disk_stats_array = NULL;
	switch (data_type) {
		case OPS:
			disk_stats_array = cJSON_GetObjectItem(cJSON_GetObjectItem(root,"blkio_stats"),"io_serviced_recursive");
			break;
		case BYTES:
			disk_stats_array = cJSON_GetObjectItem(cJSON_GetObjectItem(root,"blkio_stats"),"io_service_bytes_recursive");
			break;
	}
	
	int i, disk_stats_num = cJSON_GetArraySize(disk_stats_array);
	
	cJSON* tmp;
	char* op;
	for (i=0;i<disk_stats_num;i++) {
		 tmp = cJSON_GetArrayItem(disk_stats_array,i);
		 op = cJSON_GetObjectItem(tmp,"op")->valuestring;
		 if (!strcmp(op,"Read")) {
			 *read_val = cJSON_GetObjectItem(tmp,"value")->valueint;
		 }
		 if (!strcmp(op,"Write")) {
			 *write_val = cJSON_GetObjectItem(tmp,"value")->valueint;
		 }
	}
}
// virtual
void RsFlashWinGL::Update( BtFloat tick )
{
	// Cache the frames array
	cJSON *pFames = cJSON_GetObjectItem( m_pJSON , "frames" );

	// Cache the number of frames
	m_numFrames = cJSON_GetArraySize( pFames );

	// Increment the time
	m_currentFrameTime += tick;

	// Work out the current frame
	m_currentFrame = (BtU32)( m_currentFrameTime / BtTime::GetTick() );

	if( m_isLooping )
	{
		if( m_currentFrame > m_numFrames - 1 )
		{
			m_currentFrameTime = 0;
		}
	}
	else
	{
		if( m_currentFrame > m_numFrames - 1 )
		{
			m_currentFrame = m_numFrames - 1;
		}
	}
}
Example #19
0
void parsingCommandObject(cJSON *item)
{

    int i;
    for (i = 0 ; i < cJSON_GetArraySize(item) ; i++)
    {
        char *commandString, *valueString, *collectionString, *idString;
        int isObjt = 0;
        cJSON * subitem = cJSON_GetArrayItem(item, i);
        cJSON * value = cJSON_GetObjectItem(subitem,"value");
        cJSON * command = cJSON_GetObjectItem(subitem,"command");
        cJSON * collection = cJSON_GetObjectItem(subitem,"collection");
        cJSON * id = cJSON_GetObjectItem(subitem,"id");
        commandString    = (command) ? command->valuestring : "";
        valueString      = (value) ? value->valuestring : "";
        collectionString = (collection) ? collection->valuestring : "";
        idString         = (id) ? id->valuestring : "";

        if(value && value->type == cJSON_Object)
        {
            isObjt = 1;
            char *outObj=0;
            outObj=cJSON_PrintUnformatted(value);
            valueString = outObj;
            (command && value && collection && idString) ? parsingCommand(commandString, collectionString, idString, valueString, isObjt):checkAllFields_IsSetted(command, value, collection, id, isObjt, i);
        }
        else
        {
            (command && value) ? parsingCommand(commandString, collectionString, idString, valueString, isObjt):checkAllFields_IsSetted(command, value, collection, id, isObjt, i);
        }
    }
}
//Handler for update request from the server.
//It receives all the update requests like location, mgmt.firmware
//Currently only location and firmware updates are supported.
void messageUpdate(MessageData* md) {
	int i = 0;
	MQTTMessage* message = md->message;
	void *payload = message->payload;
	cJSON * jsonPayload = cJSON_Parse(payload);
	if (jsonPayload) {
		cJSON* jreqId = cJSON_GetObjectItem(jsonPayload, "reqId");
		strcpy(currentRequestID, jreqId->valuestring);
		printf("Update reqId:%s\n", currentRequestID);
		cJSON *d = cJSON_GetObjectItem(jsonPayload, "d");
		cJSON *fields = cJSON_GetObjectItem(d, "fields");

		for (i = 0; i < cJSON_GetArraySize(fields); i++) {
			cJSON * field = cJSON_GetArrayItem(fields, i);
			cJSON* fieldName = cJSON_GetObjectItem(field, "field");
			printf("update request received for fieldName :%s\n", fieldName->valuestring);
			cJSON * value = cJSON_GetObjectItem(field, "value");

			if (!strcmp(fieldName->valuestring, "location"))
				updateLocationRequest(value);
			else if (!strcmp(fieldName->valuestring, "mgmt.firmware"))
				updateFirmwareRequest(value);
			else if (!strcmp(fieldName->valuestring, "metadata"))
				;	//Currently not supported
			else if (!strcmp(fieldName->valuestring, "deviceInfo"))
				;	//Currently not supported
		}
		cJSON_Delete(jsonPayload);//Needs to delete the parsed pointer
	} else
		printf("Error in parsing Json\n");
}
//Handler for cancel observation request
void messageCancel(MessageData* md)
{
	printf("Cancel request called\n");
	int i = 0;
	char respMsg[100];
	MQTTMessage* message = md->message;
	void *payload = message->payload;
	cJSON * jsonPayload = cJSON_Parse(payload);
	cJSON* jreqId = cJSON_GetObjectItem(jsonPayload, "reqId");
	strcpy(currentRequestID, jreqId->valuestring);
	printf("Cancel reqId:%s\n", currentRequestID);
	cJSON *d = cJSON_GetObjectItem(jsonPayload, "d");
	cJSON *fields = cJSON_GetObjectItem(d, "fields");
	//cJSON *fields = cJSON_GetObjectItem(jsonPayload,"fields");
	for (i = 0; i < cJSON_GetArraySize(fields); i++) {
		cJSON * field = cJSON_GetArrayItem(fields, i);
		cJSON* fieldName = cJSON_GetObjectItem(field, "field");

		cJSON * value = cJSON_GetArrayItem(fields, i);
		printf("cancel called for field:%s\n",fieldName->valuestring);
		if (!strcmp(fieldName->valuestring, "mgmt.firmware")) {
			dmClient.bObserve = false;
			sprintf(respMsg,"{\"rc\":%d,\"reqId\":%s}",RESPONSE_SUCCESS,currentRequestID);
			//Publish the response to the IoTF
			publishActionResponse(RESPONSE, respMsg);
		}
	}
}
//Handler for Observe request
void messageObserve(MessageData* md) {
	int i = 0;
	MQTTMessage* message = md->message;
	void *payload = message->payload;
	char* respMsg;
	cJSON *resPayload, *resd, *resFields;
	resPayload = cJSON_CreateObject();
	cJSON_AddItemToObject(resPayload, "rc",
			cJSON_CreateNumber(RESPONSE_SUCCESS));
	cJSON * jsonPayload = cJSON_Parse(payload);
	cJSON* jreqId = cJSON_GetObjectItem(jsonPayload, "reqId");
	strcpy(currentRequestID, jreqId->valuestring);
	printf("Observe reqId:%s\n", currentRequestID);
	cJSON_AddItemToObject(resPayload, "reqId",
			cJSON_CreateString(currentRequestID));

	cJSON_AddItemToObject(resPayload, "d", resd = cJSON_CreateObject());

	cJSON_AddItemToObject(resd, "fields", resFields =
			cJSON_CreateArray());

	cJSON *d = cJSON_GetObjectItem(jsonPayload, "d");

	cJSON *fields = cJSON_GetObjectItem(d, "fields");

	//cJSON *fields = cJSON_GetObjectItem(jsonPayload,"fields");
	for (i = 0; i < cJSON_GetArraySize(fields); i++) {
		cJSON * field = cJSON_GetArrayItem(fields, i);

		cJSON* fieldName = cJSON_GetObjectItem(field, "field");

		cJSON * value = cJSON_GetArrayItem(fields, i);

		printf("Observe called for fieldName:%s\n",fieldName->valuestring);
		if (!strcmp(fieldName->valuestring, "mgmt.firmware")) {
			dmClient.bObserve = true;
			cJSON* resValue;
			cJSON* resField = cJSON_CreateObject();
			cJSON_AddItemToObject(resField, "field", cJSON_CreateString("mgmt.firmware"));
			cJSON_AddItemToObject(resField, "value", resValue = cJSON_CreateObject());
			cJSON_AddItemToObject(resValue, "state",
					cJSON_CreateNumber(
							dmClient.DeviceData.mgmt.firmware.state));

			cJSON_AddItemToObject(resValue, "updateStatus",
					cJSON_CreateNumber(
							dmClient.DeviceData.mgmt.firmware.updateStatus));

			cJSON_AddItemToArray(resFields,resField);

		}
	}
	respMsg = cJSON_Print(resPayload);
	cJSON_Delete(resPayload);
	//Publish the response to the IoTF
	publishActionResponse(RESPONSE, respMsg);

	cJSON_Delete(jsonPayload);
	free(respMsg);
}
Example #23
0
void testBatch(){
	cJSON *res, *child;
	
	res = handler_raw("["
					  "{\"jsonrpc\": \"2.0\", \"method\": \"sum\", \"params\": [2], \"id\": 1},"
					  "{\"jsonrpc\": \"2.0\", \"method\": \"sum\", \"params\": [4], \"id\": 2},"
					  "{\"jsonrpc\": \"2.0\", \"method\": \"sum\", \"params\": [6], \"id\": 3}"
					  "]");
					  
	ASSERT(res->type == cJSON_Array);
	ASSERT(cJSON_GetArraySize(res) == 3);
		
	int i = 1;
	child = res->child;
	while (child){
		
		ASSERT(strcmp(cJSON_GetObjectItem(child, "jsonrpc")->valuestring, "2.0") == 0);
		ASSERT(cJSON_GetObjectItem(child, "result")->valuedouble == (i * 2));
		ASSERT(cJSON_GetObjectItem(child, "id")->valueint == i);
		
		i++;
		child = child->next;
	}
	cJSON_Delete(res);
}
Example #24
0
int  RUCE_Roto_GetEntryNum(RUCE_Roto* This)
{
    cJSON* Entries = cJSON_GetObjectItem(This -> Ptr, "Entries");
    if(! Entries) return 0;
    
    return cJSON_GetArraySize(Entries);
}
Example #25
0
void testBatchInvalidOne(){
	cJSON *res, *child, *error;
	
	res = handler_raw("["
					  "{\"jsonrpc\": \"2.0\", \"method\": \"sum\", \"params\": [2], \"id\": 1},"
					  "{\"jsonrpc\": \"2.0\", \"method\": \"sum\", \"params\": [4], \"id\": 2},"
					  "{\"jsonrpc\": \"2.0\", \"id\": 3}" // invalid
					  "]");
	//return json_print_delete(res);
	ASSERT(res->type == cJSON_Array);
	ASSERT(cJSON_GetArraySize(res) == 3);
		
	int i = 1;
	child = res->child;
	while (child){
		if(i == 3){
			error = cJSON_GetObjectItem(child, "error");
			ASSERT(strcmp(cJSON_GetObjectItem(child, "jsonrpc")->valuestring, "2.0") == 0);
			ASSERT(cJSON_GetObjectItem(error, "code")->valueint == RESPONSE_INVALID_REQUEST);
			ASSERT(strcmp(cJSON_GetObjectItem(error, "msg")->valuestring, RESPONSE_INVALID_REQUEST_MSG) == 0);
			ASSERT(cJSON_GetObjectItem(child, "id")->valueint == 3);
		}else{
			ASSERT(strcmp(cJSON_GetObjectItem(child, "jsonrpc")->valuestring, "2.0") == 0);
			ASSERT(cJSON_GetObjectItem(child, "result")->valuedouble == (i * 2));
			ASSERT(cJSON_GetObjectItem(child, "id")->valueint == i);
		}
		i++;
		child = child->next;
	}
	cJSON_Delete(res);
}
Example #26
0
void CdynControlDlg::OnLbnDblclkList1()
{
    // TODO: Add your control notification handler code here
    int idx = m_predefined.GetCurSel();

    CString str;
    m_predefined.GetText(idx, str);
    str = _T("Run: ") + str;
    
    if (MessageBox(str, NULL, MB_OKCANCEL | MB_ICONWARNING) != IDOK)
        return;

    cJSON *action = cJSON_GetObjectItem(m_actionJSON, actions[idx]);
    
    int num = cJSON_GetArraySize(action);

    log(_T("\n-- start action %s with %d steps --\n"), str, num);
    for (int i = 0; i < num; i++) {
        cJSON *cmd = cJSON_GetArrayItem(action, i);
        SetServo(cJSON_GetObjectItem(cmd, "id")->valueint, 
                 cJSON_GetObjectItem(cmd, "deg")->valueint);
        SendServo(cJSON_GetObjectItem(cmd, "id")->valueint);
        Sleep(1000);
    }

    log(_T("-- end action --\n\n"), str, num);
}
Example #27
0
static int update_server_info(struct vbucket_config_st *vb, cJSON *config) {
    int idx, ii;
    cJSON *node, *json;

    for (ii = 0; ii < cJSON_GetArraySize(config); ++ii) {
        node = cJSON_GetArrayItem(config, ii);
        if (node) {
            if (node->type != cJSON_Object) {
                errstr = "Expected json object for nodes array item";
                return -1;
            }

            if ((idx = lookup_server_struct(vb, node)) >= 0) {
                json = cJSON_GetObjectItem(node, "couchApiBase");
                if (json != NULL) {
                    char *value = strdup(json->valuestring);
                    if (value == NULL) {
                        errstr = "Failed to allocate storage for couchApiBase string";
                        return -1;
                    }
                    vb->servers[idx].couchdb_api_base = value;
                }
            }
        }
    }
    return 0;
}
Example #28
0
/*-------------------------------------------------------------------
 Function: getDataCount()
 Purpose: get data count
 Parameters: 
 return: >=0 -- data count
         -1 -- failed
-------------------------------------------------------------------*/
int CEhJsonReader::getDataCount(void)
{
    if (!m_jsonTransData)
        return -1;

    return cJSON_GetArraySize(m_jsonTransData);
}
Example #29
0
void parse(scientist_t  ** sc)
{
    FILE * file = fopen("Scientist.json", "r");
    char text[10000];
    char line[100];

    while(fgets(line, 100, file) != NULL)
    {
        strcat(text, line);
    }
    fclose(file);

    cJSON * jList = cJSON_Parse(text);
    if (!jList)
    {
        printf("Error before: [%s]\n", cJSON_GetErrorPtr());
        return;
    }

    for (int i = 0; i < cJSON_GetArraySize(jList); i++)
    {
        cJSON * jItem = cJSON_GetArrayItem(jList, i);
        char * name = cJSON_GetObjectItem(jItem, "name")->valuestring;
        char * surname = cJSON_GetObjectItem(jItem, "surname")->valuestring;
        char * date = cJSON_GetObjectItem(jItem, "date")->valuestring;
        int salary = cJSON_GetObjectItem(jItem, "salary")->valueint;
        double age = cJSON_GetObjectItem(jItem, "age")->valuedouble;

        Scientist_set(sc[i], name, surname, age, date, salary);
    }
    cJSON_Delete(jList);
}
Example #30
0
static int reg_cb(const char *json_data) {
	int ret = -1;
	char buf[500];
	memset(buf, 0, sizeof(buf));
	memcpy(buf, json_data, strlen(json_data));

	cJSON *root = cJSON_Parse(buf);
	if (root) {
		int ret_size = cJSON_GetArraySize(root);
		if (ret_size >= 4) {
			cJSON * pClientId = cJSON_GetObjectItem(root,"c");
			cJSON * pUsername = cJSON_GetObjectItem(root,"u");
			cJSON * pPassword = cJSON_GetObjectItem(root,"p");
			cJSON * pDevId = cJSON_GetObjectItem(root,"d");
			if (pClientId != NULL && pUsername != NULL &&
					pPassword != NULL && pDevId != NULL) {
				strcpy(reg_info.client_id, pClientId->valuestring);
				strcpy(reg_info.username, pUsername->valuestring);
				strcpy(reg_info.password, pPassword->valuestring);
				strcpy(reg_info.device_id, pDevId->valuestring);
				ret = 0;
			}
		}
		cJSON_Delete(root);
	}
	return ret;
}