Exemple #1
0
/* Convert Eventinfo to json */
char *Eventinfo_to_jsonstr(Eventinfo *lf)
{
    cJSON *root;
    cJSON *rule;
    cJSON *file_diff;
    char *out;

    root = cJSON_CreateObject();
    cJSON_AddItemToObject(root, "rule", rule = cJSON_CreateObject());

    cJSON_AddNumberToObject(rule, "level", lf->generated_rule->level);

    if (lf->generated_rule->comment) {
        cJSON_AddStringToObject(rule, "comment", lf->generated_rule->comment);
    }
    if (lf->generated_rule->sigid) {
        cJSON_AddNumberToObject(rule, "sidid", lf->generated_rule->sigid);
    }
    if (lf->generated_rule->cve) {
        cJSON_AddStringToObject(rule, "cve", lf->generated_rule->cve);
    }
    if (lf->generated_rule->cve) {
        cJSON_AddStringToObject(rule, "info", lf->generated_rule->info);
    }


    if (lf->action) {
        cJSON_AddStringToObject(root, "action", lf->action);
    }
    if (lf->srcip) {
        cJSON_AddStringToObject(root, "srcip", lf->srcip);
    }
    if (lf->srcport) {
        cJSON_AddStringToObject(root, "srcport", lf->srcport);
    }
    if (lf->srcuser) {
        cJSON_AddStringToObject(root, "srcuser", lf->srcuser);
    }
    if (lf->dstip) {
        cJSON_AddStringToObject(root, "dstip", lf->dstip);
    }
    if (lf->dstport) {
        cJSON_AddStringToObject(root, "dstport", lf->dstport);
    }
    if (lf->dstuser) {
        cJSON_AddStringToObject(root, "dstuser", lf->dstuser);
    }
    if (lf->location) {
        cJSON_AddStringToObject(root, "location", lf->location);
    }
    if (lf->full_log) {
        cJSON_AddStringToObject(root, "full_log", lf->full_log);
    }
    if (lf->filename) {
        cJSON_AddItemToObject(root, "file", file_diff = cJSON_CreateObject());

        cJSON_AddStringToObject(file_diff, "path", lf->filename);

        if (lf->md5_before && lf->md5_after && strcmp(lf->md5_before, lf->md5_after) != 0  ) {
            cJSON_AddStringToObject(file_diff, "md5_before", lf->md5_before);
            cJSON_AddStringToObject(file_diff, "md5_after", lf->md5_after);
        }
        if (lf->sha1_before && lf->sha1_after && !strcmp(lf->sha1_before, lf->sha1_after) != 0) {
            cJSON_AddStringToObject(file_diff, "sha1_before", lf->sha1_before);
            cJSON_AddStringToObject(file_diff, "sha1_after", lf->sha1_after);
        }
        if (lf->owner_before && lf->owner_after && !strcmp(lf->owner_before, lf->owner_after) != 0) {
            cJSON_AddStringToObject(file_diff, "owner_before", lf->owner_before);
            cJSON_AddStringToObject(file_diff, "owner_after", lf->owner_after);
        }
        if (lf->gowner_before && lf->gowner_after && !strcmp(lf->gowner_before, lf->gowner_after) != 0 ) {
            cJSON_AddStringToObject(file_diff, "gowner_before", lf->gowner_before);
            cJSON_AddStringToObject(file_diff, "gowner_after", lf->gowner_after);
        }
        if (lf->perm_before && lf->perm_after && lf->perm_before != lf->perm_after) {
            cJSON_AddNumberToObject(file_diff, "perm_before", lf->perm_before);
            cJSON_AddNumberToObject(file_diff, "perm_after", lf->perm_after);
        }
    }
    out = cJSON_PrintUnformatted(root);
    cJSON_Delete(root);
    return out;
}
bool VGW_Vod_Stream::StartOneStream(int iStreamID,char *strUrl,char *strRegionid,char* strUserID,char *vodname,char *posterurl,int fd)
{
	if(fd)
	{
		MapVodPlay::iterator fdfind= m_mapVod_player.find(iStreamID);
		if(fdfind != m_mapVod_player.end())
		{
				//找到对应信息
			Stream* sptmpRequest = fdfind->second;			
			if(fd != sptmpRequest->m_clientSocket)
			{
				printf("the socket is changed,before = %d,after = %d\n",sptmpRequest->m_clientSocket,fd);
				fflush(stdout);
				sptmpRequest->m_clientSocket = fd;	
			}
		}
	}	
	if(!Connect_VODServer())
	{
		m_mapVod_player.clear();
		printf("error can't connect to server \n");
		fflush(stdout);
		return false;
	}

	if(pRet_root)
	{
		cJSON_Delete(pRet_root);
		pRet_root = NULL;
	}

	char strSeesionId[32]={0};
	sprintf(strSeesionId,"%d",iStreamID);
	
	char strSID[32]="3002";
	char strstype[32]="3302";
	char strctype[32]="5";
	char strvtype[32]="2";

	char strareaid[32]="2";
	char strMsg[1024]={0};
	char striip[32]="3301";
	char striport[32]="3301";
	char strsip[32]={0};
	strcpy(strsip,strMyServerIP);
	char strsport[32]={0};
	sprintf(strsport,"%d",iMSIServerPort);
	

	char strRegionID[32]="0x0603"; //"0x0604"
 //   char strOutUrl[512]= "rtsp://192.168.100.11:8845/yjy_ipqam/bjtv.ts";  //"rtsp://192.168.100.11:8845/yjy_ipqam/8081/gyc.ts";
//	unsigned long ilen= sizeof(strOutUrl);

	unsigned long ulInLen=strlen(strUrl);
	ZBase64 tmpEncode;
	std::string strencodemsg = tmpEncode.Encode((unsigned char*)strUrl,ulInLen);
	sprintf(strMsg,"%s|%s",strencodemsg.c_str(),strRegionid);
	printf("---%s \n",strUrl);
	fflush(stdout);
	printf("%s \n",strMsg);
	fflush(stdout);
	
	//需要得到返回值才可作为点播成功
	pRet_root = cJSON_CreateObject();
/*	Requst_Json_str(2,"appuserid",strappuserid);
	Requst_Json_str(2,"spuserid",strspuserid);
	Requst_Json_str(2,"areaid",strareaid);
	Requst_Json_str(2,"sid",strSID);
	Requst_Json_str(2,"iip",striip);
	Requst_Json_str(2,"iport",striport);
	Requst_Json_str(2,"sip",strsip);
	Requst_Json_str(2,"sport",strsport);	
	Requst_Json_str(2,"msg",strMsg);	
*/	
	Requst_Json_str(2,"cmd","login");
	Requst_Json_str(2,"sessionid",strSeesionId);
	Requst_Json_str(2,"sid",strSID);
	Requst_Json_str(2,"stype",strstype);
	Requst_Json_str(2,"ctype",strctype);
	Requst_Json_str(2,"vtype",strctype);

	Requst_Json_str(2,"url","");
	Requst_Json_str(2,"areaid",strareaid);
	Requst_Json_str(2,"sip",strsip);
	Requst_Json_str(2,"sport",strsport);	
	Requst_Json_str(2,"serialno",strSeesionId);
	Requst_Json_str(2,"msg",strMsg);
	Requst_Json_str(2,"vodname",vodname);
	Requst_Json_str(2,"posterurl",posterurl);
	Requst_Json_str(2,"appuserid",strSeesionId);
	Requst_Json_str(2,"spuserid",strUserID);

	
	Send_Jsoon_str();
	
	return true;
}
void   cJSON_DeleteItemFromArray(cJSON *array,int which)			{cJSON_Delete(cJSON_DetachItemFromArray(array,which));}
Exemple #4
0
int platform_anzhi_auth(const char *param, auth_cb cb, void *args)
{
    LOG_DEBUG("net", "platform_anzhi_auth: %p", args);

    cJSON *json = cJSON_Parse(param);
    if (json == NULL) {
        return PLATFORM_PARAM_ERROR;
    }

    cJSON *setting = platform_get_json(PLAT_ANZHI);
    if (setting == NULL) {
        return PLATFORM_SETTING_ERROR;
    }
    
    cJSON *url = cJSON_GetObjectItem(setting, "URL");
    if (url == NULL) {
        return PLATFORM_SETTING_ERROR;
    }


    cJSON *appKey = cJSON_GetObjectItem(setting, "appKey");
    if (appKey == NULL) {
        return PLATFORM_SETTING_ERROR;
    }

    cJSON *appSecret = cJSON_GetObjectItem(setting, "appSecret");
    if (appSecret == NULL) {
        return PLATFORM_SETTING_ERROR;
    }

    cJSON *token = cJSON_GetObjectItem(json, "token");
    if (token == NULL) {
        return PLATFORM_PARAM_ERROR;
    }

    cJSON *userId = cJSON_GetObjectItem(json, "userId");
    if (userId == NULL) {
        return PLATFORM_PARAM_ERROR;
    }

    //appkey+account+sid+appsecret
    std::string ctx = appKey->valuestring;
    ctx.append(userId->valuestring);
    ctx.append(token->valuestring);
    ctx.append(appSecret->valuestring);

    std::string sign = base64_encode(ctx.c_str(), ctx.size(), false);

    struct tm ctm;
    time64_t now = time_ms();
    char now_s[64];
    time_t tm = (time_t)(now / 1000);

    localtime_r(&tm, &ctm);
    strftime(now_s, sizeof(now_s), "%Y%m%d%H%M%S", &ctm);
    sprintf(now_s, "%s%lld", now_s, now - tm * 1000);


    std::string post_url;
    post_url.append(url->valuestring);
    post_url.append("?time=");
    post_url.append(now_s);

    post_url.append("&appkey=");
    post_url.append(appKey->valuestring);

    post_url.append("&account=");
    post_url.append(userId->valuestring);

    post_url.append("&sid=");
    post_url.append(token->valuestring);

    post_url.append("&sign=");
    post_url.append(sign);

    cJSON_Delete(json);

    // do post request
    plat_json_req *json_req = E_NEW plat_json_req(cb, args);
    json_req->plat_type = PLAT_ANZHI;
    json_req->channel = "anzhi";
    json_req->param = std::string(param);

    http_json(HTTP_POST, post_url.c_str(), "", write_callback, json_req);

    LOG_DEBUG("net", "url: %s", post_url.c_str());
    return PLATFORM_OK;
}
Exemple #5
0
cJSON* CHPRepPayloadToJson(OCRepPayload* repData)
{
    cJSON *outJson = cJSON_CreateObject();
    if (outJson == NULL)
    {
        return NULL;
    }

    OCRepPayloadValue* val = repData->values;
    while (val)
    {
        switch (val->type)
        {
            case OCREP_PROP_NULL:
                break;
            case OCREP_PROP_INT:
                OIC_LOG_V(DEBUG, TAG, "%s(int):%d", val->name, (int)val->i);
                cJSON_AddNumberToObject(outJson,val->name,(int)val->i);
                break;
            case OCREP_PROP_DOUBLE:
                OIC_LOG_V(DEBUG, TAG, "%s(double):%f", val->name, val->d);
                cJSON_AddNumberToObject(outJson,val->name,val->d);
                break;
            case OCREP_PROP_BOOL:
                OIC_LOG_V(DEBUG, TAG, "%s(bool):%s", val->name, val->b ? "true" : "false");
                cJSON_AddBoolToObject(outJson,val->name,val->b);
                break;
            case OCREP_PROP_STRING:
                OIC_LOG_V(DEBUG, TAG, "%s(string):%s", val->name, val->str);
                cJSON_AddStringToObject(outJson,val->name,val->str);
                break;
            case OCREP_PROP_OBJECT:
            {
                cJSON *objJson = CHPRepPayloadToJson(val->obj);
                if (objJson != NULL)
                {
                    cJSON_AddItemToObject(outJson,val->name,objJson);
                }
                break;
            }
            case OCREP_PROP_ARRAY:
            {
                unsigned int i = 0;
                int arraySize = (int)val->arr.dimensions[0];
                switch (val->arr.type)
                {
                    case OCREP_PROP_INT:
                        OIC_LOG_V(DEBUG, TAG, "%s(int array)", val->name);
                        if (arraySize > 0)
                        {
                            int castVal[val->arr.dimensions[0]];
                            for (i = 0 ; i < (unsigned int)arraySize ; i++)
                            {
                                castVal[i] = (int)val->arr.iArray[i];
                            }
                            cJSON *array = cJSON_CreateIntArray(castVal,arraySize);
                            if (array != NULL)
                            {
                                cJSON_AddItemToObject(outJson,val->name,array);
                            }
                        }
                        break;
                    case OCREP_PROP_DOUBLE:
                        OIC_LOG_V(DEBUG, TAG, "%s(double array)", val->name);
                        if (arraySize > 0)
                        {
                            cJSON *array = cJSON_CreateDoubleArray(val->arr.dArray,arraySize);
                            if (array != NULL)
                            {
                                cJSON_AddItemToObject(outJson,val->name,array);
                            }
                        }
                        break;
                    case OCREP_PROP_STRING:
                        OIC_LOG_V(DEBUG, TAG, "%s(string array)", val->name);
                        if (arraySize > 0)
                        {
                            cJSON *array = cJSON_CreateStringArray((const char**)val->arr.strArray,
                                                                   arraySize);
                            if (array != NULL)
                            {
                                cJSON_AddItemToObject(outJson,val->name,array);
                            }
                        }
                        break;
                    case OCREP_PROP_OBJECT:
                        if (arraySize > 0)
                        {
                            cJSON *arrayJson = cJSON_CreateArray();
                            for (i = 0 ; i < (unsigned int)arraySize ; i++)
                            {
                                cJSON *objJson = CHPRepPayloadToJson(val->arr.objArray[i]);
                                if (objJson != NULL && arrayJson != NULL)
                                {
                                    cJSON_AddItemToArray(arrayJson, objJson);
                                }
                            }
                            if (arrayJson != NULL)
                            {
                                cJSON_AddItemToObject(outJson,val->name,arrayJson);
                            }
                        }
                        break;
                    case OCREP_PROP_BOOL:
                        //TODO : Not support - cJSON_CreateBoolArray
                        break;
                    default:
                        OIC_LOG_V(ERROR, TAG, "Unknown/unsupported array type: %s", val->name);
                        break;
                }
                break;
            }
            default:
                OIC_LOG_V(ERROR, TAG, "Unknown type: %s", val->name);
                break;
        }
        val = val->next;
    }

    if( repData->values != NULL)
    {
        return outJson;
    }
    else
    {
        cJSON_Delete(outJson);
        return NULL;
    }
}
Exemple #6
0
/* Create a bunch of objects as demonstration. */
void create_objects() {
    cJSON *root, *fmt, *img, *thm, *fld;
    char *out;
    int i;    /* declare a few. */
    /* Our "days of the week" array: */
    const char *strings[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    /* Our matrix: */
    int numbers[3][3] = {{0, -1, 0},
                         {1, 0,  0},
                         {0, 0,  1}};
    /* Our "gallery" item: */
    int ids[4] = {116, 943, 234, 38793};
    /* Our array of "records": */
    struct record fields[2] = {
            {"zip", 37.7668,   -1.223959e+2, "", "SAN FRANCISCO", "CA", "94107", "US"},
            {"zip", 37.371991, -1.22026e+2,  "", "SUNNYVALE",     "CA", "94085", "US"}};

    /* Here we construct some JSON standards, from the JSON site. */

    /* Our "Video" datatype: */
    root = cJSON_CreateObject();
    cJSON_AddItemToObject(root, "name", cJSON_CreateString("Jack (\"Bee\") Nimble"));
    cJSON_AddItemToObject(root, "format", fmt = cJSON_CreateObject());
    cJSON_AddStringToObject(fmt, "type", "rect");
    cJSON_AddNumberToObject(fmt, "width", 1920);
    cJSON_AddNumberToObject(fmt, "height", 1080);
    cJSON_AddFalseToObject (fmt, "interlace");
    cJSON_AddNumberToObject(fmt, "frame rate", 24);

    out = cJSON_Print(root);
    cJSON_Delete(root);
    printf("%s\n", out);
    free(out);    /* Print to text, Delete the cJSON, print it, release the string. */

    /* Our "days of the week" array: */
    root = cJSON_CreateStringArray(strings, 7);

    out = cJSON_Print(root);
    cJSON_Delete(root);
    printf("%s\n", out);
    free(out);

    /* Our matrix: */
    root = cJSON_CreateArray();
    for (i = 0; i < 3; i++) cJSON_AddItemToArray(root, cJSON_CreateIntArray(numbers[i], 3));

/*	cJSON_ReplaceItemInArray(root,1,cJSON_CreateString("Replacement")); */

    out = cJSON_Print(root);
    cJSON_Delete(root);
    printf("%s\n", out);
    free(out);


    /* Our "gallery" item: */
    root = cJSON_CreateObject();
    cJSON_AddItemToObject(root, "Image", img = cJSON_CreateObject());
    cJSON_AddNumberToObject(img, "Width", 800);
    cJSON_AddNumberToObject(img, "Height", 600);
    cJSON_AddStringToObject(img, "Title", "View from 15th Floor");
    cJSON_AddItemToObject(img, "Thumbnail", thm = cJSON_CreateObject());
    cJSON_AddStringToObject(thm, "Url", "http:/*www.example.com/image/481989943");
    cJSON_AddNumberToObject(thm, "Height", 125);
    cJSON_AddStringToObject(thm, "Width", "100");
    cJSON_AddItemToObject(img, "IDs", cJSON_CreateIntArray(ids, 4));

    out = cJSON_Print(root);
    cJSON_Delete(root);
    printf("%s\n", out);
    free(out);

    /* Our array of "records": */

    root = cJSON_CreateArray();
    for (i = 0; i < 2; i++) {
        cJSON_AddItemToArray(root, fld = cJSON_CreateObject());
        cJSON_AddStringToObject(fld, "precision", fields[i].precision);
        cJSON_AddNumberToObject(fld, "Latitude", fields[i].lat);
        cJSON_AddNumberToObject(fld, "Longitude", fields[i].lon);
        cJSON_AddStringToObject(fld, "Address", fields[i].address);
        cJSON_AddStringToObject(fld, "City", fields[i].city);
        cJSON_AddStringToObject(fld, "State", fields[i].state);
        cJSON_AddStringToObject(fld, "Zip", fields[i].zip);
        cJSON_AddStringToObject(fld, "Country", fields[i].country);
    }

/*	cJSON_ReplaceItemInObject(cJSON_GetArrayItem(root,1),"City",cJSON_CreateIntArray(ids,4)); */

    out = cJSON_Print(root);
    cJSON_Delete(root);
    printf("%s\n", out);
    free(out);

}
Exemple #7
0
void AnalysisInitJson(char *buffer)
{
	cJSON *root, *item, *item2;
	cJSON *pJsonArray = NULL;
	cJSON *pArrayItem = NULL;
	char time[MinZone];
	int ii;

	if(!(root = cJSON_Parse(buffer)))
	{
		sNetOutput(">>>[ERR] Analisis Init json buffer failed in Global.c"," >>>");
		return;
	}


	if((item = cJSON_GetObjectItem(root, "Type")))
	{
		if (strcasecmp(item -> valuestring, "Init") == 0)
		{
			Flags.RecvPcMode = 1;


			if((item = cJSON_GetObjectItem(root, "MajorAgent")))
			{
				status.MajorAgent = item -> valueint;
			}

			item = cJSON_GetObjectItem(root, "TeamCount");
			TeamCount = item -> valueint;


			if((item = cJSON_GetObjectItem(root, "NeedAnswer")))
			{
				if(strcasecmp(item -> valuestring, YES) == 0)
				{
					//需要相应,则给对方发送相应。xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
					//这里是不是要改成验证CMDID的格式,那么打包的函数就不应该使用CreateMultiplexJson
					AgentAnswer = CreateMultiplexJson("AgentAnswer", getCommandID());
				}
			}


			//根据pc的时间,校准本地的时间。
			item = cJSON_GetObjectItem(root, "Time");
			memset(time, 0 ,sizeof(time));
			strncpy(time, item -> valuestring, strlen(item -> valuestring));

			year   = (time[2] - '0')*10 + (time[3] - '0') + 2000;
			month  = (time[5] - '0')*10 + (time[6] - '0');
			day    = (time[8] - '0')*10 + (time[9] - '0');

			hour   = (time[11] - '0')*10 + (time[12] - '0');
			minute = (time[14] - '0')*10 + (time[15] - '0');
			second = (time[17] - '0')*10 + (time[18] - '0');

			AdjustClockTime();


			item = cJSON_GetObjectItem(root, "SupplyAirToAir");
			status.Equipment.AirToAir = item -> valueint;

			item = cJSON_GetObjectItem(root, "SupplyAirToGround");
			status.Equipment.AirToGround = item -> valueint;

			item = cJSON_GetObjectItem(root, "SupplyLife");
			status.Equipment.SupplyLife = item ->valueint;



			pJsonArray = cJSON_GetObjectItem(root, "InitDetails");
			if (pJsonArray)
			{
				int size = cJSON_GetArraySize(pJsonArray);

				for(ii = 0; ii < size; ii++)
				{
					pArrayItem = cJSON_GetArrayItem(pJsonArray, ii);
					if (pArrayItem)
					{
						item2 = cJSON_GetObjectItem(pArrayItem, "AgentID");

						if( item2 -> valueint != status.AgentID )	continue;

						else{

							item2 = cJSON_GetObjectItem(pArrayItem, "GroupAgent");
							status.GroupAgent = item2 -> valueint;

							item2 = cJSON_GetObjectItem(pArrayItem, "TeamID");
							status.TeamID = item2 -> valueint;

							item2 = cJSON_GetObjectItem(pArrayItem, "MyTeamCount");
							status.MyTeamCount = item2 -> valueint;

							item2 = cJSON_GetObjectItem(pArrayItem, "Character");
							memset(status.Character, 0 ,sizeof(status.Character));
							strncpy(status.Character, item2 -> valuestring, strlen(item2->valuestring));


							if((strcasecmp(status.Character,GENERAL) == 0))	status.CharacterID = 12;
							if((strcasecmp(status.Character,GROUP)   == 0))	status.CharacterID = 11;
							if((strcasecmp(status.Character,MAJOR)   == 0))	status.CharacterID = 10;

							Flags.isBreak = 1;
							Flags.isSendRegister = 1;
							isWakeup = 1;
							sResOutput(">>> Init ownStatus is Okay "," >>>");

							break;
						}
					}
				}
			}
			else{
				sResOutput(">>>[Exc]: ","pJsonArray >>>");
			}
		}

	}

	sResOutput(">>> "," Init Finished >>>");
	cJSON_Delete(root);
	root = NULL;

}
int Switch_Manager::ReplyException(char* strurl,char* strOutUrl,int iRetcode)
{
	printf("-----ReplyException \n");
	LOG_DEBUG("DEBUG - [SWM]: - ReplyException \n");
	if(strOutUrl==NULL)
		return -1;
	char *Rcv_buf=strurl;
		//报文回复
	Stream ptmpRequest;
		cJSON *pcmd = NULL;
			//解析报文数据
	replace(Rcv_buf, "XXEE", "");
	cJSON* pRoot = cJSON_Parse(Rcv_buf);

	if (pRoot)
	{
		pcmd = cJSON_GetObjectItem(pRoot, "cmd");
		if (pcmd)
		{

			//判断请求类型
			if (strcmp(pcmd->valuestring, "add_ads_stream") == 0)
			{
				printf("--Add_stream request exception \n");
				fflush(stdout);
				//通过
				cJSON* psessionid = cJSON_GetObjectItem(pRoot, "sessionid");
				char strsessionid[128] ={0};
				if(psessionid)
					memcpy(strsessionid,psessionid->valuestring,strlen(psessionid->valuestring)+1);
				cJSON* pToken = cJSON_GetObjectItem(pRoot, "input_url");
				char input_url[128] ={0};
				if(pToken) memcpy(input_url,pToken->valuestring,strlen(pToken->valuestring)+1);

				char output_url[128] ={0};
				cJSON* pStreamID = cJSON_GetObjectItem(pRoot, "output_url");
				if(pStreamID) memcpy(output_url,pStreamID->valuestring,strlen(pStreamID->valuestring)+1);

				cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno");

				char strSerialNo[128] ={0};
				if(pSerialNo)
					memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1);

				//cJSON *pRet_root;
				ptmpRequest.pRet_root = cJSON_CreateObject();
				ptmpRequest.Requst_Json_str(2,"cmd","add_ads_stream");
				ptmpRequest.Requst_Json_str(2,"sessionid",strsessionid);

				ptmpRequest.Requst_Json_str(1,"task_id",strsessionid);
				char txt[32] ={0};
				sprintf(txt,"%d",iRetcode);
				ptmpRequest.Requst_Json_str(2,"ret_code",txt);

				ptmpRequest.Requst_Json_str(2,"serialno",strSerialNo);
				

			}
			else if(strcmp(pcmd->valuestring, "del_ads_stream") == 0)
			{
				printf("--Del_stream request exception\n");
				fflush(stdout);
				//通过
				cJSON* psessionid = cJSON_GetObjectItem(pRoot, "sessionid");
				char strsessionid[128] ={0};
				if(psessionid)
					memcpy(strsessionid,psessionid->valuestring,strlen(psessionid->valuestring)+1);

				cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno");

				char strSerialNo[128] ={0};
				if(pSerialNo)
					memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1);
				
				ptmpRequest.pRet_root = cJSON_CreateObject();
				ptmpRequest.Requst_Json_str(2,"cmd","del_ads_stream");

				ptmpRequest.Requst_Json_str(2,"sessionid",strsessionid);

				char txt[32] ={0};
				sprintf(txt,"%d",iRetcode);
				ptmpRequest.Requst_Json_str(2,"ret_code",txt);

				ptmpRequest.Requst_Json_str(2,"serialno",strSerialNo);
				
			}
			else if(strcmp(pcmd->valuestring, "reset_device") == 0)
			{
				printf("--reset_stream request exception\n");

				fflush(stdout);
				cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno");

				char strSerialNo[128] ={0};
				if(pSerialNo)
					memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1);

				//cJSON *pRet_root;
				ptmpRequest.pRet_root = cJSON_CreateObject();
				ptmpRequest.Requst_Json_str(2,"cmd","reset_device");

				char txt[32] ={0};
				sprintf(txt,"%d",iRetcode);
				ptmpRequest.Requst_Json_str(2,"ret_code",txt);

				ptmpRequest.Requst_Json_str(2,"serialno",strSerialNo);
				
			}
			else if (strcmp(pcmd->valuestring, "change_stream") == 0)
			{
				printf("--Change_stream request exception\n");
				fflush(stdout);
				cJSON* old_psessionid = cJSON_GetObjectItem(pRoot, "old_sessionid");
				char old_strsessionid[128] ={0};
				if(old_psessionid)
					memcpy(old_strsessionid,old_psessionid->valuestring,strlen(old_psessionid->valuestring)+1);
				cJSON* psessionid = cJSON_GetObjectItem(pRoot, "sessionid");
				char strsessionid[128] ={0};
				if(psessionid)
					memcpy(strsessionid,psessionid->valuestring,strlen(psessionid->valuestring)+1);
				cJSON* pInterval = cJSON_GetObjectItem(pRoot, "interval");
				char strInterval[128] ={0};
				if(pInterval)
					memcpy(strInterval,pInterval->valuestring,strlen(pInterval->valuestring)+1);


				cJSON* pToken = cJSON_GetObjectItem(pRoot, "input_url");
				char input_url[128] ={0};
				if(pToken) memcpy(input_url,pToken->valuestring,strlen(pToken->valuestring)+1);

				char output_url[128] ={0};
				cJSON* pStreamID = cJSON_GetObjectItem(pRoot, "output_url");
				if(pStreamID) memcpy(output_url,pStreamID->valuestring,strlen(pStreamID->valuestring)+1);

				cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno");

				char strSerialNo[128] ={0};
				if(pSerialNo)
					memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1);

				//cJSON *pRet_root;
				ptmpRequest.pRet_root = cJSON_CreateObject();
				ptmpRequest.Requst_Json_str(2,"cmd","change_stream");

				char txt[32] ={0};
				sprintf(txt,"%d",iRetcode);
				ptmpRequest.Requst_Json_str(2,"ret_code",txt);

				ptmpRequest.Requst_Json_str(2,"serialno",strSerialNo);
				ptmpRequest.Send_Jsoon_str();


			}
			else if(strcmp(pcmd->valuestring, "check_session") == 0)
			{
				printf("--check_session exception\n");
				//通过
				cJSON* psessionid = cJSON_GetObjectItem(pRoot, "sessionid");
				char strsessionid[128] ={0};
				int iSeessionID = 0;
				if(psessionid)
				{
					memcpy(strsessionid,psessionid->valuestring,strlen(psessionid->valuestring)+1);
					iSeessionID = atoi(strsessionid);
				}

				cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno");
				char strSerialNo[128] ={0};
				if(pSerialNo)
					memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1);

				//cJSON *pRet_root;
				ptmpRequest.pRet_root = cJSON_CreateObject();
				ptmpRequest.Requst_Json_str(2,"cmd","check_session");

				ptmpRequest.Requst_Json_str(2,"sessionid",strsessionid);

				ptmpRequest.Requst_Json_str(1,"task_id",strsessionid);
				char txt[32] ={0};
				sprintf(txt,"%d",iRetcode);
				ptmpRequest.Requst_Json_str(2,"ret_code",txt);

				ptmpRequest.Requst_Json_str(2,"serialno",strSerialNo);
				
			}
			else if(strcmp(pcmd->valuestring, "req_ads_stream") == 0)
			{
				printf("--req stream_session exception\n");
				//通过
				cJSON* psessionid = cJSON_GetObjectItem(pRoot, "sessionid");
				char strsessionid[128] ={0};
				int iSeessionID = 0;
				if(psessionid)
				{
					memcpy(strsessionid,psessionid->valuestring,strlen(psessionid->valuestring)+1);
					iSeessionID = atoi(strsessionid);
				}

				cJSON* pSerialNo = cJSON_GetObjectItem(pRoot,"serialno");
				char strSerialNo[128] ={0};
				if(pSerialNo)
					memcpy(strSerialNo,pSerialNo->valuestring,strlen(pSerialNo->valuestring)+1);

				//cJSON *pRet_root;
				ptmpRequest.pRet_root = cJSON_CreateObject();
				ptmpRequest.Requst_Json_str(2,"cmd","req_ads_stream");

				ptmpRequest.Requst_Json_str(2,"sessionid",strsessionid);

				char strnoip[128]={0};
				strcpy(strnoip,"1.1.1.1");
				char strport[32]={0};
				strcpy(strport,"1");
				ptmpRequest.Requst_Json_str(1,"switch_ip",strnoip);
				ptmpRequest.Requst_Json_str(1,"switch_port",strport);
				char txt[32] ={0};
				sprintf(txt,"%d",iRetcode);
				ptmpRequest.Requst_Json_str(2,"ret_code",txt);

				ptmpRequest.Requst_Json_str(2,"serialno",strSerialNo);
				
			}


		}
	}
	
	char cJsonBuff[1024 * 2];
	char * m_tmp;
	m_tmp = cJSON_Print(ptmpRequest.pRet_root);
	memset(cJsonBuff, 0, sizeof(cJsonBuff));
	sprintf(cJsonBuff, "%sXXEE", m_tmp);
	free(m_tmp);
	printf("-----%s \n",cJsonBuff);
	fflush(stdout);
	cJSON_Delete(ptmpRequest.pRet_root);
	//copy to output 

	strcpy(strOutUrl,cJsonBuff);
	
	return 0;
}
Exemple #9
0
cJSON *cJSON_CreateString(const char *string)	{cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_String;item->valuestring=cJSON_strdup(string);if(!item->valuestring){cJSON_Delete(item);return 0;}}return item;}
void LoadJSONMesh(PP_Resource context,
                  PPB_OpenGLES2* gl,
                  const char* mesh,
                  Transformations* psMatrices,
                  int* piNumIndices,
                  int* piNumVertices,
                  GLuint* puiVBO,
                  GLuint* puiIBO)
{
    uint16_t* pui16Indices;
    float* pfVertices;
    float* pfTexCoords;
    float* pfNormals;
    int idx;
    int vtx;
    int iNumIndices;
    int iNumVertices;
    float fMinX;
    float fMinY;
    float fMinZ;
    float fMaxX;
    float fMaxY;
    float fMaxZ;
    float fCenterX;
    float fCenterY;
    float fCenterZ;
    cJSON *psIndices;
    cJSON *psVertices;
    cJSON *psTexCoords;
    cJSON *psNormals;
    cJSON* psBoundingBox;
    float fScale;

    cJSON *psRoot = cJSON_Parse(mesh);

    if(!psRoot)
    {
        DBG_LOG(DBG_LOG_PREFIX"No root JSON");
        return;
    }

    psIndices = cJSON_GetObjectItem(psRoot,"idx");

    if(!psIndices)
    {
        DBG_LOG(DBG_LOG_PREFIX"No indices JSON");
        cJSON_Delete(psRoot);
        return;
    }

    psVertices = cJSON_GetObjectItem(psRoot,"vtxpos");
    if(!psVertices)
    {
        DBG_LOG(DBG_LOG_PREFIX"No vertices JSON");
        cJSON_Delete(psRoot);
        return;
    }

    psTexCoords = cJSON_GetObjectItem(psRoot,"texcoord");
    if(!psTexCoords)
    {
        DBG_LOG(DBG_LOG_PREFIX"No texcoords JSON");
        cJSON_Delete(psRoot);
        return;
    }
    
    psNormals = cJSON_GetObjectItem(psRoot,"normal");
    if(!psNormals)
    {
        DBG_LOG(DBG_LOG_PREFIX"No normals JSON");
        cJSON_Delete(psRoot);
        return;
    }

    psBoundingBox = cJSON_GetObjectItem(psRoot, "bndbox");
    if(!psBoundingBox)
    {
        DBG_LOG(DBG_LOG_PREFIX"No no bndbox JSON");
        cJSON_Delete(psRoot);
        return;
    }

    iNumIndices = cJSON_GetArraySize(psIndices);

    pui16Indices = new uint16_t[iNumIndices];

    for(idx = 0; idx < iNumIndices; ++idx)
    {
        cJSON* psIndex = cJSON_GetArrayItem(psIndices, idx);
        pui16Indices[idx] = psIndex->valueint;
    }

    iNumVertices = cJSON_GetArraySize(psVertices) / 3; //GetArraySize will give the number of floats in vertex position array. Always XYZ.

    pfVertices = new float[iNumVertices * 3];
    pfTexCoords = new float[iNumVertices * 3];
    pfNormals = new float[iNumVertices * 3];
    for(vtx = 0; vtx < (iNumVertices * 3);)
    {
        cJSON* psVertex;
        cJSON* psTexC;
        cJSON* psNrm;

        psVertex = cJSON_GetArrayItem(psVertices, vtx);
        pfVertices[vtx] = psVertex->valuedouble;

        psTexC = cJSON_GetArrayItem(psTexCoords, vtx);
        pfTexCoords[vtx] = psTexC->valuedouble;

        psNrm = cJSON_GetArrayItem(psNormals, vtx);
        pfNormals[vtx] = psNrm->valuedouble;

        ++vtx;

        psVertex = cJSON_GetArrayItem(psVertices, vtx);
        pfVertices[vtx] = psVertex->valuedouble;

        psTexC = cJSON_GetArrayItem(psTexCoords, vtx);
        pfTexCoords[vtx] = 1 - psTexC->valuedouble;

        psNrm = cJSON_GetArrayItem(psNormals, vtx);
        pfNormals[vtx] = psNrm->valuedouble;

        ++vtx;

        psVertex = cJSON_GetArrayItem(psVertices, vtx);
        pfVertices[vtx] = psVertex->valuedouble;

        psTexC = cJSON_GetArrayItem(psTexCoords, vtx);
        pfTexCoords[vtx] = psTexC->valuedouble;

        psNrm = cJSON_GetArrayItem(psNormals, vtx);
        pfNormals[vtx] = psNrm->valuedouble;

        ++vtx;
    }

    fMinX = cJSON_GetArrayItem(psBoundingBox, 0)->valuedouble;
    fMinY = cJSON_GetArrayItem(psBoundingBox, 1)->valuedouble;
    fMinZ = cJSON_GetArrayItem(psBoundingBox, 2)->valuedouble;
    fMaxX = cJSON_GetArrayItem(psBoundingBox, 3)->valuedouble;
    fMaxY = cJSON_GetArrayItem(psBoundingBox, 4)->valuedouble;
    fMaxZ = cJSON_GetArrayItem(psBoundingBox, 5)->valuedouble;

    cJSON_Delete(psRoot);

    //Translation and scaling to get the object to the middle of the screen.

    Identity(psMatrices->rot);
    Identity(psMatrices->scale);
    Identity(psMatrices->xform);

	fScale = fMaxX-fMinX;
	fScale = max(fMaxY - fMinY,fScale);
	fScale = max(fMaxZ - fMinZ,fScale);
	fScale = 1.f / fScale;
    Scale(psMatrices->scale, fScale, fScale, fScale);

    fCenterX = (fMinX + fMaxX) / 2.0f;
    fCenterY = (fMinY + fMaxY) / 2.0f;
    fCenterZ = (fMinZ + fMaxZ) / 2.0f;
    Translate(psMatrices->xform, -fCenterX, -fCenterY, -fCenterZ );

    //Put the vertices and indices into device memory.

    gl->GenBuffers(context, 1, puiVBO);
    gl->GenBuffers(context, 1, puiIBO);

    gl->BindBuffer(context, GL_ARRAY_BUFFER, *puiVBO);
    gl->BufferData(context, GL_ARRAY_BUFFER, sizeof(GLfloat)*(iNumVertices*9), NULL, GL_STATIC_DRAW);
    gl->BufferSubData(context, GL_ARRAY_BUFFER, 0, sizeof(GLfloat)*(iNumVertices*3), pfVertices);
    gl->BufferSubData(context, GL_ARRAY_BUFFER, sizeof(GLfloat)*(iNumVertices*3), sizeof(GLfloat)*(iNumVertices*3), pfTexCoords);
    gl->BufferSubData(context, GL_ARRAY_BUFFER, sizeof(GLfloat)*(iNumVertices*6), sizeof(GLfloat)*(iNumVertices*3), pfNormals);
    gl->BindBuffer(context, GL_ARRAY_BUFFER, 0);

    gl->BindBuffer(context, GL_ELEMENT_ARRAY_BUFFER, *puiIBO);
    gl->BufferData(context, GL_ELEMENT_ARRAY_BUFFER, sizeof(GLushort)*iNumIndices, pui16Indices, GL_STATIC_DRAW);
    gl->BindBuffer(context, GL_ELEMENT_ARRAY_BUFFER, 0);

    delete [] pui16Indices;
    delete [] pfVertices;
    delete [] pfTexCoords;

    *piNumIndices = iNumIndices;
    *piNumVertices = iNumVertices;
}
	void App42GameResponse::init()
	{
		if (_result != 200)
		{
			Util::app42Trace("App42Game failed result is %d", _result);
			buildErrorMessage();
			return;
		}
		cJSON *ptrBody = cJSON_Parse(_body.c_str());
		cJSON* ptrApp42 = Util::getJSONChild("app42", ptrBody);
		cJSON* ptrResponse = Util::getJSONChild("response", ptrApp42);
		cJSON* ptrGames = Util::getJSONChild("games", ptrResponse);
		if (ptrGames)
		{
			cJSON* ptrGame = Util::getJSONChild("game", ptrGames);

			cJSON* child = ptrGame;
			if (child->type == cJSON_Array)
			{
				child = child->child;
			}

			while (child != NULL && child->type == cJSON_Object)
			{
				App42Game app42Game;
				app42Game.name = Util::getJSONString("name", child);
				app42Game.description = Util::getJSONString("description", child);
				games.push_back(app42Game);
				child = child->next;
				if (Util::getJSONChild("scores", ptrGame))
				{
					cJSON* ptrScores = Util::getJSONChild("scores", ptrGame);
					cJSON* ptrScore = Util::getJSONChild("score", ptrScores);
					cJSON* child = ptrScore;
					if (child->type == cJSON_Array)
					{
						child = child->child;
					}
					while (child != NULL && child->type == cJSON_Object)
					{
						App42Score app42Score;
						app42Score.setUserName(Util::getJSONString("userName", child));
						app42Score.setRank(Util::getJSONDouble("rank", child));
						app42Score.setScoreId(Util::getJSONString("scoreId", child));
						app42Score.setScoreValue(Util::getJSONDouble("value", child));
						app42Score.setCreatedOn(Util::getJSONString("createdOn", child));

						cJSON* ptrFacebookProfile = Util::getJSONChild("facebookProfile", child);
						if (ptrFacebookProfile)
						{

							app42Score.facebookProfile.setName(Util::getJSONString("name", ptrFacebookProfile));
							app42Score.facebookProfile.setFbId(Util::getJSONString("id", ptrFacebookProfile));
							app42Score.facebookProfile.setPicture(Util::getJSONString("picture", ptrFacebookProfile));
						}

						cJSON *ptrJsonDoc = Util::getJSONChild("jsonDoc", child);
						if (ptrJsonDoc != NULL)
						{
							vector<JSONDocument> docArray;
							if (ptrJsonDoc->type == cJSON_Array)
							{
								ptrJsonDoc = ptrJsonDoc->child;
							}
							while (ptrJsonDoc != NULL && ptrJsonDoc->type == cJSON_Object)
							{
								JSONDocument jsonDOC;
								buildJsonDocument(ptrJsonDoc, &jsonDOC);
								ptrJsonDoc = ptrJsonDoc->next;
								docArray.push_back(jsonDOC);
							}
							app42Score.setJsonDocList(docArray);
						}
						scores.push_back(app42Score);
						child = child->next;
					}
				}
			}
		}
		else
		{
			setTotalRecords();
		}


		cJSON_Delete(ptrBody);
	}
