END_TEST

START_TEST (test_valid_3)
{
	char *s = "[{\"key1\":2  ,  \"key2\":\"val\"}, 45, null]";
    struct json_object *j_ar = json_parser_parse(s);

    fail_unless(json_type(j_ar) == json_type_array, "bad type");
    fail_unless(json_array_length(j_ar) == 3, "bad length");

    struct json_object *j_obj = json_array_get(j_ar, 0);
    struct json_object *j_int1 = json_array_get(j_ar, 1);
    struct json_object *j_null = json_array_get(j_ar, 2);

    fail_unless(json_type(j_obj) == json_type_object, "bad type");
    fail_unless(json_type(j_int1) == json_type_int, "bad type");
    fail_unless(json_type(j_null) == json_type_null, "bad type");

    struct json_object *j_int2 = json_object_get(j_obj, "key1");
    struct json_object *j_str = json_object_get(j_obj, "key2");

    fail_unless(json_int_get(j_int1) == 45, "bad value");
    fail_unless(json_int_get(j_int2) == 2, "bad value");
    fail_unless(strcmp(json_string_get(j_str), "val") == 0, "bad value");

    json_ref_put(j_ar);
}
Пример #2
0
void jsonNodeComplete(JSONNODE *root, void *identifier)
{
	Config *cfg = (Config *)identifier;
	wchar_t logstr[1024];
	
	if (root == NULL)
		return;
	KickLog(L"config JSON Knoten korrekt");

	// ------------ URL ------------
	JSONNODE *n_url = json_get_nocase(root, "project_url");

	if (n_url == NULL && json_type(n_url) != JSON_STRING)
		return;

	const char *url = json_as_string(n_url);
	const size_t cSize = strlen(url) + 1;
	wchar_t* wc = new wchar_t[cSize];
	mbstowcs(wc, url, cSize);
	cfg->SetUrl(wc);
	swprintf(logstr, L"url: %s", wc);
	KickLog(logstr);

	// ------------ request interval ------------
	JSONNODE *n_req = json_get_nocase(root, "requesttime");

	if (n_req == NULL && json_type(n_req) != JSON_NUMBER)
		return;

	unsigned long nReq = json_as_int(n_req);
	cfg->SetRequestInterval(nReq);
	swprintf(logstr, L"request interval: %d", nReq);
	KickLog(logstr);
}
Пример #3
0
void SdkHandler::passwordFinished(char *bufferchar)
{
	CCLOG("in function:[%s], buff:[%s]", __FUNCTION__, bufferchar);
	
    int state = 0;
    int userId = 0;
    int flag = 0;
    JSONNODE *n = json_parse(bufferchar);
    if (n == NULL){
        return;
    }
    JSONNODE_ITERATOR i = json_begin(n);
    while (i != json_end(n)){
		CCLOG("Start Parse Json in [%s]", __FUNCTION__);
		
        if (*i == NULL){
            break;
        }
        
        // recursively call ourselves to dig deeper into the tree
        if (json_type(*i) == JSON_ARRAY || json_type(*i) == JSON_NODE){
            break;
        }
        
        // get the node name and value as a string
        json_char *node_name = json_name(*i);
        
        // find out where to store the values
        if (strcmp(node_name, "STATE") == 0){
            json_int_t node_value = json_as_int(*i);
            state = node_value;
        }
        else if (strcmp(node_name, "USER_ID") == 0){
            json_int_t node_value = json_as_int(*i);
            userId = node_value;
            
        }
        else if (strcmp(node_name, "LOGIN_KEY") == 0){
            json_char *node_value = json_as_string(*i);
            json_free(node_value);
            
        }
        else if (strcmp(node_name, "ERROR_TYPE") == 0){
            json_int_t node_value = json_as_int(*i);
            flag = node_value;
            
        }
        // cleanup and increment the iterator
        json_free(node_name);
        ++i;
    }
	CCLOG("state:[%d], flag:[%d]", state, flag);
    SdkInfoData *sdkLoginData = new SdkInfoData();
    sdkLoginData->state = state;
    sdkLoginData->errorFlag = flag;
    SGNotificationCenter::sharedNotificationCenter()->postNotification(PASSWORDLAG,sdkLoginData,false);
	
}
Пример #4
0
void SdkHandler::destroyGuestFinished(char *bufferchar)
{
	CCLOG("in function:[%s], buff:[%s]", __FUNCTION__, bufferchar);
	
    int state = 0;
    int userId = 0;
    int flag = 0;
    JSONNODE *n = json_parse(bufferchar);
    if (n == NULL){
        return;
    }
    JSONNODE_ITERATOR i = json_begin(n);
    while (i != json_end(n)){
		CCLOG("Start Parse Json in [%s]", __FUNCTION__);
		
        if (*i == NULL){
            break;
        }
        
        // recursively call ourselves to dig deeper into the tree
        if (json_type(*i) == JSON_ARRAY || json_type(*i) == JSON_NODE){
            break;
        }
        
        // get the node name and value as a string
        json_char *node_name = json_name(*i);
        
        // find out where to store the values
        if (strcmp(node_name, "STATE") == 0){
            json_int_t node_value = json_as_int(*i);
            state = node_value;
        }
        else if (strcmp(node_name, "USER_ID") == 0){
            json_int_t node_value = json_as_int(*i);
            userId = node_value;
            
        }
        else if (strcmp(node_name, "LOGIN_KEY") == 0){
            json_char *node_value = json_as_string(*i);
            json_free(node_value);
            
        }
        else if (strcmp(node_name, "ERROR_TYPE") == 0){
            json_int_t node_value = json_as_int(*i);
            flag = node_value;
            
        }
        // cleanup and increment the iterator
        json_free(node_name);
        ++i;
    }
	
}
Пример #5
0
SEXP
R_fromJSON(SEXP r_str, SEXP simplify, SEXP nullValue, SEXP simplifyWithNames, SEXP encoding,
            SEXP r_stringFun, SEXP r_str_type)
{
    const char * str = CHAR(STRING_ELT(r_str, 0));
    JSONNODE *node;
    SEXP ans;
    int nprotect = 0;
    StringFunctionType str_fun_type = GARBAGE;

    if(r_stringFun != R_NilValue) {
	if(TYPEOF(r_stringFun) == CLOSXP) {
	    SEXP e;
	    PROTECT(e = allocVector(LANGSXP, 2));
	    nprotect++;
	    SETCAR(e, r_stringFun);
	    r_stringFun = e;
	}
	str_fun_type = INTEGER(r_str_type)[0];
    } else 
	r_stringFun = NULL;

    node = json_parse(str);
    ans = processJSONNode(node, json_type(node), INTEGER(simplify)[0], nullValue, LOGICAL(simplifyWithNames)[0],
 			  INTEGER(encoding)[0], r_stringFun, str_fun_type);
    json_delete(node);
    if(nprotect)
	UNPROTECT(nprotect);

    return(ans);
}
void JSON_Append_array_element(sLONG_PTR *pResult, PackagePtr pParams)
{
	C_TEXT json;
	C_TEXT source;
	C_TEXT returnValue;
	
	json.fromParamAtIndex(pParams, 1);
	source.fromParamAtIndex(pParams, 2);
	
	JSONNODE *n = _fromHex(json);
	
	if(n){
	
		if(json_type(n) == JSON_ARRAY)
		{
			JSONNODE *_node = _fromHex(source);
			
			if(_node){
				JSONNODE *nodeCopy = json_duplicate(_node);
				json_push_back(n, nodeCopy);
				_toHex(nodeCopy, returnValue);
			}
			
		}

	}
	
	returnValue.setReturn(pResult);
}
void JSON_Get_type(sLONG_PTR *pResult, PackagePtr pParams)
{
	C_TEXT json;
	C_LONGINT returnValue;
	
	json.fromParamAtIndex(pParams, 1);
	
	JSONNODE *n = _fromHex(json);
	
	if(n){
		switch (json_type(n)) {
			case JSON_NULL:
				returnValue.setIntValue(0);
				break;
			case JSON_STRING:
				returnValue.setIntValue(1);
				break;
			case JSON_NUMBER:
				returnValue.setIntValue(2);
				break;
			case JSON_BOOL:
				returnValue.setIntValue(3);
				break;
			case JSON_ARRAY:
				returnValue.setIntValue(4);
				break;	
			case JSON_NODE:
				returnValue.setIntValue(5);
				break;					
		}
	} 
	
	returnValue.setReturn(pResult);
}
void JSON_GET_TEXT_ARRAY(sLONG_PTR *pResult, PackagePtr pParams)
{
	C_TEXT json;
	ARRAY_TEXT values;
	
	json.fromParamAtIndex(pParams, 1);
	values.setSize(1);
	
	JSONNODE *n = _fromHex(json);
	
	if(n){
		if(json_type(n) == JSON_ARRAY){
			JSONNODE_ITERATOR i = json_begin(n);
			while (i != json_end(n)){
				if (*i){
					json_char *s = json_as_string(*i);
					std::wstring w = std::wstring(s);
					C_TEXT t;
					_copyString(w, t);
					CUTF16String u;
					t.copyUTF16String(&u);
					values.appendUTF16String(&u);
					json_free(s);
				}
				++i;
			}
		}	
	}
	
	values.toParamAtIndex(pParams, 2);
}
Пример #9
0
int json_wlparam_strset_proc(JSONNODE* node, wlp_descr_t* wlp, void* param) {
	int i;
	wlp_strset_t* ss = (wlp_strset_t*) param;
	char* js = NULL;

	if(json_type(node) != JSON_STRING)
		return WLPARAM_JSON_WRONG_TYPE;

	js = json_as_string(node);

	for(i = 0; i < wlp->range.ss_num; ++i) {
		if(strcmp(wlp->range.ss_strings[i], js) == 0) {
			*ss = i;

			json_free(js);

			return WLPARAM_JSON_OK;
		}
	}

	/* No match found - wrong value provided*/
	json_free(js);

	*ss = -1;
	return WLPARAM_JSON_OUTSIDE_RANGE;
}
Пример #10
0
END_TEST

