예제 #1
0
void eventbus_register(String address,void (*func)(String *)){
    handler_t handler;
    handler.address=address;
    handler.function=func;
	
    if(find(address)==false){
        jsonMessage_t js;
        js.address=address;
        js.type="register";
		js.replyAddress=NULL;
        JSON_Value *body = json_parse_string(NULL);
        JSON_Value *headers = json_parse_string(NULL);

        js.body=body;
        js.headers=headers;
        String message=NULL;
        getMessage(js,&message);
		
        send_frame(&message);
	
        free(message);
    }
    insertFirst(node_index,handler);
    node_index++;
}
예제 #2
0
파일: json.c 프로젝트: Ludophonic/json.h
static void json_parse_key(struct json_parse_state_s *state,
                          struct json_string_s *string) {
  if (json_parse_flags_allow_unquoted_keys & state->flags_bitset) {
    // if we are allowing unquoted keys, check for quoted anyway...
    if ('"' == state->src[state->offset]) {
      // ... if we got a comma, just parse the key as a string as normal
      json_parse_string(state, string);
    } else {
      size_t size = 0;

      string->string = state->data;

      while ((state->offset < state->size) &&
             is_valid_unquoted_key_char(state->src[state->offset])) {
        state->data[size++] = state->src[state->offset++];
      }

      // add null terminator to string
      state->data[size] = '\0';

      // record the size of the string
      string->string_size = size++;

      // move data along
      state->data += size;
    }
  } else {
    // we are only allowed to have quoted keys, so just parse a string!
    json_parse_string(state, string);
  }
}
예제 #3
0
파일: tests.c 프로젝트: xiaodezhang/cgi
void test_suite_2_with_comments(void) {
	const char *filename = "tests/test_2_comments.txt";
	JSON_Value *root_value = NULL;
	root_value = json_parse_file_with_comments(filename);
	test_suite_2(root_value);
	TEST(json_value_equals(root_value, json_parse_string(json_serialize_to_string(root_value))));
	TEST(json_value_equals(root_value, json_parse_string(json_serialize_to_string_pretty(root_value))));
	json_value_free(root_value);
}
예제 #4
0
void eventbus_publish(String address,String Headers,String Body){
    jsonMessage_t js;
    js.address=address;
    js.type="publish";
	js.replyAddress=NULL;
    JSON_Value *body = json_parse_string(Body);
    JSON_Value *headers = json_parse_string(Headers);

    js.body=body;
    js.headers=headers;
    String message=NULL;
    getMessage(js,&message);
    send_frame(&message);
    free(message);
}
PROVISIONING_QUERY_RESPONSE* queryResponse_deserializeFromJson(const char* json_string, PROVISIONING_QUERY_TYPE type)
{
     PROVISIONING_QUERY_RESPONSE* new_result = NULL;
     JSON_Value* root_value = NULL;
     JSON_Array* root_array = NULL;

     if (json_string == NULL)
     {
         LogError("Cannot deserialize NULL");
     }
     else if (type == QUERY_TYPE_INVALID)
     {
         LogError("Invalid query type");
     }
     else if ((root_value = json_parse_string(json_string)) == NULL)
     {
         LogError("Parsing JSON string failed");
     }
     else if ((root_array = json_value_get_array(root_value)) == NULL)
     {
         LogError("Creating JSON array failed");
         json_value_free(root_value);
     }
     else
     {
         if ((new_result = queryResponse_fromJson(root_array, type)) == NULL)
         {
             LogError("Creating new Query Response failed");
         }
         json_value_free(root_value); //implicitly frees root_array
         root_value = NULL;
     }

     return new_result;
}
int APP_ParseCommand(char * pReadBuffer)
{
    if(pReadBuffer == NULL)
        return COMMAND_BAD_POINTER;
    JSON_Value *rootValue = json_parse_string(pReadBuffer);
    if (json_value_get_type(rootValue) != JSONObject)
            return COMMAND_BAD_JSON;
    JSON_Object * tObject = json_value_get_object(rootValue);
        
    if(json_object_dotget_string(tObject, "message.command") != NULL)
    {
        if(strcmp(json_object_dotget_string(tObject, "message.command"), "hello") == 0)
        {
            return COMMAND_HELLO;
        }
        else if (strcmp(json_object_dotget_string(tObject, "message.command"), "configuration") == 0)
        {
            return COMMAND_CONFIGURE;
        }
        else if (strcmp(json_object_dotget_string(tObject, "message.command"), "debug_set") == 0)
        {
            return COMMAND_DEBUG_SET;
        }
        else
        {
            return COMMAND_INVALID;
        }
    }
    else
    {
        return COMMAND_INVALID;
    }
    return COMMAND_INVALID;
}
예제 #7
0
void parseJSON() {
    JSON_Value *root_value = json_parse_string(getData);
    
    if (root_value != NULL) {
        JSON_Value_Type type = root_value->type;
        
        if (type == JSONArray) {
            JSON_Array *stations = json_value_get_array(root_value);
            
            char lookupCallsign[32];
            sprintf(lookupCallsign, "%s%s", icaoCode, "_ATIS");
            
            for (int i = 0; i < json_array_get_count(stations); i++) {
                const JSON_Object *station = json_array_get_object(stations, i);
                const char *callsign = json_object_dotget_string(station, "callsign");
                
                if (strcmp(callsign, lookupCallsign) == 0) {
                    message = json_object_dotget_string(station, "atis");
                    XPLMDebugString(message);
                    break;
                }
            }
        }
        
        json_value_free(root_value);
    }
    
    newData = 0;
}
예제 #8
0
static void web_SockJsServer_message(web_SockJsServer _this, struct mg_connection *conn) {
    web_SockJsServer_Connection c = web_SockJsServer_Connection(conn->connection_param);
    if (_this->onMessage._parent.procedure) {
        if (conn->content_len) {
            char *msg = cx_malloc(conn->content_len + 1);
            memcpy(msg, conn->content, conn->content_len);
            msg[conn->content_len] = '\0';

            /* Parse & unpack message */
            JSON_Value *root = json_parse_string(msg);
            if (!root) {
                goto error;
            }

            if (json_value_get_type(root) == JSONArray) {
                JSON_Array *messages = json_value_get_array(root);
                cx_uint32 i;
                for (i = 0; i < json_array_get_count(messages); i++) {
                    const char *message = json_array_get_string(messages, i);
                    cx_call(_this->onMessage._parent.procedure, NULL, _this->onMessage._parent.instance, c, message);
                }
            }

            json_value_free(root);
        }
    }
error:;
}
예제 #9
0
파일: api.cpp 프로젝트: bwRavencl/X-fr24
// returns the name of the zone that fits the given latitude and longitude best
static char *GetZoneName(double latitude, double longitude)
{
    char *zoneName = NULL;
    char *zones = GetUrl(URL_ZONES);

    if (zones != NULL)
    {
        JSON_Value *rootJson = json_parse_string(zones);
        free(zones);
        zones = NULL;

        if (rootJson != NULL)
        {
            if (rootJson->type == JSONObject)
            {
                double bestDistance = -1.0;
                ParseZones(&zoneName, &bestDistance, json_value_get_object(rootJson), latitude, longitude);
            }

            json_value_free(rootJson);
            rootJson = NULL;
        }
    }

    return zoneName;
}
예제 #10
0
파일: main.c 프로젝트: 9re/LobiJniSample
static void handle_lobi_error(ANativeActivity *nativeActivity, int code, const char *response) {
    // see 
    // https://github.com/nakamap/docs/wiki/Android-SDK-Docs#wiki-nakamap-callback
    switch (code) {
    case LOBI_NETWORK_ERROR:
        // do something
        break;
    case LOBI_RESPONSE_ERROR:
        // do something
        break;
    case LOBI_FATAL_ERROR:
        {
            JSON_Value *responseValue = json_parse_string(response);
            JSON_Object *jsonObject = json_value_get_object(responseValue);
            // do something.
            // only in this case, response is not null and has
            // an array of messages with the key 'error'
            JSON_Array *errors = json_object_get_array((const JSON_Object *)jsonObject, "error");
            if (errors) {
                for (size_t i = 0, len = json_array_get_count(errors);
                     i < len; ++i) {
                    const char *error = json_array_get_string(errors, i);
                    lobi_showToast(nativeActivity, error);
                    LOGV("error #%d: %s", i, error);
                }
            }

            json_value_free(responseValue);
            break;
        }
    }
}
예제 #11
0
파일: json.c 프로젝트: hilesaz/drivle
struct json_val *json_parse_value(struct read_state *state)
{
    struct json_val *value;
    char ch;
    