Exemple #12
0
void AnalysisJson(char *buffer)
{
	cJSON *res, *item;

	if(!(res = cJSON_Parse(buffer)))
	{
		sNetOutput(">>>[ERR] Analisis json buffer failed in	 analysisjson Network.c "," >>>");
		return;
	}

	if((item = cJSON_GetObjectItem(res, "Type")))
	{

		if (strcasecmp(item -> valuestring, "Init") == 0)
		{
			AnalysisInitJson(buffer);

		}

		if (strcasecmp(item -> valuestring, "Register") == 0)
		{
			AnalysisRegisterJson(buffer);

		}

		if (strcasecmp(item -> valuestring, "Formation") == 0)
		{
			AnalysisFormationJson(buffer);

		}

		if (strcasecmp(item -> valuestring, "GroupFormation") == 0)
		{
			AnalysisGroupFormationJson(buffer);
		}

		if (strcasecmp(item -> valuestring, "RegisterAnswer") == 0)
		{
			item = cJSON_GetObjectItem(res, "CmdID");
			if( strcasecmp(status.SendCmdID, item->valuestring) == 0)
			{
				Flags.registers.GetAnswer = 1;
				printf("^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^\n");
				printf("^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^\n");
				printf("\n");

				printf("     Initialization and Devided Into Groups Finished\n");
				printf("\n");

				printf("^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^\n");
				printf("^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^\n");

			}
			else	sResOutput(">>> [ERR] RegisterAnswer in network.c strcasecmp CmdID "," >>>");
		}


		if (strcasecmp(item -> valuestring, "GroupFormationAnswer") == 0)
		{
			item = cJSON_GetObjectItem(res, "CmdID");
			if( strcasecmp(status.SendCmdID, item->valuestring) == 0)
			{
				if ( ++Flags.temp == (status.MyTeamCount - 1) ){
					Flags.temp = 0;
					Flags.isSendGroupFormation = 1;
				}
			}
			else	sResOutput(">>> [ERR] GroupFormationAnswer in network.c strcasecmp CmdID "," >>>");


		}

		if (strcasecmp(item -> valuestring, "RecvMission") == 0)
		{
			item = cJSON_GetObjectItem(res, "CmdID");
			if( strcasecmp(status.SendCmdID, item->valuestring) == 0)
			{
				if ( ++Flags.temp == (status.MyTeamCount - 1) ){
					Flags.temp = 0;
					Flags.isSendFinishedDownload = 1;
				}
			}
			else	sResOutput(">>> [ERR] RecvMission in network.c strcasecmp CmdID "," >>>");

		}


		if (strcasecmp(item -> valuestring, "Mission") == 0)
		{
			AnalysisMissionJson(buffer);
		}

		if (strcasecmp(item -> valuestring, "MissionDecision") == 0)
		{
			AnalysisMissionDecisionJson(buffer);
		}

		if (strcasecmp(item -> valuestring, "DecisionDownload") == 0)
		{
			AnalysisDecisionDownloadJson(buffer);
		}


		if (strcasecmp(item -> valuestring, "Adjust") == 0)
		{
			AnalysisAdjustJson(buffer);
		}

		if (strcasecmp(item -> valuestring, "Collection") == 0)
		{
			AnalysisCollectionJson(buffer);
		}


		if (strcasecmp(item -> valuestring, "ReInit") == 0)
		{
			AnalysisReInitJson(buffer);
		}

		if (strcasecmp(item -> valuestring, "Reset") == 0)
		{
			AnalysisResetJson(buffer);
		}

		if (strcasecmp(item -> valuestring, "ChangeMission") == 0)
		{
			if ( Flags.changeMissionf ){
				AnalysisChangeMissionJson(buffer);
				Flags.changeMissionf = 0;
			}
		}

		if (strcasecmp(item -> valuestring, "PreAutoFormation") == 0)
		{

		}

		if (strcasecmp(item -> valuestring, "StartMission") == 0)
		{
			if ( Flags.startMissionf ){
				AnalysisStartMissionJson(buffer);
				Flags.startMissionf = 0;
			}
		}


	}

	cJSON_Delete(res);
	res = NULL;
}
Exemple #13
0
int entry_city_weibo(struct ev_loop *loop, char *data, size_t size)
{
	int  ok  = API_OK;
	char *body = NULL;
	cJSON *obj = NULL;
	cJSON *temp= NULL;
	
	struct cnt_pool *redis_pool = NULL;
	struct cnt_pool *static_pool = NULL;
	struct cnt_pool *weidb_pool = NULL;
	
	void *redis_priority = NULL;
	void *redis_receive = NULL;
	void *redis_weibo = NULL;
	void *redis_senderInfo = NULL;
	void *redis_expire = NULL;
	struct async_ctx *task = NULL; 
/*从配置文件中,得到IP,和port*/
	int i = get_redis_link_index();
	char *host = g_weibo_cfg_file.weibo_store[i].host;
	short port = g_weibo_cfg_file.weibo_store[i].port;

/*一次性取出程序执行所有连接数,如果连接数不够,将数据打印到LOG日志里,程序返回,打印错误码,
  这样做是为了防止当连接数到达连接池顶峰时,一直取不到连接,代码一直夯在哪里*/

//	redis_priority = redis_pool_gain(loop, &redis_pool,host,port);
        redis_priority = pool_api_gain(loop, &redis_pool,host,port);
	if (NULL==redis_priority)
	{
		x_printf(W, "%s\n",data);
		ok = REDIS_POOL_GAIN_FAILED;
		return ok;
	}


//	redis_weibo = redis_pool_gain(loop, &redis_pool,host,port);
        redis_weibo = pool_api_gain(loop, &redis_pool,host,port);
	if (NULL==redis_weibo)
	{
		x_printf(W, "%s\n",data);
		ok = REDIS_POOL_GAIN_FAILED;
		return ok;
	}

//	redis_senderInfo = redis_pool_gain(loop, &redis_pool,host,port);
        redis_senderInfo = pool_api_gain(loop, &redis_pool,host,port);
	if (NULL==redis_senderInfo)
	{
		x_printf(W, "%s\n",data);
		ok = REDIS_POOL_GAIN_FAILED;
		return ok;
	}

//	redis_expire = redis_pool_gain(loop, &redis_pool,host,port);
        redis_expire = pool_api_gain(loop, &redis_pool,host,port);
	if (NULL==redis_expire)
	{
		x_printf(W, "%s\n",data);
		ok = REDIS_POOL_GAIN_FAILED;
		return ok;
	}
	
	i = get_redis_static_link_index();
	host = g_weibo_cfg_file.weibo_static[i].host;
	port = g_weibo_cfg_file.weibo_static[i].port;
//	redis_receive = redis_pool_gain(loop, &static_pool,host,port);
        redis_receive = pool_api_gain(loop, &static_pool,host,port);
	if (NULL==redis_receive)
	{
		x_printf(W, "%s\n",data);
		ok = REDIS_POOL_GAIN_FAILED;
		return ok;
	}

	i = get_weidb_link_index();
	host = g_weibo_cfg_file.weidb[i].host;
	port = g_weibo_cfg_file.weidb[i].port;
	task = (struct async_ctx *)pool_api_gain(loop, &weidb_pool, host, port);
	if (NULL==task)
	{
		x_printf(W, "%s\n",data);
		ok = HTTP_POOL_GAIN_FAILED;
		return ok;
	}
	Weibo *wb = calloc(1, sizeof(Weibo));//开空间并初始化
	if(!wb){
		ok = API_NO_MEMORY;
		goto ERROR_CITY;	
	}
	wb->loop = loop;
	/******判断传入进来的参数******/
	if (NULL == data || 0 == size) {
		ok = API_NO_DATA;
		goto ERROR_CITY;
	}else{
		if (size > MAX_LEN_STRING){
			ok = API_DATA_TOO_LONG;
			goto ERROR_CITY;
		}
	}

	/*data cjson parse*/

	obj = cJSON_Parse (data);
	if (NULL == obj) {
		ok = API_INVALID_JSON;
		goto ERROR_CITY;
	}
	wb->cjson = obj;

	/*check regionCode*/
	temp = cJSON_GetObjectItem(obj, "regionCode");
	if (NULL==temp){
		ok = API_INVALID_REGIONCODE;
		goto ERROR_CITY;
	}
	wb->regionCode = temp->valuestring;
	if(!wb->regionCode){
		ok = API_INVALID_REGIONCODE;
		goto ERROR_CITY;
	}
	/*check other*/
	ok = parse_parments (wb, obj);
	if (ok != API_OK){
		goto ERROR_CITY;
	}
	wb->loop = loop;
	wb->pool = redis_pool;
	wb->redisPriority = redis_priority;

	/*receiver:priority */
	ok = weibo_set_receive(wb,loop,redis_receive,static_pool);
	if (ok != API_OK){
		goto ERROR_CITY;
	}

	/*bizid:weibo and bizid:senderInfo*/
	ok = weibo_send_info(wb,loop,redis_weibo,redis_senderInfo,redis_expire,redis_pool);
	if (ok != API_OK){
		goto ERROR_CITY;
	}

	/*cJSON form turn into string form*/
	body = cJSON_Print(obj);
	if (!body){
		ok = JSON_OP_FAIL;
		goto ERROR_CITY;
	}
	
	/*data transmitting*/
	ok=weibo_data_transmit(body,"weidb_city",loop,weidb_pool,task,host,port);
	if (ok != API_OK){
		goto ERROR_CITY;
	}
	free(body);
	/*cant't free json,free it in callback*/
	obj = NULL;
	return ok;
ERROR_CITY:
	if (obj){
		cJSON_Delete(obj);
	}
	if(body){
		free(body);
	}
	return ok;
	
}
Exemple #14
0
int entry_personal_weibo( struct ev_loop *loop, char *data, size_t size,char *bizid )
{
	int ok = API_OK;
	char *body = NULL;
	cJSON *obj = NULL;

	struct cnt_pool *redis_pool = NULL;
	struct cnt_pool *weidb_pool = NULL;
	

        struct async_ctx *redis_priority;
        struct async_ctx *redis_weibo;
        struct async_ctx *redis_senderInfo;
        struct async_ctx *redis_expire;
	struct async_ctx *task = NULL; 

	Weibo wb = {};
	int i = get_redis_link_index();
	char *host = g_weibo_cfg_file.weibo_store[i].host;
	short port = g_weibo_cfg_file.weibo_store[i].port;

/*一次性取出程序执行所有连接数,如果连接数不够,将数据打印到LOG日志里,程序返回,打印错误码,
  这样做是为了防止当连接数到达连接池顶峰时,一直取不到连接,代码一直夯在哪里*/
//	redis_priority = redis_pool_gain(loop, &redis_pool,host,port);
        redis_priority = (struct async_ctx *)pool_api_gain(loop, &redis_pool,host,port);
	if (NULL==redis_priority)
	{
		x_printf(W, "%s\n",data);
		ok = REDIS_POOL_GAIN_FAILED;
		return ok;
	}

	redis_weibo = (struct async_ctx *)pool_api_gain(loop, &redis_pool,host,port);
	if (NULL==redis_weibo)
	{
		x_printf(W, "%s\n",data);
		ok = REDIS_POOL_GAIN_FAILED;
		return ok;
	}

        redis_senderInfo = (struct async_ctx *)pool_api_gain(loop, &redis_pool,host,port);
	if (NULL==redis_senderInfo)
	{
		x_printf(W, "%s\n",data);
		ok = REDIS_POOL_GAIN_FAILED;
		return ok;
	}

        redis_expire = (struct async_ctx *)pool_api_gain(loop, &redis_pool,host,port);
	if (NULL==redis_expire)
	{
		x_printf(W, "%s\n",data);
		ok = REDIS_POOL_GAIN_FAILED;
		return ok;
	}

	i = get_weidb_link_index();
	host = g_weibo_cfg_file.weidb[i].host;
	port = g_weibo_cfg_file.weidb[i].port;
	task = (struct async_ctx *)pool_api_gain(loop, &weidb_pool, host, port);
	if (NULL==task)
	{
		x_printf(W, "%s\n",data);
		ok = HTTP_POOL_GAIN_FAILED;
		return ok;
	}

	/****判断传入进来的参数******/

	if (NULL == data || 0 == size) {
		ok = API_NO_DATA;
		goto ERROR_PERSONAL;
	}else {
		if (size > MAX_LEN_STRING){
			ok = API_DATA_TOO_LONG;
			goto ERROR_PERSONAL;
		}
	}

	/*data cjson parse*/
	obj = cJSON_Parse (data);
	if (NULL == obj) {
		ok = API_INVALID_JSON;
		goto ERROR_PERSONAL;
	}

	/*check parments*/
	ok = parse_parments (&wb, obj);
	if (ok != API_OK){
		goto ERROR_PERSONAL;
	}

	strcpy(bizid,wb.bizid);//将生成的bizid,带回去

	/*receiverAccountID:weiboPriority*/
	ok = weibo_set_priority(wb.receiverAccountID,&wb,loop,redis_priority,redis_pool);
	if (ok != API_OK){
		goto ERROR_PERSONAL;
	}

	/*bizid:weibo and bizid:senderInfo*/
	ok = weibo_send_info(&wb, loop,redis_weibo,redis_senderInfo,redis_expire,redis_pool);
	if (ok != API_OK){
		goto ERROR_PERSONAL;
	}

	/*cJSON form turn into string form*/
	body = cJSON_Print(obj);
	if (!body){
		ok = JSON_OP_FAIL;
		goto ERROR_PERSONAL;
	}
	/*data transmitting*/
	ok = weibo_data_transmit(body,"weidb_personal",loop,weidb_pool,task,host,port);
	if (ok != API_OK){
		goto ERROR_PERSONAL;
	}

	free(body);
	cJSON_Delete(obj);
	
	return ok;

ERROR_PERSONAL:
	if (obj){
		cJSON_Delete(obj);
	}
	if(body){
		free(body);
	}
	return ok;
}
const char* SerializeReflection(ShaderInfo* psReflection)
{
    cJSON* root;

    cJSON_Hooks hooks;
    hooks.malloc_fn = jsonMalloc;
    hooks.free_fn = jsonFree;
    cJSON_InitHooks(&hooks);

    root=cJSON_CreateObject();
    cJSON_AddItemToObject(root, "ui32MajorVersion", cJSON_CreateNumber(psReflection->ui32MajorVersion));
    cJSON_AddItemToObject(root, "ui32MinorVersion", cJSON_CreateNumber(psReflection->ui32MinorVersion));

    cJSON_AddItemToObject(root, "ui32NumInputSignatures", cJSON_CreateNumber(psReflection->ui32NumInputSignatures));

    for(uint32_t i = 0; i < psReflection->ui32NumInputSignatures; ++i)
    {
        std::string name;
        name += "input";
		AppendIntToString(name, i);

        cJSON* obj = cJSON_CreateObject();
        cJSON_AddItemToObject(root, name.c_str(), obj);

        WriteInOutSignature(psReflection->psInputSignatures+i, obj);
    }

    cJSON_AddItemToObject(root, "ui32NumOutputSignatures", cJSON_CreateNumber(psReflection->ui32NumOutputSignatures));

    for(uint32_t i = 0; i < psReflection->ui32NumOutputSignatures; ++i)
    {
        std::string name;
        name += "output";
        AppendIntToString(name, i);

        cJSON* obj = cJSON_CreateObject();
        cJSON_AddItemToObject(root, name.c_str(), obj);

        WriteInOutSignature(psReflection->psOutputSignatures+i, obj);
    }

    cJSON_AddItemToObject(root, "ui32NumResourceBindings", cJSON_CreateNumber(psReflection->ui32NumResourceBindings));

    for(uint32_t i = 0; i < psReflection->ui32NumResourceBindings; ++i)
    {
        std::string name;
        name += "resource";
        AppendIntToString(name, i);

        cJSON* obj = cJSON_CreateObject();
        cJSON_AddItemToObject(root, name.c_str(), obj);

        WriteResourceBinding(psReflection->psResourceBindings+i, obj);
    }

    cJSON_AddItemToObject(root, "ui32NumConstantBuffers", cJSON_CreateNumber(psReflection->ui32NumConstantBuffers));

    for(uint32_t i = 0; i < psReflection->ui32NumConstantBuffers; ++i)
    {
        std::string name;
        name += "cbuf";
        AppendIntToString(name, i);

        cJSON* obj = cJSON_CreateObject();
        cJSON_AddItemToObject(root, name.c_str(), obj);

        WriteConstantBuffer(psReflection->psConstantBuffers+i, obj);
    }

    //psThisPointerConstBuffer is a cache. Don't need to write this out.
    //It just points to the $ThisPointer cbuffer within the psConstantBuffers array.

    for(uint32_t i = 0; i < psReflection->ui32NumClassTypes; ++i)
    {
        std::string name;
        name += "classType";
        AppendIntToString(name, i);

        cJSON* obj = cJSON_CreateObject();
        cJSON_AddItemToObject(root, name.c_str(), obj);

        WriteClassType(psReflection->psClassTypes+i, obj);
    }

    for(uint32_t i = 0; i < psReflection->ui32NumClassInstances; ++i)
    {
        std::string name;
        name += "classInst";
        AppendIntToString(name, i);

        cJSON* obj = cJSON_CreateObject();
        cJSON_AddItemToObject(root, name.c_str(), obj);

        WriteClassInstance(psReflection->psClassInstances+i, obj);
    }

    //psReflection->aui32TableIDToTypeID
    //psReflection->aui32ConstBufferBindpointRemap

    cJSON_AddItemToObject(root, "eTessPartitioning", cJSON_CreateNumber(psReflection->eTessPartitioning));
    cJSON_AddItemToObject(root, "eTessOutPrim", cJSON_CreateNumber(psReflection->eTessOutPrim));


    const char* jsonString = cJSON_Print(root);

    cJSON_Delete(root);

    return jsonString;
}
Exemple #16
0
cJSON *cJSON_CreateDoubleArray(const double *numbers,int count)	{int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!n){cJSON_Delete(a);return 0;}if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
Exemple #17
0
static int cJSONUtils_ApplyPatch(cJSON *object, cJSON *patch)
{
    cJSON *op = NULL;
    cJSON *path = NULL;
    cJSON *value = NULL;
    cJSON *parent = NULL;
    int opcode = 0;
    unsigned char *parentptr = NULL;
    unsigned char *childptr = NULL;

    op = cJSON_GetObjectItem(patch, "op");
    path = cJSON_GetObjectItem(patch, "path");
    if (!op || !path)
    {
        /* malformed patch. */
        return 2;
    }

    /* decode operation */
    if (!strcmp(op->valuestring, "add"))
    {
        opcode = 0;
    }
    else if (!strcmp(op->valuestring, "remove"))
    {
        opcode = 1;
    }
    else if (!strcmp(op->valuestring, "replace"))
    {
        opcode = 2;
    }
    else if (!strcmp(op->valuestring, "move"))
    {
        opcode = 3;
    }
    else if (!strcmp(op->valuestring, "copy"))
    {
        opcode = 4;
    }
    else if (!strcmp(op->valuestring, "test"))
    {
        /* compare value: {...} with the given path */
        return cJSONUtils_Compare(cJSONUtils_GetPointer(object, path->valuestring), cJSON_GetObjectItem(patch, "value"));
    }
    else
    {
        /* unknown opcode. */
        return 3;
    }

    /* Remove/Replace */
    if ((opcode == 1) || (opcode == 2))
    {
        /* Get rid of old. */
        cJSON_Delete(cJSONUtils_PatchDetach(object, (unsigned char*)path->valuestring));
        if (opcode == 1)
        {
            /* For Remove, this is job done. */
            return 0;
        }
    }

    /* Copy/Move uses "from". */
    if ((opcode == 3) || (opcode == 4))
    {
        cJSON *from = cJSON_GetObjectItem(patch, "from");
        if (!from)
        {
            /* missing "from" for copy/move. */
            return 4;
        }

        if (opcode == 3)
        {
            /* move */
            value = cJSONUtils_PatchDetach(object, (unsigned char*)from->valuestring);
        }
        if (opcode == 4)
        {
            /* copy */
            value = cJSONUtils_GetPointer(object, from->valuestring);
        }
        if (!value)
        {
            /* missing "from" for copy/move. */
            return 5;
        }
        if (opcode == 4)
        {
            value = cJSON_Duplicate(value, 1);
        }
        if (!value)
        {
            /* out of memory for copy/move. */
            return 6;
        }
    }
    else /* Add/Replace uses "value". */
    {
        value = cJSON_GetObjectItem(patch, "value");
        if (!value)
        {
            /* missing "value" for add/replace. */
            return 7;
        }
        value = cJSON_Duplicate(value, 1);
        if (!value)
        {
            /* out of memory for add/replace. */
            return 8;
        }
    }

    /* Now, just add "value" to "path". */

    /* split pointer in parent and child */
    parentptr = cJSONUtils_strdup((unsigned char*)path->valuestring);
    childptr = (unsigned char*)strrchr((char*)parentptr, '/');
    if (childptr)
    {
        *childptr++ = '\0';
    }
    parent = cJSONUtils_GetPointer(object, (char*)parentptr);
    cJSONUtils_InplaceDecodePointerString(childptr);

    /* add, remove, replace, move, copy, test. */
    if (!parent)
    {
        /* Couldn't find object to add to. */
        free(parentptr);
        cJSON_Delete(value);
        return 9;
    }
    else if (cJSON_IsArray(parent))
    {
        if (!strcmp((char*)childptr, "-"))
        {
            cJSON_AddItemToArray(parent, value);
        }
        else
        {
            cJSON_InsertItemInArray(parent, atoi((char*)childptr), value);
        }
    }
    else if (cJSON_IsObject(parent))
    {
        cJSON_DeleteItemFromObject(parent, (char*)childptr);
        cJSON_AddItemToObject(parent, (char*)childptr, value);
    }
    else
    {
        cJSON_Delete(value);
    }
    free(parentptr);

    return 0;
}
Exemple #18
0
cJSON *cJSON_CreateStringArray(const char **strings,int count)	{int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateString(strings[i]);if(!n){cJSON_Delete(a);return 0;}if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
Exemple #19
0
int dispatcher(cJSON *dsp,int funnum)
{                                 
	int rv;   
	switch(funnum){
	case 0:
		rv = cli_set_user_data(dsp);
		break;
	case 1:
		rv = cli_show_udf(dsp);
		break;
	case 2:
		rv = cli_show_ruleset(dsp);
		break;
	case 3:
		rv = cli_add_class_entry(dsp);
		break;
	case 4:
		rv = cli_reboot_system(dsp);
		break;
	case 5:
		rv = cli_reset_system(dsp);
		break;
	case 6:
		rv = cli_restore_configuration(dsp);
		break;
	case 7:
		rv = cli_save_config(dsp);
		break;
	case 8:
		rv = cli_show_config_file(dsp);
		break;
	case 9:
		rv = cli_show_system(dsp);
		break;
	case 10:
		rv = cli_show_system_verbose(dsp);
		break;
	case 11:
		rv = cli_show_board_info(dsp);
		break;
	case 12:
		rv = cli_httpd_start_restrat(dsp);
		break;
	case 13:
		rv = cli_httpd_stop(dsp);
		break;
	case 14:
		rv = cli_httpd_restore_configuration(dsp);
		break;
	case 15:
		rv = cli_get_httpd_status(dsp);
		break;
	case 16:
		rv = cli_show_failover(dsp);
		break;
	case 17:
		rv = cli_show_backup(dsp);
		break;
	case 18:
		rv = cli_exit_shell(dsp);
		break;
	case 19:
		rv = cli_set_is(dsp);
		break;
	case 20:
		rv = cli_set_am(dsp);
		break;
	case 21:
		rv = cli_set_debug_flag(dsp);
		break;
	case 22:
		rv = cli_r_int(dsp);
		break;
	case 23:
		rv = cli_r_int_int(dsp);
		break;
	case 24:
		rv = cli_r_vsc(dsp);
		break;
	case 25:
		rv = cli_show_subtable(dsp);
		break;
	case 26:
		rv = cli_start_capture(dsp);
		break;
	default:
		printf("dispatcher error.\n");
		rv = -1;
	}
	cJSON_Delete(dsp);
	return rv;
	} 
Exemple #20
0
static cJSON *parse_cell_env(void *payload, size_t payloadlen)
{
  struct conman_event_cell_environment_s *cenv = payload;
  char buf[32];
  cJSON *root;
  cJSON *obj = NULL;
  cJSON *array = NULL;
  unsigned int i;

  if (payloadlen < sizeof(*cenv))
    return NULL;
  if (payloadlen != sizeof(*cenv)
                    + cenv->num_neighbors * sizeof(cenv->neighbors[0]))
    return NULL;

  root = cJSON_CreateObject();
  if (!root)
    return NULL;

  if (cenv->have_serving)
    {
      obj = cJSON_CreateNamedObject("serving");
      if (!obj)
        goto err_free;

      switch (cenv->serving.type)
        {
          case CONMAN_CELL_ENVIRONMENT_TYPE_GSM:
            cJSON_AddStringToObject(obj, "type", "GSM");
            break;
          case CONMAN_CELL_ENVIRONMENT_TYPE_UMTS:
            cJSON_AddStringToObject(obj, "type", "UMTS");
            break;
          default:
            cJSON_AddStringToObject(obj, "type", "unknown");
            break;
        }

      cJSON_AddNumberToObject(obj, "mcc", cenv->serving.mcc);
      cJSON_AddNumberToObject(obj, "mnc", cenv->serving.mnc);
      cJSON_AddNumberToObject(obj, "lac", cenv->serving.lac);

      snprintf(buf, sizeof(buf), "%X", cenv->serving.cell_id);
      cJSON_AddStringToObject(obj, "cellid", buf);

      if (cenv->serving.signal_dbm >= -256 && cenv->serving.signal_dbm < 0)
        cJSON_AddNumberToObject(obj, "signal_dbm", cenv->serving.signal_dbm);

      if (cenv->serving.type == CONMAN_CELL_ENVIRONMENT_TYPE_UMTS &&
          cenv->serving.sc != 0xffff)
        cJSON_AddNumberToObject(obj, "sc", cenv->serving.sc);

      if (cenv->serving.type == CONMAN_CELL_ENVIRONMENT_TYPE_GSM &&
          cenv->serving.bsic != 0xff)
        cJSON_AddNumberToObject(obj, "bsic", cenv->serving.bsic);

      if (cenv->serving.type == CONMAN_CELL_ENVIRONMENT_TYPE_GSM &&
          cenv->serving.arfcn != 0xffff)
        cJSON_AddNumberToObject(obj, "arfcn", cenv->serving.arfcn);

      cJSON_PackChild(obj);
      cJSON_AddNamedItemToObject(root, obj);
      obj = NULL;
    }

  if (cenv->have_signal_qual)
    {
      obj = cJSON_CreateNamedObject("signal_qual");
      if (!obj)
        goto err_free;

      if (cenv->signal_qual.rssi >= -256 && cenv->signal_qual.rssi < 0)
        cJSON_AddNumberToObject(obj, "rssi", cenv->signal_qual.rssi);

      if (cenv->signal_qual.qual >= 0)
        cJSON_AddNumberToObject(obj, "qual", cenv->signal_qual.qual);

      cJSON_PackChild(obj);
      cJSON_AddNamedItemToObject(root, obj);
      obj = NULL;
    }

  if (cenv->num_neighbors > 0)
    {
      array = cJSON_CreateNamedArray("neighbors");
      if (!array)
        goto err_free;

      for (i = 0; i < cenv->num_neighbors; i++)
        {
          obj = cJSON_CreateObject();
          if (!obj)
            goto err_free;

          switch (cenv->neighbors[i].type)
            {
              case CONMAN_CELL_ENVIRONMENT_TYPE_GSM:
                cJSON_AddStringToObject(obj, "type", "GSM");
                break;
              case CONMAN_CELL_ENVIRONMENT_TYPE_UMTS:
                cJSON_AddStringToObject(obj, "type", "UMTS");
                break;
              default:
                cJSON_AddStringToObject(obj, "type", "unknown");
                break;
            }

          if (cenv->neighbors[i].have_cellid)
            {
              snprintf(buf, sizeof(buf), "%X", cenv->neighbors[i].cell_id);
              cJSON_AddStringToObject(obj, "cellid", buf);
            }

          if (cenv->neighbors[i].have_mcc_mnc_lac)
            {
              cJSON_AddNumberToObject(obj, "mcc", cenv->neighbors[i].mcc);
              cJSON_AddNumberToObject(obj, "mnc", cenv->neighbors[i].mnc);
              cJSON_AddNumberToObject(obj, "lac", cenv->neighbors[i].lac);
            }

          if (cenv->neighbors[i].have_signal_dbm)
            {
              cJSON_AddNumberToObject(obj, "signal_dbm", cenv->neighbors[i].signal_dbm);
            }

          if (cenv->neighbors[i].have_bsic)
            {
              cJSON_AddNumberToObject(obj, "bsic", cenv->neighbors[i].bsic);
            }

          if (cenv->neighbors[i].have_arfcn)
            {
              cJSON_AddNumberToObject(obj, "arfcn", cenv->neighbors[i].arfcn);
            }

          if (cenv->neighbors[i].have_sc)
            {
              cJSON_AddNumberToObject(obj, "sc", cenv->neighbors[i].sc);
            }

          cJSON_PackChild(obj);
          cJSON_AddItemToArray(array, obj);
          obj = NULL;
        }

      cJSON_PackChild(array);
      cJSON_AddNamedItemToObject(root, array);
      array = NULL;
    }

  cJSON_PackChild(root);
  return root;

err_free:
  cJSON_Delete(obj);
  cJSON_Delete(array);
  cJSON_Delete(root);
  return NULL;
}
Exemple #21
0
void AnalysisReInitJson(char *buffer)
{
	cJSON *root, *item, *item2;
	cJSON *pJsonArray = NULL;
	cJSON *pArrayItem = NULL;
	int ii;

	if(!(root = cJSON_Parse(buffer)))
	{
		return;
	}


	if((item = cJSON_GetObjectItem(root, "Type")))
	{
		if (strcasecmp(item -> valuestring, "ReInit") == 0)
		{
			item = cJSON_GetObjectItem(root, "AliveStatus");
			if(strcasecmp(item -> valuestring, status.AliveStatus) == 0)
			{
				item = cJSON_GetObjectItem(root, "CmdID");
				memset(status.AnswerCmdID,0,sizeof(status.AnswerCmdID));
				strncpy(status.AnswerCmdID, item->valuestring, strlen(item->valuestring));

				if((item = cJSON_GetObjectItem(root, "NeedAnswer")))
				{
					if(strcasecmp(item -> valuestring, YES) == 0)
					{
						//需要相应,则给对方发送相应。xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
						//这里是不是要改成验证CMDID的格式,那么打包的函数就不应该使用CreateMultiplexJson
						AgentAnswer = CreateMultiplexJson("RecvReInit", status.AnswerCmdID);

						pthread_mutex_lock(&Flags.mutex);
						SendToOthers(MAJORPC, AgentAnswer);
						pthread_mutex_unlock(&Flags.mutex);

						free(AgentAnswer);
						AgentAnswer = NULL;
					}
				}

				Flags.RecvPcMode = 1;

				if((item = cJSON_GetObjectItem(root, "MajorAgent")))
				{
					status.MajorAgent = item -> valueint;
				}

				item = cJSON_GetObjectItem(root, "IsAttack");
				strncpy(mission.IsAttack, item->valuestring, strlen(item->valuestring));

				item = cJSON_GetObjectItem(root, "TeamCount");
				TeamCount = item -> valueint;

				item = cJSON_GetObjectItem(root, "Distance");
				mission.Distance = item -> valueint;

				pJsonArray = cJSON_GetObjectItem(root, "ReInitDetails");
				if (pJsonArray)
				{
					int size = cJSON_GetArraySize(pJsonArray);
//					TeamCount = size;
					for(ii = 0; ii < size; ii++)
					{
						pArrayItem = cJSON_GetArrayItem(pJsonArray, ii);
						if (pArrayItem)
						{
							item2 = cJSON_GetObjectItem(pArrayItem, "AgentID");

							if( item2 -> valueint != status.AgentID )	continue;

							else{

								item2 = cJSON_GetObjectItem(pArrayItem, "GroupAgent");
								status.GroupAgent = item2 -> valueint;

								item2 = cJSON_GetObjectItem(pArrayItem, "TeamID");
								status.TeamID = item2 -> valueint;

								item2 = cJSON_GetObjectItem(pArrayItem, "Character");
								strncpy(status.Character, item2 -> valuestring, strlen(item2->valuestring));

								item2 = cJSON_GetObjectItem(pArrayItem, "Shape");
								strncpy(status.TeamShape, item2 -> valuestring, strlen(item2->valuestring));

								item2 = cJSON_GetObjectItem(pArrayItem, "Mission");
								strncpy(status.TeamMission, item2->valuestring, strlen(item2->valuestring));

								if((strcasecmp(status.Character,GENERAL) == 0))	status.CharacterID = 12;
								if((strcasecmp(status.Character,GROUP)   == 0))	status.CharacterID = 11;
								if((strcasecmp(status.Character,MAJOR)   == 0))	status.CharacterID = 10;


								Flags.isStartMission = 1;
								sResOutput(">>> ReInit Status is Okay "," >>>");

								break;
							}
						}
					}
				}
				else{
					sResOutput(">>>[Exc]: ","pJsonArray >>>");
				}
			}
		}
	}
	cJSON_Delete(root);
	root = NULL;
}
Exemple #22
0
static int create_conman_config(char **config)
{
  cJSON *root = NULL, *connections = NULL, *connection = NULL,
      *links = NULL, *link = NULL;

  root = cJSON_CreateObject();
  if (!root)
    {
      exapp_dbg("cJSON_CreateObject failed\n");
      return ERROR;
    }

  connections = cJSON_CreateArray();
  if (!connections)
    {
      exapp_dbg("cJSON_CreateArray failed\n");
      goto errout_free;
    }

  connection = cJSON_CreateObject();
  if (!connection)
    {
      exapp_dbg("cJSON_CreateObject failed\n");
      goto errout_free;
    }

  links = cJSON_CreateArray();
  if (!links)
    {
      exapp_dbg("cJSON_CreateArray failed\n");
      goto errout_free;
    }

  link = cJSON_CreateObject();
  if (!link)
    {
      exapp_dbg("cJSON_CreateObject failed\n");
      goto errout_free;
    }

#ifdef CONFIG_SDK_EXAMPLE_APP_CONNECTION_MODEM
  cJSON_AddNumberToObject(link, "connectionId", 0);
  cJSON_AddStringToObject(link, "pinCode", CONFIG_SDK_EXAMPLE_APP_CONNECTION_SIM_PIN);
  cJSON_AddStringToObject(link, "accessPointName", CONFIG_SDK_EXAMPLE_APP_CONNECTION_SIM_APN_NAME);
  cJSON_AddStringToObject(link, "userName", CONFIG_SDK_EXAMPLE_APP_CONNECTION_SIM_APN_USER);
  cJSON_AddStringToObject(link, "password", CONFIG_SDK_EXAMPLE_APP_CONNECTION_SIM_APN_PASSWD);

  cJSON_AddItemToArray(links, link);
  cJSON_AddItemToObject(connection, "cellularConnections", links);
#elif defined CONFIG_SDK_EXAMPLE_APP_CONNECTION_WIFI
  cJSON_AddNumberToObject(link, "connectionId", 0);
  cJSON_AddStringToObject(link, "ssid", CONFIG_SDK_EXAMPLE_APP_CONNECTION_WIFI_SSID);
  cJSON_AddStringToObject(link, "password", CONFIG_SDK_EXAMPLE_APP_CONNECTION_WIFI_PSK);
  cJSON_AddStringToObject(link, "encryption", "wpa2");

  cJSON_AddItemToArray(links, link);
  cJSON_AddItemToObject(connection, "wifiConnections", links);
#else
# error "Connectivity misconfigured"
#endif

  cJSON_AddItemToArray(connections, connection);
  cJSON_AddItemToObject(root, "connections", connections);

  *config = cJSON_PrintUnformatted(root);

  cJSON_Delete(root); /* Deletes the whole tree */

  return OK;

errout_free:

  cJSON_Delete(root);
  cJSON_Delete(connections);
  cJSON_Delete(connection);
  cJSON_Delete(links);
  cJSON_Delete(link);

  return ERROR;
}
Exemple #23
0
/* Send an alert via syslog
 * Returns 1 on success or 0 on error
 */
int OS_Alert_SendSyslog(alert_data *al_data, const SyslogConfig *syslog_config)
{
    char *tstamp;
    char *hostname;
    char syslog_msg[OS_SIZE_2048];

    /* Invalid socket */
    if (syslog_config->socket < 0) {
        return (0);
    }

    /* Clear the memory before insert */
    memset(syslog_msg, '\0', OS_SIZE_2048);

    /* Look if location is set */
    if (syslog_config->location) {
        if (!OSMatch_Execute(al_data->location,
                             strlen(al_data->location),
                             syslog_config->location)) {
            return (0);
        }
    }

    /* Look for the level */
    if (syslog_config->level) {
        if (al_data->level < syslog_config->level) {
            return (0);
        }
    }

    /* Look for rule id */
    if (syslog_config->rule_id) {
        int id_i = 0;
        while (syslog_config->rule_id[id_i] != 0) {
            if (syslog_config->rule_id[id_i] == al_data->rule) {
                break;
            }
            id_i++;
        }

        /* If we found, id is going to be a valid rule */
        if (!syslog_config->rule_id[id_i]) {
            return (0);
        }
    }

    /* Look for the group */
    if (syslog_config->group) {
        if (!OSMatch_Execute(al_data->group,
                             strlen(al_data->group),
                             syslog_config->group)) {
            return (0);
        }
    }

    /* Fix the timestamp to be syslog compatible
     * We have 2008 Jul 10 10:11:23
     * Should be: Jul 10 10:11:23
     */
    tstamp = al_data->date;
    if (strlen(al_data->date) > 14) {
        tstamp += 5;

        /* Fix first digit if the day is < 10 */
        if (tstamp[4] == '0') {
            tstamp[4] = ' ';
        }
    }

    if (syslog_config->use_fqdn) {
        hostname = __shost_long;
    } else {
        hostname = __shost;
    }

    /* Insert data */
    if (syslog_config->format == DEFAULT_CSYSLOG) {
        /* Build syslog message */
        snprintf(syslog_msg, OS_SIZE_2048,
                 "<%u>%s %s ossec: Alert Level: %u; Rule: %u - %s; Location: %s;",
                 syslog_config->priority, tstamp, hostname,
                 al_data->level,
                 al_data->rule, al_data->comment,
                 al_data->location
                );
        field_add_string(syslog_msg, OS_SIZE_2048, " classification: %s;", al_data->group );
        field_add_string(syslog_msg, OS_SIZE_2048, " srcip: %s;", al_data->srcip );
#ifdef LIBGEOIP_ENABLED
        field_add_string(syslog_msg, OS_SIZE_2048, " srccity: %s;", al_data->srcgeoip );
        field_add_string(syslog_msg, OS_SIZE_2048, " dstcity: %s;", al_data->dstgeoip );
#endif
        field_add_string(syslog_msg, OS_SIZE_2048, " dstip: %s;", al_data->dstip );
        field_add_string(syslog_msg, OS_SIZE_2048, " user: %s;", al_data->user );
        field_add_string(syslog_msg, OS_SIZE_2048, " Previous MD5: %s;", al_data->old_md5 );
        field_add_string(syslog_msg, OS_SIZE_2048, " Current MD5: %s;", al_data->new_md5 );
        field_add_string(syslog_msg, OS_SIZE_2048, " Previous SHA1: %s;", al_data->old_sha1 );
        field_add_string(syslog_msg, OS_SIZE_2048, " Current SHA1: %s;", al_data->new_sha1 );
     /* "9/19/2016 - Sivakumar Nellurandi - parsing additions" */
        field_add_string(syslog_msg, OS_SIZE_2048, " Size changed: from %s;", al_data->file_size );
        field_add_string(syslog_msg, OS_SIZE_2048, " User ownership: was %s;", al_data->owner_chg );
        field_add_string(syslog_msg, OS_SIZE_2048, " Group ownership: was %s;", al_data->group_chg );
        field_add_string(syslog_msg, OS_SIZE_2048, " Permissions changed: from %s;", al_data->perm_chg );
     /* "9/19/2016 - Sivakumar Nellurandi - parsing additions" */
        field_add_truncated(syslog_msg, OS_SIZE_2048, " %s", al_data->log[0], 2 );
    } else if (syslog_config->format == CEF_CSYSLOG) {
        snprintf(syslog_msg, OS_SIZE_2048,
                 "<%u>%s CEF:0|%s|%s|%s|%u|%s|%u|dvc=%s cs1=%s cs1Label=Location",
                 syslog_config->priority,
                 tstamp,
                 __author,
                 __ossec_name,
                 __version,
                 al_data->rule,
                 al_data->comment,
                 (al_data->level > 10) ? 10 : al_data->level,
                 hostname, al_data->location);
        field_add_string(syslog_msg, OS_SIZE_2048, " classification=%s", al_data->group );
        field_add_string(syslog_msg, OS_SIZE_2048, " src=%s", al_data->srcip );
        field_add_int(syslog_msg, OS_SIZE_2048, " dpt=%d", al_data->dstport );
        field_add_int(syslog_msg, OS_SIZE_2048, " spt=%d", al_data->srcport );
        field_add_string(syslog_msg, OS_SIZE_2048, " fname=%s", al_data->filename );
        field_add_string(syslog_msg, OS_SIZE_2048, " dhost=%s", al_data->dstip );
        field_add_string(syslog_msg, OS_SIZE_2048, " shost=%s", al_data->srcip );
        field_add_string(syslog_msg, OS_SIZE_2048, " suser=%s", al_data->user );
        field_add_string(syslog_msg, OS_SIZE_2048, " dst=%s", al_data->dstip );
#ifdef LIBGEOIP_ENABLED
        field_add_string(syslog_msg, OS_SIZE_2048, " cs4Label=SrcCity cs4=%s", al_data->srcgeoip );
        field_add_string(syslog_msg, OS_SIZE_2048, " cs5Label=DstCity cs5=%s", al_data->dstgeoip );
#endif
        field_add_string(syslog_msg, OS_SIZE_2048, " suser=%s", al_data->user );
        field_add_string(syslog_msg, OS_SIZE_2048, " dst=%s", al_data->dstip );
        field_add_truncated(syslog_msg, OS_SIZE_2048, " msg=%s", al_data->log[0], 2 );
        if (al_data->new_md5 && al_data->new_sha1) {
            field_add_string(syslog_msg, OS_SIZE_2048, " cs2Label=OldMD5 cs2=%s", al_data->old_md5);
            field_add_string(syslog_msg, OS_SIZE_2048, " cs3Label=NewMD5 cs3=%s", al_data->new_md5);
            field_add_string(syslog_msg, OS_SIZE_2048, " oldFileHash=%s", al_data->old_sha1 );
            field_add_string(syslog_msg, OS_SIZE_2048, " fhash=%s", al_data->new_sha1 );
            field_add_string(syslog_msg, OS_SIZE_2048, " fileHash=%s", al_data->new_sha1 );
        }
    } else if (syslog_config->format == JSON_CSYSLOG) {
        /* Build a JSON Object for logging */
        cJSON *root;
        char *json_string;
        root = cJSON_CreateObject();

        /* Data guaranteed to be there */
        cJSON_AddNumberToObject(root, "crit",      al_data->level);
        cJSON_AddNumberToObject(root, "id",        al_data->rule);
        cJSON_AddStringToObject(root, "component", al_data->location);

        /* Rule Meta Data */
        if (al_data->group) {
            cJSON_AddStringToObject(root, "classification", al_data->group);
        }
        if (al_data->comment) {
            cJSON_AddStringToObject(root, "description",    al_data->comment);
        }

        /* Raw log message generating event */
        if (al_data->log && al_data->log[0]) {
            cJSON_AddStringToObject(root, "message",        al_data->log[0]);
        }

        /* Add data if it exists */
        if (al_data->user) {
            cJSON_AddStringToObject(root,   "acct",       al_data->user);
        }
        if (al_data->srcip) {
            cJSON_AddStringToObject(root,   "src_ip",     al_data->srcip);
        }
        if (al_data->srcport) {
            cJSON_AddNumberToObject(root,   "src_port",   al_data->srcport);
        }
        if (al_data->dstip) {
            cJSON_AddStringToObject(root,   "dst_ip",     al_data->dstip);
        }
        if (al_data->dstport) {
            cJSON_AddNumberToObject(root,   "dst_port",   al_data->dstport);
        }
        if (al_data->filename) {
            cJSON_AddStringToObject(root,   "file",       al_data->filename);
        }
        if (al_data->old_md5) {
            cJSON_AddStringToObject(root,   "md5_old",    al_data->old_md5);
        }
        if (al_data->new_md5) {
            cJSON_AddStringToObject(root,   "md5_new",    al_data->new_md5);
        }
        if (al_data->old_sha1) {
            cJSON_AddStringToObject(root,   "sha1_old",   al_data->old_sha1);
        }
        if (al_data->new_sha1) {
            cJSON_AddStringToObject(root,   "sha1_new",   al_data->new_sha1);
        }
#ifdef LIBGEOIP_ENABLED
        if (al_data->srcgeoip) {
            cJSON_AddStringToObject(root, "src_city", al_data->srcgeoip);
        }
        if (al_data->dstgeoip) {
            cJSON_AddStringToObject(root, "dst_city", al_data->dstgeoip);
        }
#endif

        /* Create the JSON string */
        json_string = cJSON_PrintUnformatted(root);

        /* Create the syslog message */
        snprintf(syslog_msg, OS_SIZE_2048,
                 "<%u>%s %s ossec: %s",

                 /* syslog header */
                 syslog_config->priority, tstamp, hostname,

                 /* JSON Encoded Data */
                 json_string
                );
        /* Clean up the memory for the JSON structure */
        free(json_string);
        cJSON_Delete(root);
    } else if (syslog_config->format == SPLUNK_CSYSLOG) {
        /* Build a Splunk Style Key/Value string for logging */
        snprintf(syslog_msg, OS_SIZE_2048,
                 "<%u>%s %s ossec: crit=%u id=%u description=\"%s\" component=\"%s\",",

                 /* syslog header */
                 syslog_config->priority, tstamp, hostname,

                 /* OSSEC metadata */
                 al_data->level, al_data->rule, al_data->comment,
                 al_data->location
                );
        /* Event specifics */
        field_add_string(syslog_msg, OS_SIZE_2048, " classification=\"%s\",", al_data->group );

        if ( field_add_string(syslog_msg, OS_SIZE_2048, " src_ip=\"%s\",", al_data->srcip ) > 0 ) {
            field_add_int(syslog_msg, OS_SIZE_2048, " src_port=%d,", al_data->srcport );
        }

#ifdef LIBGEOIP_ENABLED
        field_add_string(syslog_msg, OS_SIZE_2048, " src_city=\"%s\",", al_data->srcgeoip );
        field_add_string(syslog_msg, OS_SIZE_2048, " dst_city=\"%s\",", al_data->dstgeoip );
#endif

        if ( field_add_string(syslog_msg, OS_SIZE_2048, " dst_ip=\"%s\",", al_data->dstip ) > 0 ) {
            field_add_int(syslog_msg, OS_SIZE_2048, " dst_port=%d,", al_data->dstport );
        }

        field_add_string(syslog_msg, OS_SIZE_2048, " file=\"%s\",", al_data->filename );
        field_add_string(syslog_msg, OS_SIZE_2048, " acct=\"%s\",", al_data->user );
        field_add_string(syslog_msg, OS_SIZE_2048, " md5_old=\"%s\",", al_data->old_md5 );
        field_add_string(syslog_msg, OS_SIZE_2048, " md5_new=\"%s\",", al_data->new_md5 );
        field_add_string(syslog_msg, OS_SIZE_2048, " sha1_old=\"%s\",", al_data->old_sha1 );
        field_add_string(syslog_msg, OS_SIZE_2048, " sha1_new=\"%s\",", al_data->new_sha1 );
        /* Message */
        field_add_truncated(syslog_msg, OS_SIZE_2048, " message=\"%s\"", al_data->log[0], 2 );
    }

    OS_SendUDPbySize(syslog_config->socket, strlen(syslog_msg), syslog_msg);
    return (1);
}
	TrainingSchedule<BackPropagation>* TrainingSchedule<BackPropagation>::FromJSON(const std::string& json)
	{
		TrainingSchedule<BackPropagation>* result = nullptr;
		BackPropagation::ModelConfig model_config;
		uint32_t minibatch_size;
		int32_t seed = 1;

		std::vector<std::pair<BackPropagation::TrainingConfig, uint32_t>> schedule;

		cJSON* root = cJSON_Parse(json.c_str());
		if(root)
		{
			cJSON* cj_type = cJSON_GetObjectItem(root, "Type");
			if(!cj_type || (strcmp(cj_type->valuestring, "MLP") != 0 && strcmp(cj_type->valuestring, "MultilayerPerceptron") != 0))
			{
				goto Error;
			}

			cJSON* cj_layers = cJSON_GetObjectItem(root, "Layers");
			cJSON* cj_activation_functions = cJSON_GetObjectItem(root, "ActivationFunctions");
			cJSON* cj_minibatch_size = cJSON_GetObjectItem(root, "MinibatchSize");
			cJSON* cj_seed = cJSON_GetObjectItem(root, "Seed");
			cJSON* cj_schedule = cJSON_GetObjectItem(root, "Schedule");

			// make sure we have the mandatory bits
			if(cj_layers && cj_activation_functions &&
			   cj_minibatch_size && cj_schedule)
			{
				// verify we hae the right number of layer values and activation function values
				if(cJSON_GetArraySize(cj_layers) > 1 && cJSON_GetArraySize(cj_layers) == (cJSON_GetArraySize(cj_activation_functions) + 1))
				{
					// get our array iterators and populate the model config
					cJSON* cj_layer_val;
					cJSON* cj_func_val;

					cj_layer_val = cJSON_GetArrayItem(cj_layers, 0);
					model_config.InputCount = cj_layer_val->valueint;

					// parse network structure/functions
					for(int k = 0; k < cJSON_GetArraySize(cj_activation_functions); k++)
					{
						cj_layer_val = cJSON_GetArrayItem(cj_layers, k + 1);
						cj_func_val = cJSON_GetArrayItem(cj_activation_functions, k);

						if(cj_layer_val && cj_func_val)
						{
							BackPropagation::LayerConfig layer_config;
							layer_config.OutputUnits = cj_layer_val->valueint;
							layer_config.Function = ParseFunction(cj_func_val->valuestring);

							if(cj_layer_val->valueint < 1)
							{
								goto Error;
							}
							if(layer_config.Function == ActivationFunction::Invalid)
							{
								goto Error;
							}

							model_config.LayerConfigs.push_back(layer_config);
						}
						else
						{
							goto Error;
						}
					}

					if(cj_seed != nullptr)
					{
						seed = cj_seed->valueint;
					}

					// minibatch size
					if(cj_minibatch_size->valueint < 1)
					{
						goto Error;
					}
					minibatch_size = cj_minibatch_size->valueint;

					// parse our schedules
					if(cJSON_GetArraySize(cj_schedule) == 0)
					{
						goto Error;
					}

					BackPropagation::TrainingConfig train_config;
					uint32_t layer_count = model_config.LayerConfigs.size();
					for(uint32_t  k = 0; k < layer_count; k++)
					{
						BackPropagation::LayerParameters layer_params;;
						train_config.Parameters.push_back(layer_params);
					}

					// now read each traing config in the schedule
					for(int k = 0; k < cJSON_GetArraySize(cj_schedule); k++)
					{
						cJSON* cj_train_config = cJSON_GetArrayItem(cj_schedule, k);

						// this function will read an object and if it's an array, populate each member of the array to the appropriate layer config
						// if it is a single value, all the values in the array are given that value
						auto read_params = [&] (uint32_t index, const char* param, float min, float max) -> bool
						{
							cJSON* cj_param = cJSON_GetObjectItem(cj_train_config, param);
							if(cj_param)
							{
								if(cj_param->type == cJSON_Array)
								{
									// ensure we have the right number of params
									if(cJSON_GetArraySize(cj_param) != layer_count)
									{
										return false;
									}

									for(uint32_t j = 0; j < layer_count; j++)
									{
										cJSON* cj_val = cJSON_GetArrayItem(cj_param, j);
										if(cj_val->type != cJSON_Number)
										{
											return false;
										}

										float val = float(cj_val->valuedouble);

										if(val < min || val > max)
										{
											return false;
										}

										train_config.Parameters[j].Data[index] = val; 
										
									}
								}
								else if(cj_param->type == cJSON_Number)
								{
									for(uint32_t j = 0; j < layer_count; j++)
									{
										float val = float(cj_param->valuedouble);
										
										if(val < min || val > max)
										{
											return false;
										}

										train_config.Parameters[j].Data[index] = val;
									}
								}
							}
							return true;
						};
#						define GET_INDEX(NAME) (((uint32_t)( &( (BackPropagation::LayerParameters*)(void*)0)->NAME) )/sizeof(float))
#						define READ_PARAMS(NAME, MIN, MAX) if(read_params(GET_INDEX(NAME), #NAME, MIN, MAX) == false) goto Error;

						READ_PARAMS(LearningRate, 0.0f, FLT_MAX)
						READ_PARAMS(Momentum, 0.0f, 1.0f)
						READ_PARAMS(L1Regularization, 0.0f, FLT_MAX)
						READ_PARAMS(L2Regularization, 0.0f, FLT_MAX)
						READ_PARAMS(Dropout, 0.0f, 1.0f)
						READ_PARAMS(Noise, 0.0f, FLT_MAX)
						READ_PARAMS(AdadeltaDecay, 0.0f, 1.0f)

						//now get the number of epochs
						cJSON* cj_epochs = cJSON_GetObjectItem(cj_train_config, "Epochs");
						if(cj_epochs == nullptr || cj_epochs->type != cJSON_Number || cj_epochs->valueint < 1)
						{
							goto Error;
						}
						uint32_t epochs = cj_epochs->valueint;
						schedule.push_back(std::pair<BackPropagation::TrainingConfig, uint32_t>(train_config, epochs));
					}
				}
				else
				{
					goto Error;
				}
			}
			else
			{
				goto Error;
			}
		}
		else
		{
			goto Error;
		}

		// create result here
		result = new TrainingSchedule<BackPropagation>(model_config, minibatch_size, seed);
		for(uint32_t k = 0; k < schedule.size(); k++)
		{
			result->AddTrainingConfig(schedule[k].first, schedule[k].second);
		}
Error:
		cJSON_Delete(root);
		return result;
	}
Exemple #25
0
void parse_ret(char *ptr,nsp_ret_t *ret_t){
    cJSON *json;
    json=cJSON_Parse((char *)ptr);
    if(!json || !json->child){ret_t->nsp_upcmd=UNKNOWN;return ;}

    cJSON *obj=json->child;

    bool has_upcmd=false;
    while(obj!=NULL){
        if(strcmp(obj->string,"nsp_upcmd")==0){
            has_upcmd=true;
            if(strcmp(obj->valuestring,"REQTCON")==0)        {ret_t->nsp_upcmd = REQTCON;}
            else if(strcmp(obj->valuestring,"UPSTAT")==0)    {ret_t->nsp_upcmd = UPSTAT;}
            else if(strcmp(obj->valuestring,"REQTBLK")==0)    {ret_t->nsp_upcmd = REQTBLK;}
            else if(strcmp(obj->valuestring,"REQTSEG")==0)    {ret_t->nsp_upcmd = REQTSEG;}
            else                                            {ret_t->nsp_upcmd = UNKNOWN;cJSON_Delete(json);return;}
        }
        else if(strcmp(obj->string,"nsp_fid")==0){
            strncpy(ret_t->nsp_fid,obj->valuestring, 32);
            ret_t->nsp_fid[32] = 0;
        }
        else if(strcmp(obj->string,"nsp_range")==0){
            parse_range(obj->valuestring, &ret_t->nsp_range);
        }
        else if(strcmp(obj->string,"nsp_upstat")==0){
            if(strcmp("FIN",obj->valuestring) == 0)            {ret_t->nsp_upstat = FIN;}
            else if(strcmp("RECV",obj->valuestring) == 0)    {ret_t->nsp_upstat = RECV;}
            else if(strcmp("NONE",obj->valuestring) == 0)    {ret_t->nsp_upstat = NONE;}
            else                                            {ret_t->nsp_upstat = UNKNOWN_UPSTAT;cJSON_Delete(json);return;}
        }
        else if(strcmp(obj->string,"nsp_fstat")==0){
            cJSON *chi = obj->child;
            while(chi!=NULL){
                if(strcmp(chi->string,"RSIZE")==0){
                    ret_t->nsp_fstat_rsize = chi->valueint;
                }
                chi=chi->next;
            }
            ret_t->nsp_fstat_rsize = 0;
        }
        else if(strcmp(obj->string,"nsp_path")==0){
            strcpy(ret_t->nsp_path,obj->valuestring);
        }
        else if(strcmp(obj->string,"nsp_ts")==0){
            ret_t->nsp_ts=obj->valueint;
        }
        else if(strcmp(obj->string,"nsp_size")==0){
            strcpy(ret_t->nsp_size,obj->valuestring);
        }
        else if(strcmp(obj->string,"nsp_sig")==0){
            strcpy(ret_t->nsp_sig,obj->valuestring);
        }
        else if(strcmp(obj->string,"nsp_segsize")==0){
            ret_t->nsp_segsize=obj->valueint;
        }
        else{}
        obj=obj->next;
    }
    if(!has_upcmd){
        ret_t->nsp_upcmd = UNKNOWN;
    }
    cJSON_Delete(json);
}
	TrainingSchedule<ContrastiveDivergence>* TrainingSchedule<ContrastiveDivergence>::FromJSON(const std::string& json)
	{
		TrainingSchedule<ContrastiveDivergence>* result = nullptr;

		cJSON* root = cJSON_Parse(json.c_str());
		if(root)
		{
			cJSON* cj_type = cJSON_GetObjectItem(root, "Type");

			if(!cj_type || (strcmp(cj_type->valuestring, "RBM") != 0 && strcmp(cj_type->valuestring, "RestrictedBoltzmannMachine") != 0))
			{
				goto Error;
			}

			cJSON* cj_visible_type = cJSON_GetObjectItem(root, "VisibleType");
			cJSON* cj_visible_count = cJSON_GetObjectItem(root, "VisibleCount");
			cJSON* cj_hidden_type = cJSON_GetObjectItem(root, "HiddenType");
			cJSON* cj_hidden_count = cJSON_GetObjectItem(root, "HiddenCount");
			cJSON* cj_minibatch_size = cJSON_GetObjectItem(root, "MinibatchSize");
			cJSON* cj_seed = cJSON_GetObjectItem(root, "Seed");
			cJSON* cj_schedule = cJSON_GetObjectItem(root, "Schedule");

			if(cj_visible_type && cj_hidden_type &&
				cj_hidden_count && cj_minibatch_size &&
				cj_schedule)
			{
				ContrastiveDivergence::ModelConfig model_config;
				uint32_t minibatch_size = 0;
				int32_t seed = 1;

				for(int func = 0; func < ActivationFunction::Count; func++)
				{
					if(strcmp(cj_visible_type->valuestring, ActivationFunctionNames[func]) == 0)
					{
						model_config.VisibleType = (ActivationFunction_t)func;
					}

					if(strcmp(cj_hidden_type->valuestring, ActivationFunctionNames[func]) == 0)
					{
						model_config.HiddenType = (ActivationFunction_t)func;
					}
				}

				// make sure we found both activation functions
				if(model_config.VisibleType == -1 || model_config.HiddenType == -1)
				{
					goto Error;
				}

				if(cj_visible_count->valueint > 0)
				{
					model_config.VisibleUnits = cj_visible_count->valueint;
				}
				else
				{
					goto Error;
				}

				if(cj_hidden_count->valueint > 0)
				{
					model_config.HiddenUnits = cj_hidden_count->valueint;
				}
				else
				{
					goto Error;
				}

				if(cj_seed != nullptr)
				{
					seed = cj_seed->valueint;
				}

				if(cj_minibatch_size->valueint > 0)
				{
					minibatch_size = cj_minibatch_size->valueint;
				}
				else
				{
					goto Error;
				}


				// now step through schedule array 
				std::vector<std::pair<ContrastiveDivergence::TrainingConfig, uint32_t>> schedule;
				CD::TrainingConfig train_config;
				uint32_t epochs;
				const int schedule_length = cJSON_GetArraySize(cj_schedule);
				if(schedule_length == 0)
				{
					goto Error;
				}
				for(int k = 0; k < schedule_length; k++)
				{
					cJSON* cj_train_config = cJSON_GetArrayItem(cj_schedule, k);

					cJSON* cj_epochs = cJSON_GetObjectItem(cj_train_config, "Epochs");
					cJSON* cj_learning_rate = cJSON_GetObjectItem(cj_train_config, "LearningRate");
					cJSON* cj_momentum = cJSON_GetObjectItem(cj_train_config, "Momentum");
					cJSON* cj_l1 = cJSON_GetObjectItem(cj_train_config, "L1Regularization");
					cJSON* cj_l2 = cJSON_GetObjectItem(cj_train_config, "L2Regularization");
					cJSON* cj_visible_dropout = cJSON_GetObjectItem(cj_train_config, "VisibleDropout");
					cJSON* cj_hidden_dropout = cJSON_GetObjectItem(cj_train_config, "HiddenDropout");
					cJSON* cj_adadelta_decay = cJSON_GetObjectItem(cj_train_config, "AdadeltaDecay");

					// epochs is the only thing required
					if(cj_epochs && cj_epochs->valueint > 0)
					{
						epochs = cj_epochs->valueint;
					}
					else
					{
						goto Error;
					}

					// the rest are optional

					if(cj_learning_rate)
					{
						if(cj_learning_rate->valuedouble >= 0.0)
						{
							train_config.LearningRate = (float)cj_learning_rate->valuedouble;
						}
						else
						{
							goto Error;
						}
					}
					if(cj_momentum)
					{
						if(cj_momentum->valuedouble >= 0.0 && cj_momentum->valuedouble < 1.0)
						{
							train_config.Momentum = (float)cj_momentum->valuedouble;
						}
						else
						{
							goto Error;
						}
						
					}
					if(cj_l1)
					{
						if(cj_l1->valuedouble >= 0.0)
						{
							train_config.L1Regularization = (float)cj_l1->valuedouble;
						}
						else
						{
							goto Error;
						}
					}
					if(cj_l2)
					{
						if(cj_l2->valuedouble >= 0.0)
						{
							train_config.L2Regularization = (float)cj_l2->valuedouble;
						}
						else
						{
							goto Error;
						}
					}
					if(cj_visible_dropout)
					{
						if(cj_visible_dropout->valuedouble >= 0.0 && cj_visible_dropout->valuedouble < 1.0)
						{
							train_config.VisibleDropout = (float)cj_visible_dropout->valuedouble;
						}
						else
						{
							goto Error;
						}
					}
					if(cj_hidden_dropout)
					{
						if(cj_hidden_dropout->valuedouble >= 0.0 && cj_hidden_dropout->valuedouble < 1.0)
						{
							train_config.HiddenDropout = (float)cj_hidden_dropout->valuedouble;
						}
						else
						{
							goto Error;
						}
					}
					if(cj_adadelta_decay)
					{
						if(cj_adadelta_decay->valuedouble >= 0.0 && cj_adadelta_decay->valuedouble < 1.0)
						{
							train_config.AdadeltaDecay = (float)cj_adadelta_decay->valuedouble;
						}
					}


					// save off this schedule and epoch count
					schedule.push_back(std::pair<CD::TrainingConfig, uint32_t>(train_config, epochs));
				}

				// finally construct our training schedule
				result = new TrainingSchedule<ContrastiveDivergence>(model_config, minibatch_size, seed);
				for(uint32_t k = 0; k < schedule.size(); k++)
				{
					result->AddTrainingConfig(schedule[k].first, schedule[k].second);
				}
			}
		}
Error:
		cJSON_Delete(root);
		return result;
	}
/* Private: Serialize the root JSON object to a string (ending with a newline)
 * and send it to the listener.
 *
 * root - The JSON object to send.
 * listener - The listener device to send on.
 */
void sendJSON(cJSON* root, Listener* listener) {
    char* message = cJSON_PrintUnformatted(root);
    sendMessage(listener, (uint8_t*) message, strlen(message));
    cJSON_Delete(root);
    free(message);
}
Exemple #28
0
/* Replace array/object items with new ones. */
void   cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem)		{cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return;
	newitem->next=c->next;newitem->prev=c->prev;if (newitem->next) newitem->next->prev=newitem;
	if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;c->next=c->prev=0;cJSON_Delete(c);}