START_TEST (test_valid_2)
{
	char *s = "[2  ,  3]";
    struct json_object *obj = json_parser_parse(s);

    fail_unless(json_type(obj) == json_type_array, "bad type");
    fail_unless(json_array_length(obj) == 2, "bad length");

    struct json_object *j_int0 = json_array_get(obj, 0);
    struct json_object *j_int1 = json_array_get(obj, 1);
    fail_unless(json_type(j_int0) == json_type_int, "bad type");
    fail_unless(json_type(j_int1) == json_type_int, "bad type");

    fail_unless(json_int_get(j_int0) == 2, "bad value");
    fail_unless(json_int_get(j_int1) == 3, "bad value");

    json_ref_put(obj);
}
Пример #11
0
bool admJsonToCouple::scan( void *xnode,string name)
{
    JSONNODE *node=(JSONNODE *)xnode;
   if (!node){
        ADM_error("Invalid JSON Node\n");
        return false;
    }
 
    JSONNODE_ITERATOR i = json_begin(node);
    while (i != json_end(node)){
        if (*i == NULL){
            ADM_error("Invalid JSON Node\n");
            return false;
        }
        json_char *node_name = json_name(*i);
        //printf("Node :%s\n",node_name);
        // recursively call ourselves to dig deeper into the tree
        if (json_type(*i) == JSON_ARRAY || json_type(*i) == JSON_NODE)
        {
            if(name=="") 
                scan(*i,string(node_name));
            else
                scan(*i,name+string(".")+string(node_name));
        }
        else
        {
            keyVal k;
            json_char *node_value = json_as_string(*i);
            if(name=="") 
                k.key=string(node_name);
            else 
                k.key=string(name)+string(".")+string(node_name);
            k.value=string(node_value);
            readItems.push_back(k);
            json_free(node_value);
        }
        json_free(node_name);
        ++i;
    }
    return true;
}
Пример #12
0
bool Json::Parse(const string& str)
{
	JSONNODE* node = json_parse(str.c_str());

	if (node == NULL)
		return false;

	JSONNODE_ITERATOR iter = json_begin(node);
	while (iter != json_end(node))
	{
		json_char* nodeName = json_name(*iter);
		if(string(nodeName) == "" || json_type(*iter) == JSON_NULL)
		{
			json_free(nodeName);
			break;
		}

		if (json_type(*iter) == JSON_NODE)
		{
			if(!Parse(nodeName, *iter))
				return false;
		}
		else if(json_type(*iter) == JSON_ARRAY)
		{
			JSONNODE_ITERATOR i = json_begin(*iter);
			while (i != json_end(*iter))
			{
				if(json_type(*iter) == JSON_NUMBER)
				{
					mDataFloatArray[nodeName].push_back(json_as_float(*i));
				}
				else
				{
					mDataStrArray[nodeName].push_back(json_as_string(*i));
				}
				i++;
			}
		}
		else if(json_type(*iter) == JSON_NUMBER)
		{
			mDataFloat[nodeName] = json_as_float(*iter);
		}
		else if(json_type(*iter) == JSON_BOOL)
		{
			mDataBool[nodeName] = json_as_bool(*iter);
		}
		else if(json_type(*iter) == JSON_STRING)
		{
			mDataStr[nodeName] = json_as_string(*iter);
		}
		json_free(nodeName);
		iter++;
	}
	json_delete(node);
	return true;
}
Пример #13
0
static void _json_write(FILE * file, json_t json, unsigned int depth)
{
    switch (json_type(json)) {
    case ARRAY:
        _json_write_array(file, json_array(json), depth);
        break;
    case OBJECT:
        _json_write_object(file, json_object(json), depth);
        break;
    case STRING:
        _json_write_string(file, json_string(json));
        break;
    };
}
Пример #14
0
END_TEST