    if (read_state_left(state) < 1) {
        json_error_print(state, "Unexpected end of file parsing generic value\n");
        return 0;
    }
    ch = *state->read;
    
    switch (ch) {
        case 't':
            value = json_parse_true(state);
            break;
        case 'f':
            value = json_parse_false(state);
            break;
        case 'n':
            value = json_parse_null(state);
            break;
        case '\"':
            value = json_parse_string(state);
            break;
        case '{':
            value = json_parse_object(state);
            break;
        case '[':
            value = json_parse_array(state);
            break;
        default:
            value = json_parse_number(state);
    }
    return value;
}
예제 #12
0
파일: ejs-json.c 프로젝트: eberan/echo-js
/* 15.12.2 */
static ejsval
_ejs_JSON_parse (ejsval env, ejsval _this, uint32_t argc, ejsval *args)
{
    ejsval text = _ejs_undefined;
    ejsval reviver = _ejs_undefined;

    if (argc > 0) text = args[0];
    if (argc > 1) reviver = args[1];


    /* 1. Let JText be ToString(text). */
    ejsval jtext = ToString(text);

    /* 2. Parse JText using the grammars in 15.12.1. Throw a SyntaxError exception if JText did not conform to the 
       JSON grammar for the goal symbol JSONText.  */
    char *flattened_jtext =  ucs2_to_utf8(EJSVAL_TO_FLAT_STRING(jtext));

    /* 3. Let unfiltered be the result of parsing and evaluating JText as if it was the source text of an ECMAScript 
       Program but using JSONString in place of StringLiteral. Note that since JText conforms to the JSON 
       grammar this result will be either a primitive value or an object that is defined by either an ArrayLiteral or 
       an ObjectLiteral. */
    JSON_Value* root_val = json_parse_string(flattened_jtext);

    free(flattened_jtext);

    if (root_val == NULL) {
        printf ("SyntaxError\n");
        EJS_NOT_IMPLEMENTED();
    }

    ejsval unfiltered;
    if (!json_value_to_ejsval(root_val, &unfiltered)) {
        json_value_free (root_val);
        /* unfiltered here is an exception */
        EJS_NOT_IMPLEMENTED();
    }

    json_value_free (root_val);

    /* 4. If IsCallable(reviver) is true, then */
    if (EJSVAL_IS_CALLABLE(reviver)) {
        printf ("no reviver support in JSON.parse yet\n");
        EJS_NOT_IMPLEMENTED();
        /*    a. Let root be a new object created as if by the expression new Object(), where Object is the
              standard built-in constructor with that name. */
        /*    b. Call the [[DefineOwnProperty]] internal method of root with the empty String, the 
              PropertyDescriptor {[[Value]]: unfiltered, [[Writable]]: true, [[Enumerable]]: true, 
              [[Configurable]]: true}, and false as arguments. */
        /*    c. Return the result of calling the abstract operation Walk, passing root and the empty String. The 
              abstract operation Walk is described below. */
    }
    /* 5. Else */
    else {
        /*    a. Return unfiltered. */
        return unfiltered;
    }
}
예제 #13
0
/******************************************************************************
 *                                                                            *
 * Function: json_parse_object                                                *
 *                                                                            *
 * Purpose: Parses JSON object                                                *
 *                                                                            *
 * Parameters: start - [IN] the JSON data                                     *
 *             error - [OUT] the parsing error message (can be NULL)          *
 *                                                                            *
 * Return value: The number of characters parsed. On error 0 is returned and  *
 *               error parameter (if not NULL) contains allocated error       *
 *               message.                                                     *
 *                                                                            *
 * Author: Andris Zeila                                                       *
 *                                                                            *
 ******************************************************************************/