void   cJSON_DeleteItemFromObject(cJSON *object,const char *string) {cJSON_Delete(cJSON_DetachItemFromObject(object,string));}
Exemple #30
0
/**
 * The entity handler determines how to process a POST request.
 * Per the REST paradigm, POST can also be used to update representation of existing
 * resource or create a new resource.
 * For pstat, it updates only tm and om.
 */
static OCEntityHandlerResult HandlePstatPutRequest(const OCEntityHandlerRequest *ehRequest)
{
    OCEntityHandlerResult ehRet = OC_EH_ERROR;
    cJSON *postJson = NULL;

    if (ehRequest->resource)
    {
        postJson = cJSON_Parse(((OCSecurityPayload*)ehRequest->payload)->securityData);
        VERIFY_NON_NULL(TAG, postJson, INFO);
        cJSON *jsonPstat = cJSON_GetObjectItem(postJson, OIC_JSON_PSTAT_NAME);
        VERIFY_NON_NULL(TAG, jsonPstat, INFO);
        cJSON *commitHashJson = cJSON_GetObjectItem(jsonPstat, OIC_JSON_COMMIT_HASH_NAME);
        uint16_t commitHash = 0;
        if (commitHashJson)
        {
            commitHash = commitHashJson->valueint;
        }
        cJSON *tmJson = cJSON_GetObjectItem(jsonPstat, OIC_JSON_TM_NAME);
        if (tmJson && gPstat)
        {
            gPstat->tm = (OicSecDpm_t)tmJson->valueint;
            if(0 == tmJson->valueint && gPstat->commitHash == commitHash)
            {
                gPstat->isOp = true;
                gPstat->cm = NORMAL;
                OC_LOG (INFO, TAG, PCF("CommitHash is valid and isOp is TRUE"));
            }
            else
            {
                OC_LOG (INFO, TAG, PCF("CommitHash is not valid"));
            }
        }
        cJSON *omJson = cJSON_GetObjectItem(jsonPstat, OIC_JSON_OM_NAME);
        if (omJson && gPstat)
        {
            /*
             * Check if the operation mode is in the supported provisioning services
             * operation mode list.
             */
            for(size_t i=0; i< gPstat->smLen; i++)
            {
                if(gPstat->sm[i] == omJson->valueint)
                {
                    gPstat->om = (OicSecDpom_t)omJson->valueint;
                    break;
                }
            }
        }
        // Convert pstat data into JSON for update to persistent storage
        char *jsonStr = BinToPstatJSON(gPstat);
        if (jsonStr)
        {
            cJSON *jsonPstat = cJSON_Parse(jsonStr);
            OICFree(jsonStr);
            if (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_PSTAT_NAME, jsonPstat))
            {
                ehRet = OC_EH_OK;
            }
        }
    }
 exit:
    //Send payload to request originator
    if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL))
    {
        OC_LOG (ERROR, TAG, PCF("SendSRMResponse failed in HandlePstatPostRequest"));
    }
    cJSON_Delete(postJson);
    return ehRet;
}