START_TEST (test_valid_4_utf)
{
	char *s = "[\"Элементы\", 5, \"массива\"]";
    struct json_object *j_ar = json_parser_parse(s);

    fail_unless(json_type(j_ar) == json_type_array, "bad type");
    fail_unless(json_array_length(j_ar) == 3, "bad length");

    struct json_object *j_str_1 = json_array_get(j_ar, 0);
    struct json_object *j_int = json_array_get(j_ar, 1);
    struct json_object *j_str_2 = json_array_get(j_ar, 2);

    fail_unless(json_type(j_str_1) == json_type_string, "bad type");
    fail_unless(json_type(j_str_2) == json_type_string, "bad type");
    fail_unless(json_type(j_int) == json_type_int, "bad type");

    fail_unless(json_int_get(j_int) == 5, "bad value_int");
    fail_unless(strcmp(json_string_get(j_str_1), "Элементы") == 0, "bad value_str_1");
    fail_unless(strcmp(json_string_get(j_str_2), "массива") == 0, "bad value_str_2");

    json_ref_put(j_ar);
}
Пример #15
0
int json_wlparam_string_proc(JSONNODE* node, wlp_descr_t* wlp, void* param) {
	wlp_string_t* str = (wlp_string_t*) param;
	char* js = NULL;

	if(json_type(node) != JSON_STRING)
		return WLPARAM_JSON_WRONG_TYPE;

	js = json_as_string(node);

	if(strlen(js) > wlp->range.str_length)
		return WLPARAM_JSON_OUTSIDE_RANGE;

	strcpy(param, js);

	json_free(js);

	return WLPARAM_JSON_OK;
}
Пример #16
0
static int get_status_and_reason(struct json_object *obj, int *status, char **reason)
{
	char *result_reason;
	int result_status;
	if (json_type(obj) == json_type_array || json_object_get(obj, JSON_RPC_ERROR_MEMBER) == NULL) {
		result_status = HTTP_SUCCESS_STATUS;
		result_reason = strdup(HTTP_SUCCESS_REASON);
	} else {
		int result_code = json_int_get(json_object_get(json_object_get(obj, JSON_RPC_ERROR_MEMBER), JSON_RPC_ERROR_CODE_MEMBER));
		result_reason = strdup(json_string_get(json_object_get(json_object_get(obj, JSON_RPC_ERROR_MEMBER), JSON_RPC_ERROR_MESSAGE_MEMBER)));
		result_status = get_status_by_code(result_code);
	}

	if (result_reason == NULL || result_status == -1)
		return -1;

	*reason = result_reason;
	*status = result_status;

	return 0;
}
void JSON_GET_BOOL_ARRAY(sLONG_PTR *pResult, PackagePtr pParams)
{
	C_TEXT json;
	ARRAY_BOOLEAN values;
	
	json.fromParamAtIndex(pParams, 1);
	values.setSize(1);
	
	JSONNODE *n = _fromHex(json);
	
	if(n){
		if(json_type(n) == JSON_ARRAY){
			JSONNODE_ITERATOR i = json_begin(n);
			while (i != json_end(n)){
				if (*i){
					values.appendBooleanValue(json_as_bool(*i));					
				}
				++i;
			}
		}	
	}
	
	values.toParamAtIndex(pParams, 2);
}
void Callback(JSONNODE * test, void *){
    ++counter;
    switch(counter){
	   case 1:
		  assertEquals(json_type(test), JSON_NODE);
		  assertTrue(json_empty(test));
		  break;
	   case 2:
		  assertEquals(json_type(test), JSON_ARRAY);
		  assertTrue(json_empty(test));
		  break;
	   case 3:{
		  assertEquals(json_type(test), JSON_NODE);
		  assertEquals(json_size(test), 1);
		  json_char * temp = json_name(json_at(test, 0));
		  assertCStringSame(temp, JSON_TEXT("hello"));
		  json_free(temp);
		  assertEquals(json_as_int(json_at(test, 0)), 1);
		  break;}
	   case 4:
		  assertEquals(json_type(test), JSON_ARRAY);
		  assertEquals(json_size(test), 3);
		  break;
	   case 5:{
		  assertEquals(json_type(test), JSON_NODE);
		  assertEquals(json_size(test), 1);
		  json_char * temp = json_name(json_at(test, 0));
		  assertCStringSame(temp, JSON_TEXT("hi"));
		  json_free(temp);
		  assertEquals(json_size(json_at(test, 0)), 1);
		  assertEquals(json_type(json_at(json_at(test, 0),0)), JSON_NUMBER);
		  temp = json_name(json_at(json_at(test, 0),0));
		  assertCStringSame(temp, JSON_TEXT("one"));
		  json_free(temp);
		  assertEquals(json_as_int(json_at(json_at(test, 0),0)), 1);
		  break;}
    }
}
Пример #19
0
SEXP 
processJSONNode(JSONNODE *n, int parentType, int simplify, SEXP nullValue, int simplifyWithNames, cetype_t charEncoding,
                 SEXP r_stringCall, StringFunctionType str_fun_type)
{
    
    if (n == NULL){
        PROBLEM "invalid JSON input"
	    ERROR;
    }
 
    JSONNODE *i;
    int len = 0, ctr = 0;
    int nprotect = 0;
    int numNulls = 0;
    len = json_size(n);
    char startType = parentType; // was 127
    
    int isNullHomogeneous = (TYPEOF(nullValue) == LGLSXP || TYPEOF(nullValue) == REALSXP ||
                                TYPEOF(nullValue) == STRSXP || TYPEOF(nullValue) == INTSXP);
    int numStrings = 0;
    int numLogicals = 0;
    int numNumbers = 0;

    SEXP ans, names = NULL;
    PROTECT(ans = NEW_LIST(len)); nprotect++;

    int homogeneous = 0;
    int elType = NILSXP;
    while (ctr < len){  // i != json_end(n)

	i = json_at(n, ctr);

        if (i == NULL){
            PROBLEM "Invalid JSON Node"
		ERROR;
        }

	json_char *node_name = json_name(i);
	
	char type = json_type(i);
	if(startType == 127)
	    startType = type;

	SEXP el;
	switch(type) {
   	   case JSON_NULL:
	       el = nullValue; /* R_NilValue; */
	       numNulls++;
	       if(isNullHomogeneous) {
		   homogeneous++;
		   elType = setType(elType, TYPEOF(nullValue));
	       } else
		   elType = TYPEOF(nullValue);
	       break;
   	   case JSON_ARRAY:
  	   case JSON_NODE:
	       el = processJSONNode(i, type, simplify, nullValue, simplifyWithNames, charEncoding, r_stringCall, str_fun_type);
	       if(Rf_length(el) > 1)
		   elType = VECSXP;
	       else
		   elType = setType(elType, TYPEOF(el));
	       break;
 	   case JSON_NUMBER:
	       el = ScalarReal(json_as_float(i));
	       homogeneous++;
	       elType = setType(elType, REALSXP);
	       numNumbers++;
	       break;
 	   case JSON_BOOL:
	       el = ScalarLogical(json_as_bool(i));
	       elType = setType(elType, LGLSXP);
	       numLogicals++;
	       break;
 	   case JSON_STRING:
	   {
//XXX Garbage collection
#if 0 //def JSON_UNICODE
	       wchar_t *wtmp = json_as_string(i);
	       char *tmp;
	       int len = wcslen(wtmp);
	       int size = sizeof(char) * (len * MB_LEN_MAX + 1);
	       tmp = (char *)malloc(size);
	       if (tmp == NULL) {
                   PROBLEM "Cannot allocate memory"
                   ERROR;
               }
	       wcstombs(tmp, wtmp, size);
#else
    char *tmp = json_as_string(i);
//    tmp = reEnc(tmp, CE_BYTES, CE_UTF8, 1);
#endif


    if(r_stringCall != NULL && TYPEOF(r_stringCall) == EXTPTRSXP) {
        if(str_fun_type == SEXP_STR_ROUTINE) {
	    SEXPStringRoutine fun;
	    fun = (SEXPStringRoutine) R_ExternalPtrAddr(r_stringCall);	    
	    el = fun(tmp, charEncoding);
	} else {
	    char *tmp1;
	    StringRoutine fun;
	    fun = (StringRoutine) R_ExternalPtrAddr(r_stringCall);
	    tmp1 = fun(tmp);
	    if(tmp1 != tmp)
		json_free(tmp);
	    tmp = tmp1;
	    el = ScalarString(mkCharCE(tmp, charEncoding));
	}
    } else {
	el = ScalarString(mkCharCE(tmp, charEncoding));
    	     /* Call the R function if there is one. */
	if(r_stringCall != NULL) {
	    SETCAR(CDR(r_stringCall), el);
	    el = Rf_eval(r_stringCall, R_GlobalEnv);
	}
	/* XXX compute with elType. */
    }

	       json_free(tmp);
	       
	       elType = setType(elType, 
   				     /* If we have a class, not a primitive type */
                                  Rf_length(getAttrib(el, Rf_install("class"))) ? LISTSXP : TYPEOF(el));
               if(r_stringCall != NULL && str_fun_type != NATIVE_STR_ROUTINE) {
		   switch(TYPEOF(el)) {
			  case REALSXP:
   			     numNumbers++;
			  break;
			  case LGLSXP:
   			     numLogicals++;
			  break;
			  case STRSXP:
   			     numStrings++;
			  break;
		   }
	       } else if(TYPEOF(el) == STRSXP) 
		   numStrings++;
      }
	       break;
	default:
	    PROBLEM "shouldn't be here"
		WARN;
	    el = R_NilValue;
	    break;
	}
	SET_VECTOR_ELT(ans, ctr, el);

	if(parentType == JSON_NODE || (node_name && node_name[0])) {
	    if(names == NULL) {
	        PROTECT(names = NEW_CHARACTER(len)); nprotect++;
	    }
	    if(node_name && node_name[0])
		SET_STRING_ELT(names, ctr, mkChar(node_name));
	}
	json_free(node_name);
	ctr++;
    }

    /* If we have an empty object, we try to make it into a form equivalent to emptyNamedList
       if it is a {},  or as an AsIs object in R if an empty array. */
    if(len == 0 && (parentType == -1 || parentType == JSON_ARRAY || parentType == JSON_NODE)) {
        if(parentType == -1) 
            parentType = startType;

        if(parentType == JSON_NODE)
	   SET_NAMES(ans, NEW_CHARACTER(0));
        else  {
	   SET_CLASS(ans, ScalarString(mkChar("AsIs")));
	}

    } else if(simplifyWithNames || names == NULL || Rf_length(names) == 0) {
	int allSame = (numNumbers == len || numStrings == len || numLogicals == len) || 
	    ((TYPEOF(nullValue) == LGLSXP && LOGICAL(nullValue)[0] == NA_INTEGER) && 
	     ((numNumbers + numNulls) == len || (numStrings + numNulls) == len || (numLogicals + numNulls) == len));
        homogeneous = allSame ||  ( (numNumbers + numStrings + numLogicals + numNulls) == len);
        if(simplify == NONE) {
	} else if(allSame && 
 		   (numNumbers == len && (simplify & STRICT_NUMERIC)) ||
  		      ((numLogicals == len) && (simplify & STRICT_LOGICAL)) ||
		      ( (numStrings == len) && (simplify & STRICT_CHARACTER))) {
   	       ans = makeVector(ans, len, elType, nullValue);
	} else if((simplify == ALL && homogeneous) || (simplify == STRICT && allSame)) {
   	       ans = makeVector(ans, len, elType, nullValue);
	}
    }
      

    if(names)
	SET_NAMES(ans, names);
	
    UNPROTECT(nprotect);
    return(ans);
}
Пример #20
0
void SdkHandler::thirdLoginFinished(char *bufferchar)
{
	CCLOG("in function:[%s], buff:[%s]", __FUNCTION__, bufferchar);
	
	CCLOG("userName:[%s], password:[%s]", userName.c_str(), password.c_str());
	
    int state = 0;
    int userId = 0;
    int flag = 0;
    const char* loginKey = NULL;
    JSONNODE *n = json_parse(bufferchar);
    if (n == NULL){
        return;
    }
    JSONNODE_ITERATOR i = json_begin(n);
    while (i != json_end(n)){
		
		CCLOG("Start Parse Json in [%s]", __FUNCTION__);
        if (*i == NULL){
            break;
        }
        
        // recursively call ourselves to dig deeper into the tree
        if (json_type(*i) == JSON_ARRAY || json_type(*i) == JSON_NODE){
            break;
        }
        
        // get the node name and value as a string
        json_char *node_name = json_name(*i);
        
        // find out where to store the values
        if (strcmp(node_name, "STATE") == 0){
            json_int_t node_value = json_as_int(*i);
            state = node_value;
        }
        else if (strcmp(node_name, "USER_ID") == 0){
            json_int_t node_value = json_as_int(*i);
            userId = node_value;
            
        }
        else if (strcmp(node_name, "LOGIN_KEY") == 0){
            json_char *node_value = json_as_string(*i);
            loginKey = node_value;
            
        }
        else if (strcmp(node_name, "ERROR_TYPE") == 0){
            json_int_t node_value = json_as_int(*i);
            flag = node_value;
            
        }
        // cleanup and increment the iterator
        json_free(node_name);
        ++i;
    }
	
	if (flag == 20)
	{
        SGNotificationCenter::sharedNotificationCenter()->postNotification(INVALID_INFO_TIP,new CCInteger(20),false);
		return ;
	}
	
	
	CCLOG("state:[%d], err_type:[%d]", state, flag);
    if (state == 1)
	{
        SdkInfoData *sdkLoginData = new SdkInfoData();
        sdkLoginData->accountId = userId;
        sdkLoginData->errorFlag = flag;
        sdkLoginData->loginKey = std::string(loginKey);
		sdkLoginData->userName = this->userName;
		sdkLoginData->password = this->password;
		sdkLoginData->isEx = this->isExist;
		
		CCLOG("loginKey:[%s]", loginKey);
		
		//需要将登陆数据写入本地,在此非主线程,需要将当前数据发至主线程写入本地文件
        SGNotificationCenter::sharedNotificationCenter()->postNotification(THIRDPARTYLOGIN,sdkLoginData,false);
		
    }
    else if (flag == 13)
    {
        SGNotificationCenter::sharedNotificationCenter()->postNotification(BIND_FAILED, false);
    }
    else
    {
		CCLOG("Login Failed!");
    }
}
Пример #21
0
void SdkHandler::registFinished(char *bufferchar)
{
	CCLOG("in function:[%s], buff:[%s]", __FUNCTION__, bufferchar);
	
	
    int state = 0;
    int userId = 0;
    int flag = 0;
    const char* loginKey = NULL;
    JSONNODE *n = json_parse(bufferchar);
    if (n == NULL){
        return;
    }
    JSONNODE_ITERATOR i = json_begin(n);
    while (i != json_end(n)){
		CCLOG("Start Parse Json in [%s]", __FUNCTION__);
        if (*i == NULL){
            break;
        }
        
        // recursively call ourselves to dig deeper into the tree
        if (json_type(*i) == JSON_ARRAY || json_type(*i) == JSON_NODE){
            break;
        }
        
        // get the node name and value as a string
        json_char *node_name = json_name(*i);
        
        // find out where to store the values
        if (strcmp(node_name, "STATE") == 0){
            json_int_t node_value = json_as_int(*i);
            state = node_value;
        }
        else if (strcmp(node_name, "USER_ID") == 0){
            json_int_t node_value = json_as_int(*i);
            userId = node_value;
            
        }
        else if (strcmp(node_name, "LOGIN_KEY") == 0){
            json_char *node_value = json_as_string(*i);
            loginKey = node_value;
            
        }
        else if (strcmp(node_name, "ERROR_TYPE") == 0){
            json_int_t node_value = json_as_int(*i);
            flag = node_value;
            
        }
        // cleanup and increment the iterator
        json_free(node_name);
        ++i;
    }
	
	//这里做状态判定
	if (flag == 10)
	{
        SGNotificationCenter::sharedNotificationCenter()->postNotification(INVALID_INFO_TIP,new CCInteger(10),false);
		return ;
	}
	else if (flag == 11)
	{
        SGNotificationCenter::sharedNotificationCenter()->postNotification(INVALID_INFO_TIP,new CCInteger(11),false);
		return ;
	}
	else if (flag == 12)
	{
        SGNotificationCenter::sharedNotificationCenter()->postNotification(INVALID_INFO_TIP,new CCInteger(12),false);
		return ;
	}
	
	
	CCLOG("Json parse completed! in fun : [%s]", __FUNCTION__);
	
    SdkInfoData *sdkLoginData = new SdkInfoData();
    sdkLoginData->state = state;
    sdkLoginData->accountId = userId;
    sdkLoginData->flag = flag;
    sdkLoginData->loginKey = std::string(loginKey);
	sdkLoginData->userName = userName;
	sdkLoginData->password = password;
	sdkLoginData->isEx = true;
	
	
	CCLOG("####state:[%d]m accountId : [%d], flag : [%d], loginKey:[%s]####", state, userId, flag, loginKey);
    SGNotificationCenter::sharedNotificationCenter()->postNotification(REREGISTFLAG,sdkLoginData,false);

}
void JSON_GET_CHILD_NODES(sLONG_PTR *pResult, PackagePtr pParams)
{
	C_TEXT json;
	ARRAY_TEXT nodes;
	ARRAY_LONGINT types;
	ARRAY_TEXT names;
	
	json.fromParamAtIndex(pParams, 1);
	nodes.setSize(1);
	types.setSize(1);
	names.setSize(1);	
	
	JSONNODE *n = _fromHex(json);
	
	if(n){
		JSONNODE_ITERATOR i = json_begin(n);
		while (i != json_end(n)){
			if (*i){
				json_char *s = json_name(*i);
				std::wstring w = std::wstring(s);
				C_TEXT t;
				_copyString(w, t);
				json_free(s);
				CUTF16String nodeName;
				t.copyUTF16String(&nodeName);
				names.appendUTF16String(&nodeName);
				
				C_TEXT h;
				_toHex(*i, h);
				CUTF16String nodeRef;
				h.copyUTF16String(&nodeRef);	
				nodes.appendUTF16String(&nodeRef);				
				
				switch (json_type(*i)) {
					case JSON_NULL:
						types.appendIntValue(0);
						break;
					case JSON_STRING:
						types.appendIntValue(1);					
						break;
					case JSON_NUMBER:
						types.appendIntValue(2);							
						break;
					case JSON_BOOL:
						types.appendIntValue(3);							
						break;	
					case JSON_ARRAY:
						types.appendIntValue(4);							
						break;
					case JSON_NODE:
						types.appendIntValue(5);							
						break;							
				}
			}
			++i;			
		}
	}
	
	nodes.toParamAtIndex(pParams, 2);
	types.toParamAtIndex(pParams, 3);
	names.toParamAtIndex(pParams, 4);
}
void TestSuite::TestInspectors(void){
    UnitTest::SetPrefix("TestInspectors.cpp - Inspectors");
    #ifdef JSON_LIBRARY
		  JSONNODE * test = json_new(JSON_NULL);
		  assertEquals(json_type(test), JSON_NULL);
		  json_char * res = json_as_string(test);
		  assertCStringSame(res, JSON_TEXT(""));
		  json_free(res);
		  assertEquals_Primitive(json_as_int(test), 0);
		  assertEquals_Primitive(json_as_float(test), 0.0f);
		  assertEquals(json_as_bool(test), false);

		  json_set_f(test, 15.5f);
		  assertEquals(json_type(test), JSON_NUMBER);
		#ifdef JSON_CASTABLE
		  res = json_as_string(test);
		  assertCStringSame(res, JSON_TEXT("15.5"));
		  json_free(res);
		#endif
		  assertEquals_Primitive(json_as_int(test), 15);
		  assertEquals_Primitive(json_as_float(test), 15.5f);
		  #ifdef JSON_CASTABLE
				assertEquals(json_as_bool(test), true);
		  #endif

		  json_set_f(test, 0.0f);
		  assertEquals(json_type(test), JSON_NUMBER);
		#ifdef JSON_CASTABLE
		  res = json_as_string(test);
		  assertCStringSame(res, JSON_TEXT("0"));
		  json_free(res);
		#endif
		  assertEquals_Primitive(json_as_int(test), 0);
		  assertEquals_Primitive(json_as_float(test), 0.0f);
		  #ifdef JSON_CASTABLE
			assertEquals(json_as_bool(test), false);
		  #endif
	
		  json_set_b(test, true);
		  assertEquals(json_type(test), JSON_BOOL);
		  #ifdef JSON_CASTABLE
			res = json_as_string(test);
			assertCStringSame(res, JSON_TEXT("true"));
			json_free(res);
			assertEquals_Primitive(json_as_int(test), 1);
			assertEquals_Primitive(json_as_float(test), 1.0f);
		  #endif
		  assertEquals(json_as_bool(test), true);

		  json_set_b(test, false);
		  assertEquals(json_type(test), JSON_BOOL);
		  #ifdef JSON_CASTABLE
			res = json_as_string(test);
			assertCStringSame(res, JSON_TEXT("false"));
			json_free(res);
			assertEquals_Primitive(json_as_int(test), 0);
			assertEquals_Primitive(json_as_float(test), 0.0f);
		  #endif
		  assertEquals(json_as_bool(test), false);
		  #ifdef JSON_CASTABLE
				  json_cast(test, JSON_NODE);
				  assertEquals(json_type(test), JSON_NODE);
				  assertEquals(json_size(test), 0);
				  json_push_back(test, json_new_a(JSON_TEXT("hi"), JSON_TEXT("world")));
				  json_push_back(test, json_new_a(JSON_TEXT("hello"), JSON_TEXT("mars")));
				  json_push_back(test, json_new_a(JSON_TEXT("salut"), JSON_TEXT("france")));
				  assertEquals(json_size(test), 3);
				  TestSuite::testParsingItself(test);

				  JSONNODE * casted = json_as_array(test);
				  #ifdef JSON_UNIT_TEST
					 assertNotEquals(((JSONNode*)casted) -> internal, ((JSONNode*)test) -> internal);
				  #endif
				  assertEquals(json_type(casted), JSON_ARRAY);
				  assertEquals(json_type(test), JSON_NODE);
				  assertEquals(json_size(test), 3);
				  assertEquals(json_size(casted), 3);
				  TestSuite::testParsingItself(casted);
		   #endif
				  UnitTest::SetPrefix("TestInspectors.cpp - Location");

		   #ifdef JSON_CASTABLE
				  #define CheckAt(parent, locale, text)\
					 if(JSONNODE * temp = json_at(parent, locale)){\
						json_char * _res = json_as_string(temp);\
						assertCStringSame(_res, text);\
						json_free(_res);\
					 } else {\
						FAIL(std::string("CheckAt: ") + #parent + "[" + #locale + "]");\
					 }

				  #define CheckNameAt(parent, locale, text)\
					 if(JSONNODE * temp = json_at(parent, locale)){\
						json_char * _res = json_name(temp);\
						assertCStringSame(_res, text);\
						json_free(_res);\
					 } else {\
						FAIL(std::string("CheckNameAt: ") + #parent + "[" + #locale + "]");\
					 }

		          CheckAt(casted, 0, JSON_TEXT("world"));
				  CheckAt(casted, 1, JSON_TEXT("mars"));
				  CheckAt(casted, 2, JSON_TEXT("france"));
				  CheckNameAt(casted, 0, JSON_TEXT(""));
				  CheckNameAt(casted, 1, JSON_TEXT(""));
				  CheckNameAt(casted, 2, JSON_TEXT(""));
	
				  CheckAt(test, 0, JSON_TEXT("world"));
				  CheckAt(test, 1, JSON_TEXT("mars"));
				  CheckAt(test, 2, JSON_TEXT("france"));
				  CheckNameAt(test, 0, JSON_TEXT("hi"));
				  CheckNameAt(test, 1, JSON_TEXT("hello"));
				  CheckNameAt(test, 2, JSON_TEXT("salut"));
		  

				  #define CheckGet(parent, locale, text)\
					 if(JSONNODE * temp = json_get(parent, locale)){\
						json_char * _res = json_as_string(temp);\
						assertCStringSame(_res, text);\
						json_free(_res);\
					 } else {\
						FAIL(std::string("CheckGet: ") + #parent + "[" + #locale + "]");\
					 }

				  #ifdef JSON_CASE_INSENSITIVE_FUNCTIONS
					 #define CheckGetNoCase(parent, locale, text)\
						if(JSONNODE * temp = json_get_nocase(parent, locale)){\
							json_char * _res = json_as_string(temp);\
							assertCStringSame(_res, text);\
							json_free(_res);\
						} else {\
							FAIL(std::string("CheckGetNoCase: ") + #parent + "[" + #locale + "]");\
						}
				  #else
					 #define CheckGetNoCase(parent, locale, text)
				  #endif

				  CheckGet(test, JSON_TEXT("hi"), JSON_TEXT("world"));
				  CheckGetNoCase(test, JSON_TEXT("HI"), JSON_TEXT("world"));
				  CheckGet(test, JSON_TEXT("hello"), JSON_TEXT("mars"));
				  CheckGetNoCase(test, JSON_TEXT("HELLO"), JSON_TEXT("mars"));
				  CheckGet(test, JSON_TEXT("salut"), JSON_TEXT("france"));
				  CheckGetNoCase(test, JSON_TEXT("SALUT"), JSON_TEXT("france"));
	
				assertNull(json_get(test, JSON_TEXT("meh")));
				#ifdef JSON_CASE_INSENSITIVE_FUNCTIONS
					assertNull(json_get_nocase(test, JSON_TEXT("meh")));
				#endif
			#endif


		  #ifdef JSON_ITERATORS
			#ifdef JSON_CASTABLE
			 UnitTest::SetPrefix("TestInspectors.cpp - Iterators");
			 for(JSONNODE_ITERATOR it = json_begin(casted), end = json_end(casted); it != end; ++it){
				json_char * _res = json_name(*it);
				assertCStringSame(_res, JSON_TEXT(""));
				json_free(_res);
			 }
			#endif
		  #endif

		  #ifdef JSON_BINARY
			 UnitTest::SetPrefix("TestInspectors.cpp - Binary");
			 json_set_binary(test, (const unsigned char *)"Hello World", 11);
			 assertEquals(json_type(test), JSON_STRING);
			 json_char * _res = json_as_string(test);
			 assertCStringSame(_res, JSON_TEXT("SGVsbG8gV29ybGQ="));
			 json_free(_res);

			 unsigned long i;
			 if(char * bin = (char*)json_as_binary(test, &i)){
				assertEquals(i, 11);
				char * terminated = (char*)std::memcpy(std::malloc(i + 1), bin, i);
				terminated[i] = '\0';
				assertCStringEquals(terminated, "Hello World");
				json_free(bin);
				std::free(terminated);
			 } else {
				FAIL("as_binary failed");
			 }

			 json_set_a(test, JSON_TEXT("Hello World"));
			 assertEquals(json_type(test), JSON_STRING);
			 _res = json_as_string(test);
			 assertCStringSame(_res, JSON_TEXT("Hello World"));
			 json_free(_res);

			 #ifdef JSON_SAFE
				assertEquals(json_as_binary(test, &i), 0);
				assertEquals(i, 0);
			 #endif
		  #endif


		  json_delete(test);
		  #ifdef JSON_CASTABLE
			json_delete(casted);
		  #endif
    #else
		  JSONNode test = JSONNode(JSON_NULL);
		  #ifdef JSON_CASTABLE
			 assertEquals(test.as_string(), JSON_TEXT(""));
			 assertEquals(test.as_int(), 0);
			 assertEquals(test.as_float(), 0.0f);
			 assertEquals(test.as_bool(), false);
		  #endif

		  test = 15.5f;
		  assertEquals(test.type(), JSON_NUMBER);
		#ifdef JSON_CASTABLE
		  assertEquals(test.as_string(), JSON_TEXT("15.5"));
		#endif
		  assertEquals(test.as_int(), 15);
		  assertEquals(test.as_float(), 15.5f);
		  #ifdef JSON_CASTABLE
			 assertEquals(test.as_bool(), true);
		  #endif

		  test = 0.0f;
		  assertEquals(test.type(), JSON_NUMBER);
		#ifdef JSON_CASTABLE
		  assertEquals(test.as_string(), JSON_TEXT("0"));
		#endif
		  assertEquals(test.as_int(), 0);
		  assertEquals(test.as_float(), 0.0f);
		  #ifdef JSON_CASTABLE
			 assertEquals(test.as_bool(), false);
		  #endif

		  test = true;
		  assertEquals(test.type(), JSON_BOOL);
		  #ifdef JSON_CASTABLE
			 assertEquals(test.as_string(), JSON_TEXT("true"));
			 assertEquals(test.as_int(), 1);
			 assertEquals(test.as_float(), 1.0f);
		  #endif
		  assertEquals(test.as_bool(), true);

		  test = false;
		  assertEquals(test.type(), JSON_BOOL);
		  #ifdef JSON_CASTABLE
			 assertEquals(test.as_string(), JSON_TEXT("false"));
			 assertEquals(test.as_int(), 0);
			 assertEquals(test.as_float(), 0.0f);
		  #endif
		  assertEquals(test.as_bool(), false);

		  #ifdef JSON_CASTABLE
			 test.cast(JSON_NODE);
		  #else
			 test = JSONNode(JSON_NODE);
		  #endif
		  assertEquals(test.type(), JSON_NODE);
		  assertEquals(test.size(), 0);
		  test.push_back(JSONNode(JSON_TEXT("hi"), JSON_TEXT("world")));
		  test.push_back(JSONNode(JSON_TEXT("hello"), JSON_TEXT("mars")));
		  test.push_back(JSONNode(JSON_TEXT("salut"), JSON_TEXT("france")));
		  assertEquals(test.size(), 3);
		  TestSuite::testParsingItself(test);

		  #ifdef JSON_CASTABLE
			 JSONNode casted = test.as_array();
			 #ifdef JSON_UNIT_TEST
				assertNotEquals(casted.internal, test.internal);
			 #endif
			 assertEquals(casted.type(), JSON_ARRAY);
			 assertEquals(test.type(), JSON_NODE);
			 assertEquals(test.size(), 3);
			 assertEquals(casted.size(), 3);
			 TestSuite::testParsingItself(casted);
		  #endif

		  UnitTest::SetPrefix("TestInspectors.cpp - Location");

		  try {
			 #ifdef JSON_CASTABLE
				assertEquals(casted.at(0), JSON_TEXT("world"));
				assertEquals(casted.at(1), JSON_TEXT("mars"));
				assertEquals(casted.at(2), JSON_TEXT("france"));
				assertEquals(casted.at(0).name(), JSON_TEXT(""));
				assertEquals(casted.at(1).name(), JSON_TEXT(""));
				assertEquals(casted.at(2).name(), JSON_TEXT(""));
			 #endif
			 assertEquals(test.at(0), JSON_TEXT("world"));
			 assertEquals(test.at(1), JSON_TEXT("mars"));
			 assertEquals(test.at(2), JSON_TEXT("france"));
			 assertEquals(test.at(0).name(), JSON_TEXT("hi"));
			 assertEquals(test.at(1).name(), JSON_TEXT("hello"));
			 assertEquals(test.at(2).name(), JSON_TEXT("salut"));
		  } catch (std::out_of_range){
			 FAIL("exception caught");
		  }

		  try {
			 assertEquals(test.at(JSON_TEXT("hi")), JSON_TEXT("world"));
			 assertEquals(test.at(JSON_TEXT("hello")), JSON_TEXT("mars"));
			 assertEquals(test.at(JSON_TEXT("salut")), JSON_TEXT("france"));
			 #ifdef JSON_CASE_INSENSITIVE_FUNCTIONS
				assertEquals(test.at_nocase(JSON_TEXT("SALUT")), JSON_TEXT("france"));
				assertEquals(test.at_nocase(JSON_TEXT("HELLO")), JSON_TEXT("mars"));
				assertEquals(test.at_nocase(JSON_TEXT("HI")), JSON_TEXT("world"));
			 #endif
		  } catch (std::out_of_range){
			 FAIL("exception caught");
		  }

		  assertException(test.at(JSON_TEXT("meh")), std::out_of_range);
		  #ifdef JSON_CASE_INSENSITIVE_FUNCTIONS
			 assertException(test.at_nocase(JSON_TEXT("meh")), std::out_of_range);
		  #endif

		  assertEquals(test[JSON_TEXT("hi")], json_string(JSON_TEXT("world")));
		  assertEquals(test[JSON_TEXT("hello")], json_string(JSON_TEXT("mars")));
		  assertEquals(test[JSON_TEXT("salut")], json_string(JSON_TEXT("france")));
		  assertEquals(test[0], JSON_TEXT("world"));
		  assertEquals(test[1], JSON_TEXT("mars"));
		  assertEquals(test[2], JSON_TEXT("france"));

		  #ifdef JSON_ITERATORS
			#ifdef JSON_CASTABLE
			 UnitTest::SetPrefix("TestInspectors.cpp - Iterators");
			 for(JSONNode::iterator it = casted.begin(), end = casted.end(); it != end; ++it){
				assertEquals((*it).name(), JSON_TEXT(""));
			 }
			#endif
		  #endif

		  #ifdef JSON_BINARY
			 UnitTest::SetPrefix("TestInspectors.cpp - Binary");
			 test.set_binary((const unsigned char *)"Hello World", 11);
			 assertEquals(test.type(), JSON_STRING);
			 assertEquals(test.as_string(), JSON_TEXT("SGVsbG8gV29ybGQ="));
			 assertEquals(test.as_binary(), "Hello World");
			 assertEquals(test.as_binary().size(), 11);

			 test = JSON_TEXT("Hello World");
			 assertEquals(test.type(), JSON_STRING);
			 assertEquals(test.as_string(), JSON_TEXT("Hello World"));
			 #ifdef JSON_SAFE
				assertEquals(test.as_binary(), "");
			 #endif
		  #endif
		  
         #ifdef JSON_READ_PRIORITY
			//This is a regression test for a bug in at()
			json_string buffer(JSON_TEXT("{ \"myValue1\" : \"foo\", \"myValue2\" : \"bar\"}"));
			JSONNode current = libjson::parse(buffer);
			try {
				JSONNode & value1 = current[JSON_TEXT("myValue1")];
				assertEquals(value1.as_string(), JSON_TEXT("foo"));
				JSONNode & value2 = current[JSON_TEXT("myValue2")];
				assertEquals(value2.as_string(), JSON_TEXT("bar"));
			} catch (...){
				assertTrue(false);
			}
        #endif
    #endif
}
Пример #24
0
/**
 * Called by serial_eventloop, this calls the relevant commands.
 *
 * This calls the next command in the stack. By default, the command
 * is cmd_main_menu.
 *
 * New in 12.17 onwards: we accept json-formatted commands as well. Those
 * commands are parsed & dispatched below.
 *
 * Important remark: the CLI does not support multiple commands in one
 * line. For instance { "get": "guid", "get": "rtc" } will not work.
 *
 * JSON commands are as follow:
 *
 * Settings not linked to setting keys
 * "set" {
 *      "rtc": integer (Unix timestamp)
 *      "devicetag": string (device tag)
 *      }
 *
 *  Get/set settings keys (Work in progress not implemented yet):
 * "setkey" { "name": string, "value": value }
 * "getkey": "name"
 *
 *  Getting values not linked to setting keys
 * "get":
 *    - "guid"
 *    - "rtc"
 *    - "devicetag"
 *    - "settings"
 *    - "cpm"
 *
 */
void serial_process_command(char *line) {

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

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

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

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

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

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

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

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

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

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

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

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

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


	ProjectStats *stats = new ProjectStats;
	stats->nBackers = backers;
	stats->nComments = comments;
	stats->fPledged = pledged;
	return stats;
}
Пример #26
0
SEXP
R_json_node_type(SEXP r_ref)
{
    JSONNODE *node = (JSONNODE *) R_ExternalPtrAddr(r_ref);
    return(ScalarInteger( (int) json_type(node)));
}
Пример #27
0
static int _change_state(json_parser *parser, int next_state)
{
    json_parser_stack_item *top_stack_item = parser->stack + parser->top;
    int value_end = 0;
    json_value *v = NULL, *parent;

    if (next_state == OK) {
        if (parser->state == N3) {
            /* null */
            value_end = 1;
            v = json_null_alloc(parser->config.alloc_func);
        } else if (parser->state == T3) {
            /* true */
            value_end = 1;
            v = json_boolean_alloc(1, parser->config.alloc_func);
        } else if (parser->state == F4) {
            /* false */
            value_end = 1;
            v = json_boolean_alloc(0, parser->config.alloc_func);
        } else if (parser->state == ST) {
            /* end of string in object_value or array */
            assert(top_stack_item->value_begin > 0);
            value_end = 1;
            v = _create_string_value(
                    &parser->config, 
                    top_stack_item->value_begin, 
                    parser->char_index - top_stack_item->value_begin
                );
        }
    } else if (next_state == ST) {
        if (parser->state == OB || parser->state == KE) {
            /* begin of string in object_name */
            assert(top_stack_item->mode == MODE_OBJECT_KEY);
            top_stack_item->name_begin = parser->char_index + 1;
        } else if (parser->state == VA) {
            /* begin of string in object_value */
            assert(top_stack_item->mode == MODE_OBJECT_VALUE);
            top_stack_item->value_begin = parser->char_index + 1;
        } else if (parser->state == AR) {
            /* begin of string in array */
            assert(top_stack_item->mode == MODE_ARRAY);
            top_stack_item->value_begin = parser->char_index + 1;
        }
    } else if (next_state == CO) {
        if (parser->state == ST) {
            /* end of string in object_name */
            assert(top_stack_item->mode == MODE_OBJECT_KEY);
            top_stack_item->name_len = parser->char_index - top_stack_item->name_begin;
        }
    }

    if (parser->state == VA || parser->state == AR) {
        if (next_state == MI || next_state == ZE || next_state == IN) {
            /* begin of number */
            assert(top_stack_item->mode == MODE_OBJECT_VALUE || top_stack_item->mode == MODE_ARRAY);
            top_stack_item->value_begin = parser->char_index;
        }
    } else if (parser->state == FR || parser->state == IN || parser->state == ZE || parser->state == E3) {
        if (next_state == OK || next_state == KE || next_state == VA) {
            /* end of number */
            assert(top_stack_item->value_begin > 0);
            value_end = 1;
            v = _create_number_value(
                    &parser->config,
                    top_stack_item->value_begin,
                    parser->char_index - top_stack_item->value_begin
                );
        }
    }

    if (value_end) {
        if (!v)
            return false;
        
        if (top_stack_item->mode == MODE_ARRAY) {
            /* insert v into the array */
            parent = top_stack_item->value;
            assert(parent && json_type(parent) == json_type_array);
            if (!json_array_set(parent, json_array_size(parent), v))
                return false;
        
        } else if (top_stack_item->mode == MODE_OBJECT_VALUE) {
            /* record v into the stack */
            assert(top_stack_item->value == NULL);
            top_stack_item->value = v;
        
        } else {
            assert(0);
            json_free(v);
            return false;
        }
    }

    parser->state = next_state;
    return true;
}
void TestSuite::TestFunctions(void){
    UnitTest::SetPrefix("TestFunctions.cpp - Swap");
    #ifdef JSON_LIBRARY
		  JSONNODE * test1 = json_new(JSON_NODE);
		  JSONNODE * test2 = json_new(JSON_NODE);
		  json_set_i(test1, 14);
		  json_set_i(test2, 35);
		  json_swap(test1, test2);
		  assertEquals_Primitive(json_as_int(test1), 35);
		  assertEquals_Primitive(json_as_int(test2), 14);

		  UnitTest::SetPrefix("TestFunctions.cpp - Duplicate");
		  json_delete(test1);
		  test1 = json_duplicate(test2);
		  #ifdef JSON_UNIT_TEST
			 assertNotEquals(((JSONNode*)test1) -> internal, ((JSONNode*)test2) -> internal);
		  #endif
		  assertTrue(json_equal(test1, test2));


		  UnitTest::SetPrefix("TestFunctions.cpp - Duplicate with children");
		  JSONNODE * node = json_new(JSON_NODE);
		  json_push_back(node, json_new_i(JSON_TEXT(""), 15));
		  json_push_back(node, json_new_f(JSON_TEXT(""), 27.4f));
		  json_push_back(node, json_new_b(JSON_TEXT(""), true));

		  TestSuite::testParsingItself(node);

		  JSONNODE * dup = json_duplicate(node);
		  assertEquals(json_size(dup), 3);
		  #ifdef JSON_UNIT_TEST
			 assertNotEquals(((JSONNode*)node) -> internal, ((JSONNode*)dup) -> internal);
		  #endif
		  assertEquals(json_type(dup), JSON_NODE);

		  TestSuite::testParsingItself(node);
		  TestSuite::testParsingItself(dup);

		  assertEquals_Primitive(json_as_int(json_at(dup, 0)), 15);
		  assertEquals_Primitive(json_as_float(json_at(dup, 1)), 27.4f);
		  assertEquals(json_as_bool(json_at(dup, 2)), true);
		  assertTrue(json_equal(json_at(dup, 0), json_at(node, 0)));
		  assertTrue(json_equal(json_at(dup, 1), json_at(node, 1)));
		  assertTrue(json_equal(json_at(dup, 2), json_at(node, 2)));


		  TestSuite::testParsingItself(dup);

		  #ifdef JSON_ITERATORS
			 for(JSONNODE_ITERATOR it = json_begin(node), end = json_end(node), dup_it = json_begin(dup);
				it != end;
				++it, ++dup_it){
				assertTrue(json_equal(*it, *dup_it));
				#ifdef JSON_UNIT_TEST
				    assertNotEquals(((JSONNode*)(*it)) -> internal, ((JSONNode*)(*dup_it)) -> internal);
				#endif
			 }
		  #endif

		  UnitTest::SetPrefix("TestFunctions.cpp - Nullify");
		  json_nullify(test1);
		  assertEquals(json_type(test1), JSON_NULL);
		  json_char * res = json_name(test1);
		  assertCStringSame(res, JSON_TEXT(""));
		  json_free(res);

		  #ifdef JSON_CASTABLE
			  UnitTest::SetPrefix("TestFunctions.cpp - Cast");
			  json_cast(test1, JSON_NULL);
			  json_set_i(test2, 1);
			  json_cast(test2, JSON_BOOL);
			  assertEquals(json_type(test1), JSON_NULL);
			  assertEquals(json_type(test2), JSON_BOOL);
			  assertEquals(json_as_bool(test2), true);
			  json_set_b(test2, true);
			  assertEquals(json_as_bool(test2), true);

			  json_cast(test2, JSON_NUMBER);
			  assertEquals_Primitive(json_as_float(test2), 1.0f);
			  json_set_f(test2, 0.0f);
			  assertEquals_Primitive(json_as_float(test2), 0.0f);
			  json_cast(test2, JSON_BOOL);
			  assertEquals(json_as_bool(test2), false);
		  #endif

		  UnitTest::SetPrefix("TestFunctions.cpp - Merge");
		  json_set_a(test1, JSON_TEXT("hello"));
		  json_set_a(test2, JSON_TEXT("hello"));
		  #ifdef JSON_UNIT_TEST
			 assertNotEquals(((JSONNode*)test1) -> internal, ((JSONNode*)test2) -> internal);
		  #endif
		  assertTrue(json_equal(test1, test2));
		  json_merge(test1, test2);
		  #ifdef JSON_UNIT_TEST
			 #ifdef JSON_REF_COUNT
				  assertEquals(((JSONNode*)test1) -> internal, ((JSONNode*)test2) -> internal);
			 #else
				  assertNotEquals(((JSONNode*)test1) -> internal, ((JSONNode*)test2) -> internal);
			 #endif
		  #endif

		#ifdef JSON_CASTABLE
			  json_cast(test1, JSON_NODE);
			  json_cast(test2, JSON_NODE);
			  assertEquals(json_type(test1), JSON_NODE);
			  assertEquals(json_type(test2), JSON_NODE);
			  json_push_back(test1, json_new_a(JSON_TEXT("hi"), JSON_TEXT("world")));
			  json_push_back(test2, json_new_a(JSON_TEXT("hi"), JSON_TEXT("world")));

			  TestSuite::testParsingItself(test1);
			  TestSuite::testParsingItself(test2);

			  json_merge(test1, test2);
			  #ifdef JSON_UNIT_TEST
				 #ifdef JSON_REF_COUNT
					  assertEquals(((JSONNode*)test1) -> internal, ((JSONNode*)test2) -> internal);
				 #else
					  assertNotEquals(((JSONNode*)test1) -> internal, ((JSONNode*)test2) -> internal);
				 #endif
			  #endif

			  TestSuite::testParsingItself(test1);
			  TestSuite::testParsingItself(test2);
		#endif

		  json_delete(test1);
		  json_delete(test2);
		  json_delete(node);
		  json_delete(dup);
    #else
		  JSONNode test1;
		  JSONNode test2;
		  test1 = JSON_TEXT("hello");
		  test2 = JSON_TEXT("world");
		  test1.swap(test2);
		  assertEquals(test1, JSON_TEXT("world"));
		  assertEquals(test2, JSON_TEXT("hello"));

		  UnitTest::SetPrefix("TestFunctions.cpp - Duplicate");
		  test1 = test2.duplicate();
		  #ifdef JSON_UNIT_TEST
			 assertNotEquals(test1.internal, test2.internal);
		  #endif
		  assertEquals(test1, test2);

		  UnitTest::SetPrefix("TestFunctions.cpp - Duplicate with children");
		  JSONNode node = JSONNode(JSON_NODE);
		  node.push_back(JSONNode(JSON_TEXT(""), 15));
		  node.push_back(JSONNode(JSON_TEXT(""), JSON_TEXT("hello world")));
		  node.push_back(JSONNode(JSON_TEXT(""), true));

		  TestSuite::testParsingItself(node);

		  JSONNode dup = node.duplicate();
		  assertEquals(dup.size(), 3);
		  #ifdef JSON_UNIT_TEST
			 assertNotEquals(node.internal, dup.internal);
		  #endif
		  assertEquals(dup.type(), JSON_NODE);

		  TestSuite::testParsingItself(node);
		  TestSuite::testParsingItself(dup);

		  try {
			 assertEquals(dup.at(0), 15);
			 assertEquals(dup.at(1), JSON_TEXT("hello world"));
			 assertEquals(dup.at(2), true);
			 assertEquals(dup.at(0), node.at(0));
			 assertEquals(dup.at(1), node.at(1));
			 assertEquals(dup.at(2), node.at(2));
		  } catch (std::out_of_range){
			 FAIL("exception caught");
		  }

		  TestSuite::testParsingItself(dup);

		  #ifdef JSON_ITERATORS
			 for(JSONNode::iterator it = node.begin(), end = node.end(), dup_it = dup.begin();
				it != end;
				++it, ++dup_it){
				assertEquals(*it, *dup_it);
				#ifdef JSON_UNIT_TEST
				    assertNotEquals((*it).internal, (*dup_it).internal);
				#endif
			 }
		  #endif

		  UnitTest::SetPrefix("TestFunctions.cpp - Nullify");
		  test1.nullify();
		  assertEquals(test1.type(), JSON_NULL);
		  assertEquals(test1.name(), JSON_TEXT(""));

		  #ifdef JSON_CASTABLE
			 UnitTest::SetPrefix("TestFunctions.cpp - Cast");
			 test1.cast(JSON_NULL);
			 test2 = 1;
			 test2.cast(JSON_BOOL);
			 assertEquals(test1.type(), JSON_NULL);
			 assertEquals(test2.type(), JSON_BOOL);
			 assertEquals(test2, true);
			 test2 = true;
			 assertEquals(test2, true);
			 test2.cast(JSON_NUMBER);
			 assertEquals(test2, 1.0f);
			 test2 = 0.0f;
			 assertEquals(test2, 0.0f);
			 test2.cast(JSON_BOOL);
			 assertEquals(test2, false);
		  #endif
    
		  UnitTest::SetPrefix("TestFunctions.cpp - Merge");
		  test1 = JSON_TEXT("hello");
		  test2 = JSON_TEXT("hello");
		  #ifdef JSON_UNIT_TEST
			 assertNotEquals(test1.internal, test2.internal);
		  #endif
		  assertEquals(test1, test2);
		  test1.merge(test2);
		  #ifdef JSON_UNIT_TEST
			 #ifdef JSON_REF_COUNT
				  assertEquals(test1.internal, test2.internal);
			 #else
				  assertNotEquals(test1.internal, test2.internal);
			 #endif
		  #endif

		  #ifdef JSON_CASTABLE
			 test1.cast(JSON_NODE);
			 test2.cast(JSON_NODE);
		  #else
			 test1 = JSONNode(JSON_NODE);
			 test2 = JSONNode(JSON_NODE);
		  #endif
		  assertEquals(test1.type(), JSON_NODE);
		  assertEquals(test2.type(), JSON_NODE);
		  test1.push_back(JSONNode(JSON_TEXT("hi"), JSON_TEXT("world")));
		  test2.push_back(JSONNode(JSON_TEXT("hi"), JSON_TEXT("world")));

		  TestSuite::testParsingItself(test1);
		  TestSuite::testParsingItself(test2);

		  test1.merge(test2);
		  #ifdef JSON_UNIT_TEST
			 #ifdef JSON_REF_COUNT
				  assertEquals(test1.internal, test2.internal);
			 #else
				  assertNotEquals(test1.internal, test2.internal);
			 #endif
		  #endif

		  TestSuite::testParsingItself(test1);
		  TestSuite::testParsingItself(test2);
    #endif
}
Пример #29
0
static int _pop(json_parser *parser, modes mode)
{
/*
    Pop the stack, assuring that the current mode matches the expectation.
    Return false if there is underflow or if the modes mismatch.
*/
    json_parser_stack_item *top_stack_item, *parent_stack_item;
    json_value *v, *parent;
    modes parent_mode;
    char name[MAX_NAME_LEN];

    if (parser->top < 0 || parser->stack[parser->top].mode != mode) {
        return false;
    }

    top_stack_item = parser->stack + parser->top;

    if (parser->top > 0) {
        parent_stack_item = parser->stack + parser->top - 1;
        v = top_stack_item->value;
        parent = parent_stack_item->value;
        parent_mode = parent_stack_item->mode;
        
        if (mode == MODE_ARRAY || mode == MODE_OBJECT) {
            assert(v);
            if (parent_mode == MODE_OBJECT_VALUE || parent_mode == MODE_DONE) {
                assert(parent == NULL);
                /* copy to parent level */
                parent_stack_item->value = v;
            } else if (parent_mode == MODE_ARRAY) {
                assert(parent && json_type(parent) == json_type_array);
                /* insert v into the array */
                if (!json_array_set(parent, json_array_size(parent), v))
                    return false;
            } else {
                assert(0);
                return false;
            }

        } else if (mode == MODE_OBJECT_KEY) {
            if (parent && parent_mode == MODE_OBJECT) {
                /* copy to parent level */
                parent_stack_item->name_begin = top_stack_item->name_begin;
                parent_stack_item->name_len = top_stack_item->name_len;
            } else {
                assert(0);
                return false;
            }

        } else if (mode == MODE_OBJECT_VALUE) {
            assert(v);
            if (parent && parent_mode == MODE_OBJECT) {
                /* insert v into the object */
                if (!_get_object_name(&parser->config, 
                        parent_stack_item->name_begin, 
                        parent_stack_item->name_len, 
                        name)
                    )
                    return false;
                if (!json_object_set(parent, name, v))
                    return false;
            } else {
                assert(0);
                return false;
            }
        }
    }

    memset(top_stack_item, 0, sizeof(json_parser_stack_item));
    parser->top -= 1;
    
    return true;
}