static int	json_parse_object(const char *start, char **error)
{
	const char	*ptr = start;
	int		len;

	/* parse object name */
	SKIP_WHITESPACE(ptr);

	/* not an object, failing */
	if ('{' != *ptr)
		return json_error("invalid object format, expected opening character '{'", ptr, error);

	ptr++;
	SKIP_WHITESPACE(ptr);

	if ('}' != *ptr)
	{
		while (1)
		{
			if ('"' != *ptr)
				return json_error("invalid object name", ptr, error);

			/* cannot parse object name, failing */
			if (0 == (len = json_parse_string(ptr, error)))
				return 0;

			ptr += len;

			/* parse name:value separator */
			SKIP_WHITESPACE(ptr);

			if (':' != *ptr)
				return json_error("invalid object name/value separator", ptr, error);
			ptr++;

			if (0 == (len = json_parse_value(ptr, error)))
				return 0;

			ptr += len;

			SKIP_WHITESPACE(ptr);

			if (',' != *ptr)
				break;

			ptr++;
			SKIP_WHITESPACE(ptr);
		}

		/* object is not properly closed, failing */
		if ('}' != *ptr)
			return json_error("invalid object format, expected closing character '}'", ptr, error);
	}

	return ptr - start + 1;
}
예제 #14
0
 virtual ParseResultBase* Parse(const char* json, size_t length) const {
     (void)length;
     ParsonParseResult* pr = new ParsonParseResult;
     pr->root = json_parse_string(json);
     if (!pr->root) {
         delete pr;
         return 0;
     }
 	return pr;
 }
예제 #15
0
void eventbus_unregister(String address){

    if(find(address)==false){
        jsonMessage_t js;
        js.address=address;
        js.type="register";
		js.replyAddress=NULL;
        JSON_Value *body = json_parse_string(NULL);
        JSON_Value *headers = json_parse_string(NULL);

        js.body=body;
        js.headers=headers;
        String message=NULL;
        getMessage(js,&message);
        send_frame(&message);
        free(message);
    }
    delete_node(&address);
}
예제 #16
0
파일: api.cpp 프로젝트: bwRavencl/X-fr24
// retrieves the balancer url with the lowest load, if there are several balancers with the same load one of these is randomly selected
static char *GetBalancerUrl(void)
{
    char *bestUrl = NULL;

    char *balance = GetUrl(URL_BALANCE);
    if (balance != NULL)
    {
        JSON_Value *rootJson = json_parse_string(balance);
        free(balance);
        balance = NULL;

        if (rootJson != NULL && rootJson->type == JSONObject)
        {
            JSON_Object *serversJson = json_value_get_object(rootJson);

            if (serversJson != NULL)
            {
                size_t serverCount = json_object_get_count(serversJson);
                int bestLoad = 0;

                for (int i = 0; i < serverCount; i++)
                {
                    const char *url = json_object_get_name(serversJson, i);

                    JSON_Value *value = json_object_get_value(serversJson, url);

                    if (value != NULL && value->type == JSONNumber)
                    {
                        int load = (int) json_object_get_number(serversJson, url);

                        if (load != 0 && (bestUrl == NULL || load <= bestLoad/* || (load == bestLoad && rand() % 2)*/))
                        {
                            if (bestUrl != NULL)
                            {
                                free(bestUrl);
                                bestUrl = NULL;
                            }

                            bestUrl = (char*) malloc(strlen(url) + 1);
                            if (bestUrl != NULL)
                                strcpy(bestUrl, url);

                            bestLoad = load;
                        }
                    }
                }
            }

            json_value_free(rootJson);
            rootJson = NULL;
        }
    }

    return bestUrl;
}
예제 #17
0
/******************************************************************************
 *                                                                            *
 * Function: json_parse_value                                                 *
 *                                                                            *
 * Purpose: Parses JSON object value                                          *
 *                                                                            *
 * Parameters: start - [IN] the JSON data                                     *
 *             error - [OUT] the parsing error message (can be NULL)          *
 *                                                                            *
 * Return value: The number of characters parsed. On error 0 is returned and  *
 *               error parameter (if not NULL) contains allocated error       *
 *               message.                                                     *
 *                                                                            *
 * Author: Andris Zeila                                                       *
 *                                                                            *
 ******************************************************************************/
int	json_parse_value(const char *start, char **error)
{
	const char	*ptr = start;
	int		len;

	SKIP_WHITESPACE(ptr);

	switch (*ptr)
	{
		case '\0':
			return json_error("unexpected end of object value", NULL, error);
		case '"':
			if (0 == (len = json_parse_string(ptr, error)))
				return 0;
			break;
		case '{':
			if (0 == (len = json_parse_object(ptr, error)))
				return 0;
			break;
		case '[':
			if (0 == (len = json_parse_array(ptr, error)))
				return 0;
			break;
		case 't':
			if (0 == (len = json_parse_literal(ptr, "true", error)))
				return 0;
			break;
		case 'f':
			if (0 == (len = json_parse_literal(ptr, "false", error)))
				return 0;
			break;
		case 'n':
			if (0 == (len = json_parse_literal(ptr, "null", error)))
				return 0;
			break;
		case '0':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
		case '-':
			if (0 == (len = json_parse_number(ptr, error)))
				return 0;
			break;
		default:
			return json_error("invalid JSON object value starting character", ptr, error);
	}

	return ptr - start + len;
}
예제 #18
0
파일: json.c 프로젝트: itsusony/mysql_json
char *json(UDF_INIT *initid, UDF_ARGS *args,
      char *result, unsigned long *length,
      char *is_null, char *error)
{
    JSON_Value *jv = json_parse_string(args->args[0]);
    JSON_Value_Type json_type = json_value_get_type(jv);
    if(json_type==JSONError){
        *length=0;
        *is_null=1;
        *error=1;
        json_value_free(jv);
        return NULL;
    }else{
        if(json_type == JSONObject){
            JSON_Object *o = json_value_get_object(jv);
            JSON_Value *value = json_object_dotget_value(o,args->args[1]);
            if(value==NULL){
                *length = 0;
                *is_null = 0;
                return NULL;
            }else{
                *is_null = 0;
                switch(json_value_get_type(value)){
                    case JSONArray:
                        *is_null = 1;
                        break;
                    case JSONError:
                    case JSONObject:
                        *is_null = 1;
                        *error = 1;
                        break;
                    case JSONString:
                        strcpy(initid->ptr,((char*)json_value_get_string(value)));
                        break;
                    case JSONNumber:
                        sprintf(initid->ptr,"%f",json_value_get_number(value));
                        break;
                    case JSONNull:
                        *is_null = 1;
                        break;
                    case JSONBoolean:
                        sprintf(initid->ptr,"%d",json_value_get_boolean(value));
                        break;
                }
                *length = initid->ptr == NULL ? 0 : strlen(initid->ptr); 
            }
        }else{
            *is_null = 1;
        }
        json_value_free(jv);
        return initid->ptr; 
    }
}
예제 #19
0
파일: json.c 프로젝트: wschnrid/yaz
static struct json_node *json_parse_value(json_parser_t p)
{
    int c = look_ch(p);
    if (c == '\"')
        return json_parse_string(p);
    else if (strchr("0123456789-", c))
        return json_parse_number(p);
    else if (c == '{')
        return json_parse_object(p);
    else if (c == '[')
        return json_parse_array(p);
    else if (c == '%')
    {
        struct json_subst_info *sb;
        int idx = 0;
        p->cp++;
        c = *p->cp;
        while (c >= '0' && c <= '9')
        {
            idx = idx*10 + (c - '0');
            p->cp++;
            c = *p->cp;
        }
        for (sb = p->subst; sb; sb = sb->next)
            if (sb->idx == idx)
                return sb->node;
    }
    else if (c == 0)
    {
        return 0;
    }
    else
    {
        char tok[8];
        int i = 0;
        while (c >= 'a' && c <= 'z' && i < 7)
        {
            tok[i++] = c;
            p->cp++;
            c = *p->cp;
        }
        tok[i] = 0;
        if (!strcmp(tok, "true"))
            return json_new_node(p, json_node_true);
        else if (!strcmp(tok, "false"))
            return json_new_node(p, json_node_false);
        else if (!strcmp(tok, "null"))
            return json_new_node(p, json_node_null);
    }
    p->err_msg = "bad token";
    return 0;
}
예제 #20
0
corto_int16 json_deserialize(corto_value *v, corto_string s)
{
    corto_assert(v != NULL, "NULL passed to json_deserialize");

    char *json = s;
    if ((json[0] != '{') && (json[1] != '[') && (json[0] != '[')) {
        corto_asprintf(&json, "{\"value\": %s}", json);
    }

    JSON_Value *jsonValue = json_parse_string(json);
    if (!jsonValue) {
        corto_seterr("invalid JSON '%s'", json);
        goto error;
    }

    corto_type type = corto_value_getType(v);

    if (type->kind == CORTO_PRIMITIVE) {
        JSON_Object* jsonObj = json_value_get_object(jsonValue);
        if (!jsonObj) {
            corto_seterr("json: invalid JSON for primitive value '%s'", json);
            goto error;
        }

        JSON_Value *jsonValue = json_object_get_value(jsonObj, "value");
        if (!jsonValue) {
            corto_seterr("json: missing 'value' field for primitive value '%s'", json);
            goto error;
        }
    }

    if (json_deserialize_from_JSON_Value(v, jsonValue)) {
        goto error;
    }

    if (json != s) {
        corto_dealloc(json);
    }

    return 0;
error:
    if (json != s) {
        corto_dealloc(json);
    }

    if (jsonValue) {
        json_value_free(jsonValue);
    }
    return -1;
}
예제 #21
0
static int
json_parse_object(const unsigned char **ucp, const unsigned char *ue,
	size_t *st, size_t lvl)
{
	const unsigned char *uc = *ucp;
	DPRINTF("Parse object: ", uc, *ucp);
	while (uc < ue) {
		uc = json_skip_space(uc, ue);
		if (uc == ue)
			goto out;
		if (*uc++ != '"') {
			DPRINTF("not string", uc, *ucp);
			goto out;
		}
		DPRINTF("next field", uc, *ucp);
		if (!json_parse_string(&uc, ue)) {
			DPRINTF("not string", uc, *ucp);
			goto out;
		}
		uc = json_skip_space(uc, ue);
		if (uc == ue)
			goto out;
		if (*uc++ != ':') {
			DPRINTF("not colon", uc, *ucp);
			goto out;
		}
		if (!json_parse(&uc, ue, st, lvl + 1)) {
			DPRINTF("not json", uc, *ucp);
			goto out;
		}
		if (uc == ue)
			goto out;
		switch (*uc++) {
		case ',':
			continue;
		case '}': /* { */
			*ucp = uc;
			DPRINTF("Good object: ", uc, *ucp);
			return 1;
		default:
			*ucp = uc - 1;
			DPRINTF("not more", uc, *ucp);
			goto out;
		}
	}
out:
	DPRINTF("Bad object: ", uc, *ucp);
	*ucp = uc;
	return 0;
}
예제 #22
0
파일: tests.c 프로젝트: Kutoc/parson
void serialization_example(void) {
    JSON_Value *root_value = json_value_init_object();
    JSON_Object *root_object = json_value_get_object(root_value);
    char *serialized_string = NULL;
    json_object_set_string(root_object, "name", "John Smith");
    json_object_set_number(root_object, "age", 25);
    json_object_dotset_string(root_object, "address.city", "Cupertino");
    json_object_dotset_value(root_object, "contact.emails",
                             json_parse_string("[\"[email protected]\", \"[email protected]\"]"));
    serialized_string = json_serialize_to_string(root_value);
    puts(serialized_string);
    json_free_serialized_string(serialized_string);
    json_value_free(root_value);
}
예제 #23
0
/*typically "left" is the output of SERIALIZE... and right is hand-coded JSON*/
static bool areTwoJsonsEqual(const unsigned char* left, size_t leftSize, const char* right)
{
    bool result;

    char* cloneOfLeft = (char*)malloc(leftSize + 1); /*because of out SERIALIZE... there is a byte array that is NOT '\0' terminated*/
    ASSERT_IS_NOT_NULL(cloneOfLeft);

    (void)memcpy(cloneOfLeft, left, leftSize);
    cloneOfLeft[leftSize] = '\0';

    JSON_Value* actualJson = json_parse_string((char*)cloneOfLeft);
    ASSERT_IS_NOT_NULL(actualJson);
    JSON_Value* expectedJson = json_parse_string(right);
    ASSERT_IS_NOT_NULL(expectedJson);

    result = (json_value_equals(expectedJson, actualJson) != 0);

    json_value_free(expectedJson);
    json_value_free(actualJson);
    free(cloneOfLeft);

    return result;
}
예제 #24
0
파일: port.c 프로젝트: migadu/gmimex
int main(void) {
    int bytes_read;
    gchar buffer[MAX_BUFFER_SIZE];
    JSON_Value *root_value;
    JSON_Object *root_object;
    gchar *json_str;
    gchar *func_name;
    gchar *path;

    while((bytes_read = read_msg(buffer)) > 0) {
    	json_str = g_strndup((const gchar *)buffer, bytes_read);
    	root_value = json_parse_string(json_str);
    	root_object = json_value_get_object(root_value);
    	func_name = (gchar *)json_object_get_string(root_object, "exec");
    	path = (gchar *)json_object_get_string(root_object, "path");
			GString *json_message = NULL;

    	if (!g_ascii_strcasecmp(func_name, "get_preview_json")) {
				json_message = gmimex_get_json(path, JSON_NO_MESSAGE_CONTENT);
  			if (!json_message) {
  				send_err();
  			} else {
					send_msg((gchar *)json_message->str, json_message->len);
			  	g_string_free(json_message, TRUE);
			  }
    	} else if (!g_ascii_strcasecmp(func_name, "get_json")) {
  			gboolean raw = json_object_get_boolean(root_object, "raw");
  			json_message = gmimex_get_json(path, (raw ? JSON_RAW_MESSAGE_CONTENT : JSON_PREPARED_MESSAGE_CONTENT));
  			if (!json_message) {
  				send_err();
  			} else {
					send_msg((gchar *)json_message->str, json_message->len);
			  	g_string_free(json_message, TRUE);
			  }
    	} else if (!g_ascii_strcasecmp(func_name, "get_part")) {
    		int part_id = json_object_get_number(root_object, "partId");
			  GByteArray *part_content = gmimex_get_part(path, part_id);
			  if (!part_content) {
			  	send_err();
			  } else {
    			send_msg((gchar *)part_content->data, part_content->len);
    			g_byte_array_free(part_content, TRUE);
    		}
    	}
    	json_value_free(root_value);
    	g_free(json_str);
    }
    return 0;
}
예제 #25
0
static ACVP_RESULT inspect_http_code(ACVP_CTX *ctx, int code) {
    ACVP_RESULT result = ACVP_TRANSPORT_FAIL; /* Generic failure */
    JSON_Value *root_value = NULL;
    const JSON_Object *obj = NULL;
    const char *err_str = NULL;

    if (code == HTTP_OK) {
        /* 200 */
        return ACVP_SUCCESS;
    }

    if (code == HTTP_UNAUTH) {
        int diff = 1;

        root_value = json_parse_string(ctx->curl_buf);

        obj = json_value_get_object(root_value);
        if (!obj) {
            ACVP_LOG_ERR("HTTP body doesn't contain top-level JSON object");
            goto end;
        }

        err_str = json_object_get_string(obj, "error");
        if (!err_str) {
            ACVP_LOG_ERR("JSON object doesn't contain 'error'");
            goto end;
        }

        strncmp_s(JWT_EXPIRED_STR, JWT_EXPIRED_STR_LEN, err_str, JWT_EXPIRED_STR_LEN, &diff);
        if (!diff) {
            result = ACVP_JWT_EXPIRED;
            goto end;
        }

        strncmp_s(JWT_INVALID_STR, JWT_INVALID_STR_LEN, err_str, JWT_INVALID_STR_LEN, &diff);
        if (!diff) {
            result = ACVP_JWT_INVALID;
            goto end;
        }
    }

end:
    if (root_value) json_value_free(root_value);

    return result;
}
예제 #26
0
static mrb_value
mrb_json_parse(mrb_state *mrb, mrb_value self)
{
  mrb_value value;
  JSON_Value *root_value;
  mrb_value json = mrb_nil_value();
  mrb_get_args(mrb, "S", &json);

  root_value = json_parse_string(mrb_str_to_cstr(mrb, json));
  if (!root_value) {
    mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid json");
  }

  value = json_value_to_mrb_value(mrb, root_value);
  json_value_free(root_value);
  return value;
}
예제 #27
0
static mrb_value
mrb_json_parse(mrb_state *mrb, mrb_value self)
{
  mrb_value json = mrb_nil_value();
  mrb_get_args(mrb, "o", &json);
  if (!mrb_string_p(json)) {
    mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid argument");
  }

  JSON_Value *root_value = json_parse_string(RSTRING_PTR(json));
  if (!root_value) {
    mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid json");
  }

  mrb_value value = json_value_to_mrb_value(mrb, root_value);
  json_value_free(root_value);
  return value;
}
예제 #28
0
파일: tests.c 프로젝트: Kutoc/parson
void persistence_example(void) {
    JSON_Value *schema = json_parse_string("{\"name\":\"\"}");
    JSON_Value *user_data = json_parse_file("user_data.json");
    char buf[256];
    const char *name = NULL;
    if (user_data == NULL || json_validate(schema, user_data) != JSONSuccess) {
        puts("Enter your name:");
        scanf("%s", buf);
        user_data = json_value_init_object();
        json_object_set_string(json_object(user_data), "name", buf);
        json_serialize_to_file(user_data, "user_data.json");
    }
    name = json_object_get_string(json_object(user_data), "name");
    printf("Hello, %s.", name);
    json_value_free(schema);
    json_value_free(user_data);
    return;
}
static MODULE_HANDLE SimulatedDevice_HL_Create(MESSAGE_BUS_HANDLE busHandle, const void* configuration)
{
	MODULE_HANDLE result;
    if (busHandle == NULL || configuration == NULL)
    {
		LogError("invalid SIMULATED_DEVICE_HL module args.");
        result = NULL;
    }
    else
    {
        JSON_Value* json = json_parse_string((const char*)configuration);
        if (json == NULL)
        {
            LogError("unable to json_parse_string");
            result = NULL;
        }
        else
        {
            JSON_Object* root = json_value_get_object(json);
            if (root == NULL)
            {
                LogError("unable to json_value_get_object");
                result = NULL;
            }
            else
            {
                const char* macAddress = json_object_get_string(root, "macAddress");
                if (macAddress == NULL)
                {
                    LogError("unable to json_object_get_string");
                    result = NULL;
                }
                else
                {
                    result = MODULE_STATIC_GETAPIS(SIMULATED_DEVICE_MODULE)()->Module_Create(busHandle, macAddress);
                }
            }
            json_value_free(json);
        }
    }
	return result;
}
예제 #30
0
파일: djcs.c 프로젝트: tiehuis/libhcs
int djcs_import_public_key(djcs_public_key *pk, const char *json)
{
    JSON_Value *root = json_parse_string(json);
    JSON_Object *obj = json_value_get_object(root);
    pk->s = json_object_get_number(obj, "s");
    pk->n = malloc(sizeof(mpz_t) * (pk->s + 1));

    mpz_init(pk->n[0]);
    mpz_set_str(pk->n[0], json_object_get_string(obj, "n"), HCS_INTERNAL_BASE);
    json_value_free(root);

    /* Calculate remaining values */
    mpz_add_ui(pk->g, pk->n[0], 1);
    for (unsigned long i = 1; i <= pk->s; ++i) {
        mpz_init_set(pk->n[i], pk->n[i-1]);
        mpz_mul(pk->n[i], pk->n[i], pk->n[0]);
    }

    return 0;
}