예제 #1
0
파일: protocol4.c 프로젝트: toha/piswitch
/**
	json 2 protocol4
*/
int json_decode_protocol4 (protocol4* self, json_t* root) 
{
  json_error_t error;

	if (!root) {
		  fprintf(stderr, "error: on line %d: %s\n", error.line, error.text);
		  return 1;
	}

	if (!json_is_object(root)) {
		  fprintf(stderr, "error: root is not an object\n");
			json_decref(root);
			json_decref(root);
		  return 1;
	}

	json_t *network, *address, *magic;

  network = json_object_get(root, "network");
  address = json_object_get(root, "address");
  magic = json_object_get(root, "magic");

  if(!json_is_number(network) ||  !json_is_number(address) || !json_is_number(magic)) {
      fprintf(stderr, "error: something is not a number\n");
      json_decref(root);
      return 1;
  }

	self->network = json_number_value(network);
	self->address = json_number_value(address);
	self->magic = json_number_value(magic);
	
	return 0;
} 
예제 #2
0
/* 判断janson的类型 */
int my_json_type(json_t *value)
{
    if(json_is_object(value))
	{
        printf("json_is_object\n");
		return JSON_OBJECT;
	}

    if(json_is_array(value))
	{
        printf("json_is_array\n");
		return JSON_ARRAY;
	}

    if(json_is_string(value))
	{
        printf("json_is_string\n");
		return JSON_STRING;
	}

    if(json_is_integer(value))
	{
        printf("json_is_integer\n");
		return JSON_INTEGER;
	}

    if(json_is_real(value))
	{
        printf("json_is_real\n");
		return JSON_REAL;
	}

    if(json_is_number(value))
	{
        printf("json_is_number\n");
	}

    if(json_is_boolean(value))
	{
        printf("json_is_boolean\n");
	}

    if(json_is_null(value))
	{
        printf("json_is_null\n");
		return JSON_NULL;
	}

	if(json_is_true(value))
	{
        printf("json_boolean(1)\n");
		return JSON_TRUE;
	}

    if(json_is_false(value))
	{
        printf("json_boolean(0)\n");
		return JSON_FALSE;
	}
}
예제 #3
0
파일: cxJson.c 프로젝트: 812872970/cxEngine
cxBool cxJsonPushValue(json_t *value)
{
    if(json_is_integer(value)){
        lua_pushinteger(gL,(int)json_integer_value(value));
    }else if(json_is_string(value)){
        lua_pushstring(gL, json_string_value(value));
    }else if(json_is_number(value)){
        lua_pushnumber(gL, json_number_value(value));
    }else if(json_is_true(value)){
        lua_pushboolean(gL, 1);
    }else if(json_is_false(value)){
        lua_pushboolean(gL, 0);
    }else if(json_is_null(value)){
        lua_pushnil(gL);
    }else if(json_is_real(value)){
        lua_pushnumber(gL, json_real_value(value));
    }else if(json_is_object(value)){
        cxJsonPushObject(value);
    }else if(json_is_array(value)){
        cxJsonPushArray(value);
    }else{
        return false;
    }
    return true;
}
예제 #4
0
/**
 * GET /leave/:join
 */
static void twitch_join()
{
	char url[256];
	sprintf(url, "%sjoin/%s", TwitchExtendedBaseUrl, gConfigTwitch.channel);

	_twitchState = TWITCH_STATE_JOINING;
	_twitchIdle = false;

	http_json_request request;
	request.url = url;
	request.method = HTTP_METHOD_GET;
	request.body = NULL;
	http_request_json_async(&request, [](http_json_response *jsonResponse) -> void {
		if (jsonResponse == NULL) {
			_twitchState = TWITCH_STATE_LEFT;
			console_writeline("Unable to connect to twitch channel.");
		} else {
			json_t *jsonStatus = json_object_get(jsonResponse->root, "status");
			if (json_is_number(jsonStatus) && json_integer_value(jsonStatus) == 200)
				_twitchState = TWITCH_STATE_JOINED;
			else
				_twitchState = TWITCH_STATE_LEFT;

			http_request_json_dispose(jsonResponse);

			_twitchLastPulseTick = 0;
			console_writeline("Connected to twitch channel.");
		}
		_twitchIdle = true;
	});
}
예제 #5
0
/**
 * Gets the specified field from a json string
 */
tABC_CC ABC_UtilGetIntValueFromJSONString(const char *szJSON,
                                          const char *szFieldName,
                                          int       *pValue,
                                          tABC_Error *pError)
{
    tABC_CC cc = ABC_CC_Ok;

    json_t *pJSON_Root = NULL;
    json_t *pJSON_Value = NULL;

    ABC_CHECK_NULL(szJSON);
    ABC_CHECK_NULL(szFieldName);
    ABC_CHECK_NULL(pValue);

    // decode the object
    json_error_t error;
    pJSON_Root = json_loads(szJSON, 0, &error);
    ABC_CHECK_ASSERT(pJSON_Root != NULL, ABC_CC_JSONError, "Error parsing JSON");
    ABC_CHECK_ASSERT(json_is_object(pJSON_Root), ABC_CC_JSONError, "Error parsing JSON");

    // get the field
    pJSON_Value = json_object_get(pJSON_Root, szFieldName);
    ABC_CHECK_ASSERT((pJSON_Value && json_is_number(pJSON_Value)), ABC_CC_JSONError, "Error parsing JSON int value");
    *pValue = (int) json_integer_value(pJSON_Value);

exit:
    if (pJSON_Root) json_decref(pJSON_Root);

    return cc;
}
예제 #6
0
파일: weather_wunder.c 프로젝트: maxux/z03
static int wunder_parse(json_t *root, weather_data_t *weather) {
	json_t *node, *subnode;
	
	node = json_object_get(root, "current_observation");
	if(!json_is_object(node)) {
		fprintf(stderr, "[-] wunder/parse: cannot get current_observation\n");
		return 0;
	}
	
	/* grab location */	
	subnode = json_object_get(node, "display_location");
	if(!json_is_object(subnode)) {
		fprintf(stderr, "[-] wunder/parse: cannot get display_location\n");
		return 0;
	}
	
	if(!(json_string_value(json_object_get(subnode, "full")))) {
		fprintf(stderr, "[-] wunder/parse: cannot get full\n");
		return 0;
	}
	
	strncpy(
		weather->location,
		json_string_value(json_object_get(subnode, "full")),
		sizeof(weather->location)
	);
	
	/* grab temperature */
	if(!(json_is_number(json_object_get(node, "temp_c")))) {
		fprintf(stderr, "[-] wunder/parse: cannot get temp_c\n");
		return 0;
	}
	
	if(json_is_real(json_object_get(node, "temp_c")))
		weather->temp = json_real_value(json_object_get(node, "temp_c"));
	
	else weather->temp = (double) json_integer_value(json_object_get(node, "temp_c"));
	
	/* grab humidity */
	if(!(json_string_value(json_object_get(node, "relative_humidity")))) {
		fprintf(stderr, "[-] wunder/parse: cannot get relative_humidity\n");
		return 0;
	}
	
	weather->humidity = atof(json_string_value(json_object_get(node, "relative_humidity")));
	
	/* grab date */
	if(!(json_string_value(json_object_get(node, "observation_time_rfc822")))) {
		fprintf(stderr, "[-] wunder/parse: cannot get observation_time_rfc822\n");
		return 0;
	}
	
	strncpy(
		weather->date,
		json_string_value(json_object_get(node, "observation_time_rfc822")),
		sizeof(weather->date)
	);
	
	return 1;
}
예제 #7
0
파일: json.c 프로젝트: hongiklee/json
long double json_number_get(json_t *json)
{
    if ( ! json_is_number(json))
        return 0;

    return ((json_number_t *)json)->value;
}
예제 #8
0
static int get_int_orelse(json_t* json, const char* key, int def) {
    json_t* v = json_object_get(json, key);
    if (v == NULL)
	return def;
    if (!json_is_number(v)) {
	stats_error_log("Expected an integer value for '%s' - using default of '%d'", key, def);
    }
    return (int)json_integer_value(v);
}
예제 #9
0
static void qtvlist_json_load_and_verify_string(const char *input)
{
	json_t *server_array = NULL;
	json_t *server_count = NULL;
	json_t *player_count = NULL;
	json_t *observ_count = NULL;
	json_error_t error;

	if (root != NULL) {
		json_decref(root);
		root = NULL;
	}

	root = json_loads(input, 0, &error);
	if (root == NULL) {
		Com_Printf("error: JSON error on line %d: %s\n", error.line, error.text);
		goto err;
	}

	if (!json_is_object(root)) {
		Com_Printf("error: invalid JSON, root is not an object\n");
		goto err;
	}

	server_array = json_object_get(root, "Servers");
	server_count = json_object_get(root, "ServerCount");
	player_count = json_object_get(root, "PlayerCount");
	observ_count = json_object_get(root, "ObserverCount");

	if (!json_is_array(server_array)  || !json_is_number(server_count) ||
	    !json_is_number(player_count) || !json_is_number(observ_count)) {
		Com_Printf("error: invalid JSON, unsupported format\n");
		goto err;
	}

	return;
err:
	if (root != NULL) {
		json_decref(root);
		root = NULL;
	}
}
예제 #10
0
파일: cfg.c 프로젝트: exponentjs/watchman
double cfg_get_double(w_root_t *root, const char *name, double defval) {
  json_t *val = cfg_get_json(root, name);

  if (val) {
    if (!json_is_number(val)) {
      w_log(W_LOG_FATAL, "Expected config value %s to be a number\n", name);
    }
    return json_real_value(val);
  }

  return defval;
}
예제 #11
0
파일: protocol5.c 프로젝트: toha/piswitch
/**
	json 2 protocol5
*/
int json_decode_protocol5 (protocol5* self, json_t* root) 
{
  json_error_t error;

	if (!root) {
		  fprintf(stderr, "error: on line %d: %s\n", error.line, error.text);
		  return 1;
	}

	if (!json_is_object(root)) {
		  fprintf(stderr, "error: root is not an object\n");
			json_decref(root);
			json_decref(root);
		  return 1;
	}

	json_t *network, *address, *broadcast, *state, *dimmer;

  network = json_object_get(root, "network");
  address = json_object_get(root, "address");
  broadcast = json_object_get(root, "broadcast");
  state = json_object_get(root, "state");
  dimmer = json_object_get(root, "dimmer");

  if(!json_is_number(network) || !json_is_number(address) || !json_is_number(broadcast) || 
		 !json_is_number(state) || !json_is_number(dimmer))
  {
      fprintf(stderr, "error: something is not a number\n");
      json_decref(root);
      return 1;
  }

	self->network = json_number_value(network);
	self->address = json_number_value(address);
	self->broadcast = json_number_value(broadcast);
	self->state = json_number_value(state);
	self->dimmer = json_number_value(dimmer);
	
	return 0;
} 
예제 #12
0
json_t* OBSAPIMessageHandler::HandleSetVolume(OBSAPIMessageHandler* handler, json_t* message)
{
    json_t* channel = json_object_get(message, "channel");
    json_t* volume = json_object_get(message, "volume");
    json_t* finalValue = json_object_get(message, "final");

    if(volume == NULL)
    {
        return GetErrorResponse("Volume not specified.");
    }

    if(!json_is_number(volume))
    {
        return GetErrorResponse("Volume not number.");
    }
    
    float val = (float) json_number_value(volume);
    val = min(1.0f, max(0.0f, val));

    if(finalValue == NULL)
    {
        return GetErrorResponse("Final not specified.");
    }
    
    if(!json_is_boolean(finalValue))
    {
        return GetErrorResponse("Final is not a boolean.");
    }

    if(channel != NULL && json_typeof(channel) == JSON_STRING)
    {
        const char* channelVal = json_string_value(channel);
        if(stricmp(channelVal, "desktop") == 0)
        {
            OBSSetDesktopVolume(val, json_is_true(finalValue));
        }
        else if(stricmp(channelVal, "microphone") == 0)
        {
            OBSSetMicVolume(val, json_is_true(finalValue));
        }
        else
        {
            return GetErrorResponse("Invalid channel specified.");
        }
    }
    else
    {
        return GetErrorResponse("Channel not specified.");
    }
    return GetOkResponse();
}
예제 #13
0
bool w_perf_finish(w_perf_t *perf) {
  gettimeofday(&perf->time_end, NULL);
  w_timeval_sub(perf->time_end, perf->time_begin, &perf->duration);
#ifdef HAVE_SYS_RESOURCE_H
  getrusage(RUSAGE_SELF, &perf->usage_end);

  // Compute the delta for the usage
  w_timeval_sub(perf->usage_end.ru_utime, perf->usage_begin.ru_utime,
                &perf->usage.ru_utime);
  w_timeval_sub(perf->usage_end.ru_stime, perf->usage_begin.ru_stime,
                &perf->usage.ru_stime);

#define DIFFU(n) perf->usage.n = perf->usage_end.n - perf->usage_begin.n
  DIFFU(ru_maxrss);
  DIFFU(ru_ixrss);
  DIFFU(ru_idrss);
  DIFFU(ru_minflt);
  DIFFU(ru_majflt);
  DIFFU(ru_nswap);
  DIFFU(ru_inblock);
  DIFFU(ru_oublock);
  DIFFU(ru_msgsnd);
  DIFFU(ru_msgrcv);
  DIFFU(ru_nsignals);
  DIFFU(ru_nvcsw);
  DIFFU(ru_nivcsw);
#undef DIFFU
#endif

  if (!perf->will_log) {
    if (perf->wall_time_elapsed_thresh == 0) {
      json_t *thresh = cfg_get_json(NULL, "perf_sampling_thresh");
      if (thresh) {
        if (json_is_number(thresh)) {
          perf->wall_time_elapsed_thresh = json_number_value(thresh);
        } else {
          json_unpack(thresh, "{s:f}", perf->description,
                    &perf->wall_time_elapsed_thresh);
        }
      }
    }

    if (perf->wall_time_elapsed_thresh > 0 &&
        w_timeval_diff(perf->time_begin, perf->time_end) >
            perf->wall_time_elapsed_thresh) {
      perf->will_log = true;
    }
  }

  return perf->will_log;
}
예제 #14
0
void BinWriter::writeType(json_t *jtype)
{
    TypeIndex *tindex = new TypeIndex;

    typeIndexes.push_back(tindex);

    tindex->position = bytes.getPosition();

    utString package = json_string_value(json_object_get(jtype, "package"));
    utString name    = json_string_value(json_object_get(jtype, "name"));

    utString fullname = package;
    fullname += ".";
    fullname += name;

    tindex->iFullName = poolString(fullname.c_str());

    int itype        = poolJString(json_object_get(jtype, "type"));
    int ipackagename = poolString(package.c_str());
    int iname        = poolString(name.c_str());

    json_t *jtypeid = json_object_get(jtype, "typeid");
    assert(jtypeid && json_is_number(jtypeid));

    int itypeid = (int)json_number_value(jtypeid);

    int isource     = -1;
    int ilinenumber = -1;

    json_t *jsource = json_object_get(jtype, "source");

    if (jsource && json_is_string(jsource))
    {
        isource     = poolString(json_string_value(jsource));
        ilinenumber = (int)json_integer_value(json_object_get(jtype, "line"));
    }

    bytes.writeInt(itype);
    bytes.writeInt(ipackagename);
    bytes.writeInt(iname);
    bytes.writeInt(itypeid);
    bytes.writeInt(isource);
    bytes.writeInt(ilinenumber);

    writeClass(jtype);

    tindex->length = bytes.getPosition() - tindex->position;
}
예제 #15
0
파일: json.cpp 프로젝트: Y-way/LoomSDK
double JSON::getArrayNumber(int index)
{
    if (!isArray())
    {
        return 0.f;
    }

    json_t *jobject = json_array_get(_json, index);

    if (!jobject || !json_is_number(jobject))
    {
        return 0.f;
    }

    return (double)json_number_value(jobject);
}
예제 #16
0
파일: perf.cpp 프로젝트: danez/watchman
bool watchman_perf_sample::finish() {
  gettimeofday(&time_end, nullptr);
  w_timeval_sub(time_end, time_begin, &duration);
#ifdef HAVE_SYS_RESOURCE_H
  getrusage(RUSAGE_SELF, &usage_end);

  // Compute the delta for the usage
  w_timeval_sub(usage_end.ru_utime, usage_begin.ru_utime, &usage.ru_utime);
  w_timeval_sub(usage_end.ru_stime, usage_begin.ru_stime, &usage.ru_stime);

#define DIFFU(n) usage.n = usage_end.n - usage_begin.n
  DIFFU(ru_maxrss);
  DIFFU(ru_ixrss);
  DIFFU(ru_idrss);
  DIFFU(ru_minflt);
  DIFFU(ru_majflt);
  DIFFU(ru_nswap);
  DIFFU(ru_inblock);
  DIFFU(ru_oublock);
  DIFFU(ru_msgsnd);
  DIFFU(ru_msgrcv);
  DIFFU(ru_nsignals);
  DIFFU(ru_nvcsw);
  DIFFU(ru_nivcsw);
#undef DIFFU
#endif

  if (!will_log) {
    if (wall_time_elapsed_thresh == 0) {
      auto thresh = cfg_get_json("perf_sampling_thresh");
      if (thresh) {
        if (json_is_number(thresh)) {
          wall_time_elapsed_thresh = json_number_value(thresh);
        } else {
          json_unpack(thresh, "{s:f}", description, &wall_time_elapsed_thresh);
        }
      }
    }

    if (wall_time_elapsed_thresh > 0 &&
        w_timeval_diff(time_begin, time_end) > wall_time_elapsed_thresh) {
      will_log = true;
    }
  }

  return will_log;
}
예제 #17
0
파일: var.c 프로젝트: punarinta/bombyx
map_table_t *json_to_map(bombyx_env_t *env, json_t *json)
{
    size_t index;
    json_t *value;
    const char *key;
    map_table_t *map;

    // TODO: minimum map size (100?)

    if (json_is_object(json))
    {
        map = map_table_create(json_object_size(json));
        json_object_foreach(json, key, value)
        {
            var v = {0};
            if (json_is_object(value))
            {
                // process recursively
                v.type = VAR_MAP;
                v.data = json_to_map(env, value);
                v.data_size = sizeof(map_table_t);
            }
            else if (json_is_array(value))
            {
                v.type = VAR_ARRAY;
                v.data = json_to_array(env, value);
                v.data_size = sizeof(array_t);
            }
            else if (json_is_string(value))
            {
                v.type = VAR_STRING;
                v.data = strdup(json_string_value(value));
                v.data_size = json_string_length(value) + 1;
            }
            else if (json_is_number(value))
            {
                v.type = VAR_DOUBLE;
                v.data = challoc(env->pool_of_doubles);
                v.data_size = sizeof(double);
                *(double *)v.data = json_number_value(value);
            }
            map_add(env, map, (char *)key, v);
        }
    }
예제 #18
0
파일: build.c 프로젝트: IlariaD/ssm
ssm_var_t *ssm_var_new(json_t *jparameters, ssm_nav_t *nav)
{
    gsl_matrix *m = gsl_matrix_calloc(nav->theta_all->length, nav->theta_all->length);


    int i,j, index;
    ssm_it_parameters_t *it = nav->theta_all;
    json_t *jresource = json_object_get(jparameters, "resources");

    for(index=0; index< json_array_size(jresource); index++){
        json_t *el = json_array_get(jresource, index);

        const char* name = json_string_value(json_object_get(el, "name"));
        if (strcmp(name, "covariance") == 0) {

            json_t *values = json_object_get(el, "data");

            for(i=0; i<it->length; i++){
                for(j=0; j<it->length; j++){
                    json_t *jcov_i = json_object_get(values, it->p[i]->name);
                    if(jcov_i){
                        json_t *jcov_ij = json_object_get(jcov_i, it->p[j]->name);
                        if(jcov_ij){
                            if(json_is_number(jcov_ij)) {
                                gsl_matrix_set(m, i, j, json_number_value(jcov_ij));
                            } else {
                                char str[SSM_STR_BUFFSIZE];
                                snprintf(str, SSM_STR_BUFFSIZE, "error: parameters.covariance.%s.%s is not a number\n", it->p[i]->name, it->p[j]->name);
                                ssm_print_err(str);
                                exit(EXIT_FAILURE);
                            }
                        }
                    }
                }
            }

            break;
        }
    }

    return m;
}
예제 #19
0
void Stimulus3DShaderDemo::receive_json_message(const std::string& topic_name,
                                                const std::string& json_message) {
    json_t *root;
    json_error_t error;

    root = json_loads(json_message.c_str(), 0, &error);
    if(!root) {
        throw std::runtime_error("error in json");
    }

    json_t *data_json = json_object_get(root, "data");
    if (data_json==NULL) {
        throw std::runtime_error("key not in JSON");
    }
    if(!json_is_number(data_json)){
        throw std::runtime_error("error in json");
    }
    _example_param = json_number_value( data_json );
    example_param_uniform->set(_example_param);

}
예제 #20
0
/**
 * Parse a signed integer
 *
 * If the key does not exist in the src object, returns success but does fill in *dest.
 *
 * @param src JSON object to pull a value from
 * @param key key to pull
 * @param dest (output) pointer to an allocated integer
 * @return TR_CFG_SUCCESS or an error code
 */
static TR_CFG_RC tr_cfg_parse_integer(json_t *src, const char *key, int *dest)
{
  json_t *jtmp;

  /* Validate parameters */
  if ((src == NULL) || (key == NULL) || (dest == NULL))
    return TR_CFG_BAD_PARAMS;

  /* See if we have a value for this key; do nothing if not */
  jtmp = json_object_get(src, key);
  if (jtmp) {
    if (json_is_number(jtmp)) {
      *dest = (int) json_integer_value(jtmp);
    } else {
      tr_debug("tr_cfg_parse_unsigned: Parsing error, %s is not a number.", key);
      return TR_CFG_NOPARSE;
    }
  }

  return TR_CFG_SUCCESS;
}
예제 #21
0
/*
 * parse (optional) timestamp from payload
 */
static apr_byte_t oidc_jose_get_timestamp(apr_pool_t *pool, json_t *json,
		const char *claim_name, apr_byte_t is_mandatory, double *result,
		oidc_jose_error_t *err) {
	*result = OIDC_JWT_CLAIM_TIME_EMPTY;
	json_t *v = json_object_get(json, claim_name);
	if (v != NULL) {
		if (json_is_number(v)) {
			*result = json_number_value(v);
		} else if (is_mandatory) {
			oidc_jose_error(err,
					"mandatory JSON key \"%s\" was found but the type is not a number",
					claim_name);
			return FALSE;
		}
	} else if (is_mandatory) {
		oidc_jose_error(err, "mandatory JSON key \"%s\" could not be found",
				claim_name);
		return FALSE;
	}
	return TRUE;
}
예제 #22
0
int schema_traverse(const avro_schema_t schema, json_t *json, json_t *dft,
                    avro_value_t *current_val, int quiet, int strjson, size_t max_str_sz) {

    json = json ? json : dft;
    if (!json) {
        fprintf(stderr, "ERROR: Avro schema does not match JSON\n");
        return 1;
    }

    switch (schema->type) {
    case AVRO_RECORD:
    {
        if (!json_is_object(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON object for Avro record, got something else\n");
            return 1;
        }

        int len = avro_schema_record_size(schema), i;
        for (i=0; i<len; i++) {

            const char *name = avro_schema_record_field_name(schema, i);
            avro_schema_t field_schema = avro_schema_record_field_get_by_index(schema, i);

            json_t *json_val = json_object_get(json, name);
            json_t *dft = avro_schema_record_field_default_get_by_index(schema, i);

            avro_value_t field;
            avro_value_get_by_index(current_val, i, &field, NULL);

            if (schema_traverse(field_schema, json_val, dft, &field, quiet, strjson, max_str_sz))
                return 1;
        }
    } break;

    case AVRO_LINK:
        /* TODO */
        fprintf(stderr, "ERROR: AVRO_LINK is not implemented\n");
        return 1;
        break;

    case AVRO_STRING:
        if (!json_is_string(json)) {
            if (json && strjson) {
                /* -j specified, just dump the remaining json as string */
                char * js = json_dumps(json, JSON_COMPACT|JSON_SORT_KEYS|JSON_ENCODE_ANY);
                if (max_str_sz && (strlen(js) > max_str_sz))
                    js[max_str_sz] = 0; /* truncate the string - this will result in invalid JSON! */
                avro_value_set_string(current_val, js);
                free(js);
                break;
            }
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON string for Avro string, got something else\n");
            return 1;
        } else {
            const char *js = json_string_value(json);
            if (max_str_sz && (strlen(js) > max_str_sz)) {
                /* truncate the string */
                char *jst = malloc(strlen(js));
                strcpy(jst, js);
                jst[max_str_sz] = 0;
                avro_value_set_string(current_val, jst);
                free(jst);
            } else
                avro_value_set_string(current_val, js);
        }
        break;

    case AVRO_BYTES:
        if (!json_is_string(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON string for Avro string, got something else\n");
            return 1;
        }
        /* NB: Jansson uses null-terminated strings, so embedded nulls are NOT
           supported, not even escaped ones */
        const char *s = json_string_value(json);
        avro_value_set_bytes(current_val, (void *)s, strlen(s));
        break;

    case AVRO_INT32:
        if (!json_is_integer(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON integer for Avro int, got something else\n");
            return 1;
        }
        avro_value_set_int(current_val, json_integer_value(json));
        break;

    case AVRO_INT64:
        if (!json_is_integer(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON integer for Avro long, got something else\n");
            return 1;
        }
        avro_value_set_long(current_val, json_integer_value(json));
        break;

    case AVRO_FLOAT:
        if (!json_is_number(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON number for Avro float, got something else\n");
            return 1;
        }
        avro_value_set_float(current_val, json_number_value(json));
        break;

    case AVRO_DOUBLE:
        if (!json_is_number(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON number for Avro double, got something else\n");
            return 1;
        }
        avro_value_set_double(current_val, json_number_value(json));
        break;

    case AVRO_BOOLEAN:
        if (!json_is_boolean(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON boolean for Avro boolean, got something else\n");
            return 1;
        }
        avro_value_set_boolean(current_val, json_is_true(json));
        break;

    case AVRO_NULL:
        if (!json_is_null(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON null for Avro null, got something else\n");
            return 1;
        }
        avro_value_set_null(current_val);
        break;

    case AVRO_ENUM:
        // TODO ???
        break;

    case AVRO_ARRAY:
        if (!json_is_array(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON array for Avro array, got something else\n");
            return 1;
        } else {
            int i, len = json_array_size(json);
            avro_schema_t items = avro_schema_array_items(schema);
            avro_value_t val;
            for (i=0; i<len; i++) {
                avro_value_append(current_val, &val, NULL);
                if (schema_traverse(items, json_array_get(json, i), NULL, &val, quiet, strjson, max_str_sz))
                    return 1;
            }
        }
        break;

    case AVRO_MAP:
        if (!json_is_object(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON object for Avro map, got something else\n");
            return 1;
        } else {
            avro_schema_t values = avro_schema_map_values(schema);
            void *iter = json_object_iter(json);
            avro_value_t val;
            while (iter) {
                avro_value_add(current_val, json_object_iter_key(iter), &val, 0, 0);
                if (schema_traverse(values, json_object_iter_value(iter), NULL, &val, quiet, strjson, max_str_sz))
                    return 1;
                iter = json_object_iter_next(json, iter);
            }
        }
        break;

    case AVRO_UNION:
    {
        int i;
        avro_value_t branch;
        for (i=0; i<avro_schema_union_size(schema); i++) {
            avro_value_set_branch(current_val, i, &branch);
            avro_schema_t type = avro_schema_union_branch(schema, i);
            if (!schema_traverse(type, json, NULL, &branch, 1, strjson, max_str_sz))
                break;
        }
        if (i==avro_schema_union_size(schema)) {
            fprintf(stderr, "ERROR: No type in the Avro union matched the JSON type we got\n");
            return 1;
        }
        break;
    }
    case AVRO_FIXED:
        if (!json_is_string(json)) {
            if (!quiet)
                fprintf(stderr, "ERROR: Expecting JSON string for Avro fixed, got something else\n");
            return 1;
        }
        /* NB: Jansson uses null-terminated strings, so embedded nulls are NOT
           supported, not even escaped ones */
        const char *f = json_string_value(json);
        if (avro_value_set_fixed(current_val, (void *)f, strlen(f))) {
            fprintf(stderr, "ERROR: Setting Avro fixed value FAILED\n");
            return 1;
        }
        break;

    default:
        fprintf(stderr, "ERROR: Unknown type: %d\n", schema->type);
        return 1;
    }
    return 0;
}
예제 #23
0
파일: JSON.cpp 프로젝트: kibae/defer.io
bool Json::isNumber() const
{
	return json_is_number( data );
}
예제 #24
0
파일: tickets.c 프로젝트: toha/DCAF
int json2ticket(json_t *j, struct dcaf_ticket *t) {
  if (!json_is_object(j)) {
    printf("a1\n");
    return 1;
  }

  json_t *j_id = json_object_get(j, "id");
  json_t *j_face = json_object_get(j, "face");
  json_t *j_verifier = json_object_get(j, "verifier");
  json_t *j_verifier_size = json_object_get(j, "verifier_size");

  if (!j_id || !j_face || !j_verifier || !j_verifier_size ||
      !json_is_string(j_id) || !json_is_object(j_face) ||
      !json_is_string(j_verifier) || !json_is_number(j_verifier_size)) {
    return 2;
  }

  t->id = json_string_value(j_id);
  t->verifier_size = json_integer_value(j_verifier_size);

  char *verifier_b64 = json_string_value(j_verifier);
  size_t verifier_size = 0;
  unsigned char *verifier_str =
      base64_decode(verifier_b64, strlen(verifier_b64), &verifier_size);
  memcpy(t->verifier, verifier_str, t->verifier_size);
  // base64_cleanup(); muss raus, sonst funzt das nächste base64 nicht
  free(verifier_str);
  // free(verifier_b64);

  json_t *j_face_ai = json_object_get(j_face, "AI");

  json_t *j_face_seq_nr = json_object_get(j_face, "sequence_number");
  json_t *j_face_timestamp = json_object_get(j_face, "timestamp");
  json_t *j_face_lifetime = json_object_get(j_face, "lifetime");
  json_t *j_face_dtls_psk_gen_method =
      json_object_get(j_face, "dtls_psk_gen_method");
  json_t *j_conditions = json_object_get(j_face, "conditions");

  if (!j_face_ai || !j_face_seq_nr || !j_face_timestamp || !j_face_lifetime ||
      !j_face_dtls_psk_gen_method || !j_conditions ||
      !json_is_array(j_face_ai) || !json_is_number(j_face_seq_nr) ||
      !json_is_number(j_face_timestamp) || !json_is_number(j_face_lifetime) ||
      !json_is_number(j_face_dtls_psk_gen_method) ||
      !json_is_array(j_conditions)) {
    return 3;
  }

  t->face.sequence_number = json_integer_value(j_face_seq_nr);
  t->face.timestamp = json_integer_value(j_face_timestamp);
  t->face.lifetime = json_integer_value(j_face_lifetime);
  t->face.dtls_psk_gen_method = json_integer_value(j_face_dtls_psk_gen_method);

  size_t index;
  json_t *j_face_ai_el;
  json_array_foreach(j_face_ai, index, j_face_ai_el) {
    json_t *j_face_ai_rs = json_object_get(j_face_ai_el, "rs");
    json_t *j_face_ai_resource = json_object_get(j_face_ai_el, "resource");
    json_t *j_face_ai_methods = json_object_get(j_face_ai_el, "methods");

    if (!j_face_ai_rs || !j_face_ai_resource || !j_face_ai_methods ||
        !json_is_string(j_face_ai_rs) || !json_is_string(j_face_ai_resource) ||
        !json_is_number(j_face_ai_methods)) {
      return 4;
    }

    t->face.AIs[index].rs = json_string_value(j_face_ai_rs);
    t->face.AIs[index].resource = json_string_value(j_face_ai_resource);
    t->face.AIs[index].methods = json_integer_value(j_face_ai_methods);
  }
예제 #25
0
파일: build.c 프로젝트: IlariaD/ssm
/**
 * in case of simulation extend data or reset n_obs to take into
 * account opts->end ISO 8601 date
 */
void ssm_data_adapt_to_simul(ssm_data_t *data, json_t *jdata, ssm_nav_t *nav, ssm_options_t *opts)
{
    int i, n;

    if(strcmp("", opts->end)==0){
        return;
    }

    struct tm tm_start_date_t0;
    memset(&tm_start_date_t0, 0, sizeof(struct tm));

    strptime(data->date_t0, "%Y-%m-%d", &tm_start_date_t0);
    time_t t_start_date_t0 = timegm(&tm_start_date_t0);

    struct tm tm_end;
    memset(&tm_end, 0, sizeof(struct tm));
    strptime(opts->end, "%Y-%m-%d", &tm_end);
    time_t t_end = timegm(&tm_end);

    double delta_date_t0 = difftime(t_end, t_start_date_t0)/(24.0*60.0*60.0);
    if(delta_date_t0 < 0.0){
	ssm_print_err("end date is before t0");
	exit(EXIT_FAILURE);
    }

    unsigned int time_start;
    struct tm tm_start;
    memset(&tm_start, 0, sizeof(struct tm));
    time_t t_start;
    if(data->length){
        strptime(data->rows[data->length-1]->date, "%Y-%m-%d", &tm_start);
        time_start = data->rows[data->length-1]->time;
	t_start = timegm(&tm_start);
    } else {
        t_start = t_start_date_t0;
    }

    double delta = difftime(t_end, t_start)/(24.0*60.0*60.0);
    if(delta < 0.0){

	//there are data but t_end before the last data point. In this case we just adjuts n_obs and n_obs_nonan
	if(data->length){
	    data->n_obs = 0;
	    data->n_obs_nonan = 0;

	    while(data->rows[data->n_obs]->time <= delta_date_t0){
		if(data->rows[data->n_obs]->ts_nonan_length){
		    data->n_obs_nonan += 1;
		}
		data->n_obs += 1;
	    }
	    
	    //safety
	    data->n_obs = GSL_MIN(data->n_obs, data->length);
	    data->n_obs_nonan = GSL_MIN(data->n_obs, data->n_obs_nonan);

	    return;
	}

        ssm_print_err("end date is before t0");
        exit(EXIT_FAILURE);
    }

    int n_extra = (int) ceil(delta / (double) opts->freq);
    if(n_extra){
        int offset = data->length;
        data->length +=  n_extra;
        data->n_obs += n_extra;

        ssm_row_t **rows = realloc(data->rows, data->length * sizeof (ssm_row_t *));
        if (rows!=NULL) {
            data->rows = rows;
        } else {
            ssm_print_err("could not re-allocate memory for ssm_data_t rows");
            exit(EXIT_FAILURE);
        }

        time_t t = t_start;
        char iso_8601[] = "YYYY-MM-DD";
        double one_day_in_sec = 24.0*60.0*60.0;
        int inc = opts->freq * 24*60*60;
	json_t *jreset_all = json_object_get(jdata, "reset_all");
	int states_reset_length = json_array_size(jreset_all);

        for(n=0; n<n_extra; n++){
            ssm_row_t *row = malloc(sizeof (ssm_row_t));
            if (row == NULL) {
                ssm_print_err("Allocation impossible for ssm_data_row_t *");
                exit(EXIT_FAILURE);
            }

            t += inc;
            struct tm *tm;
            tm = gmtime(&t);

            strftime(iso_8601, sizeof(iso_8601), "%Y-%m-%d", tm);
            row->date = strdup(iso_8601);
            row->time = time_start + (unsigned int) difftime(t, t_start)/one_day_in_sec;
            row->ts_nonan_length = 0;


            row->states_reset_length = states_reset_length;
            row->states_reset = malloc(states_reset_length * sizeof (ssm_state_t *));
            if (row->states_reset == NULL) {
                ssm_print_err("Allocation impossible for ssm_data_row_t.states_reset");
                exit(EXIT_FAILURE);
            }
	    for(i=0; i<row->states_reset_length; i++){
		json_t *jreset_all_i = json_array_get(jreset_all, i);
		if(json_is_number(jreset_all_i)) {
		    int id = json_integer_value(jreset_all_i);
		    row->states_reset[i] = nav->states[id];
		} else {
		    char str[SSM_STR_BUFFSIZE];
		    snprintf(str, SSM_STR_BUFFSIZE, "error: reset_all[%d] is not an integer\n", i);
		    ssm_print_err(str);
		    exit(EXIT_FAILURE);
		}
	    }
	    
            row->values = NULL;
            data->rows[offset+n] = row;
        }
    }
}
예제 #26
0
파일: build.c 프로젝트: IlariaD/ssm
ssm_data_t *ssm_data_new(json_t *jdata, ssm_nav_t *nav, ssm_options_t *opts)
{
    char str[SSM_STR_BUFFSIZE];
    int i, j;

    ssm_data_t *data = malloc(sizeof (ssm_data_t));
    if (data==NULL) {
        ssm_print_err("Allocation impossible for ssm_data_t");
        exit(EXIT_FAILURE);
    }

    json_t *jstart = json_object_get(jdata, "start");
    if(json_is_string(jstart)) {
        data->date_t0 = strdup(json_string_value(jstart));
    } else {
        ssm_print_err("data start is not a string");
        exit(EXIT_FAILURE);
    }


    json_t *jdata_data = json_object_get(jdata, "data");

    data->length = json_array_size(jdata_data);
    data->ts_length = nav->observed_length;

    //n_obs
    if(opts->n_obs >= 0){
        data->n_obs = (opts->n_obs < data->length) ? opts->n_obs : data->length;
    } else {
        data->n_obs = data->length;
    }

    ssm_row_t **rows = malloc(data->length * sizeof (ssm_row_t *));
    if (rows==NULL) {
        ssm_print_err("Allocation impossible for ssm_data_row_t **");
        exit(EXIT_FAILURE);
    }

    data->length_nonan = 0;
    data->n_obs_nonan = 0;
    data->ind_nonan = ssm_u1_new(data->length);

    for (i=0; i< data->length; i++){
        rows[i] = malloc(sizeof (ssm_row_t));
        if (rows[i] == NULL) {
            ssm_print_err("Allocation impossible for ssm_data_row_t *");
            exit(EXIT_FAILURE);
        }

        json_t *jrow = json_array_get(jdata_data, i);

        json_t *jdate = json_object_get(jrow, "date");
        if(json_is_string(jdate)) {
            rows[i]->date = strdup(json_string_value(jdate));
        } else {
            snprintf(str, SSM_STR_BUFFSIZE, "error: data[%d].date is not a string\n", i);
            ssm_print_err(str);
            exit(EXIT_FAILURE);
        }

        json_t *jtime = json_object_get(jrow, "time");
        if(json_is_number(jtime)) {
            rows[i]->time = (unsigned int) json_integer_value(jtime);
        } else {
            snprintf(str, SSM_STR_BUFFSIZE, "error: data[%d].time is not an integer\n", i);
            ssm_print_err(str);
            exit(EXIT_FAILURE);
        }

        json_t *jobserved = json_object_get(jrow, "observed");
        rows[i]->ts_nonan_length = json_array_size(jobserved);

        if(rows[i]->ts_nonan_length){
            rows[i]->observed = malloc(rows[i]->ts_nonan_length * sizeof (ssm_observed_t *));
            if (rows[i]->observed == NULL) {
                ssm_print_err("Allocation impossible for ssm_data_row_t.observed");
                exit(EXIT_FAILURE);
            }

            for(j=0; j<rows[i]->ts_nonan_length; j++){
                json_t *jobserved_j = json_array_get(jobserved, j);
                if(json_is_number(jobserved_j)) {
                    int id = json_integer_value(jobserved_j);
                    rows[i]->observed[j] = nav->observed[id];
                } else {
                    snprintf(str, SSM_STR_BUFFSIZE, "error: data[%d].observed[%d] is not an integer\n", i, j);
                    ssm_print_err(str);
                    exit(EXIT_FAILURE);
                }
            }
        }

        rows[i]->values = ssm_load_jd1_new(jrow, "values");

        json_t *jreset = json_object_get(jrow, "reset");
        rows[i]->states_reset_length = json_array_size(jreset);

        if(rows[i]->states_reset_length){
            rows[i]->states_reset = malloc(rows[i]->states_reset_length * sizeof (ssm_state_t *));
            if (rows[i]->states_reset == NULL) {
                ssm_print_err("Allocation impossible for ssm_data_row_t.states_reset");
                exit(EXIT_FAILURE);
            }
        }

        for(j=0; j<rows[i]->states_reset_length; j++){
            json_t *jreset_j = json_array_get(jreset, j);
            if(json_is_number(jreset_j)) {
                int id = json_integer_value(jreset_j);
                rows[i]->states_reset[j] = nav->states[id];
            } else {
                snprintf(str, SSM_STR_BUFFSIZE, "error: data[%d].reset[%d] is not an integer\n", i, j);
                ssm_print_err(str);
                exit(EXIT_FAILURE);
            }
        }

        if(rows[i]->ts_nonan_length){
            data->ind_nonan[data->length_nonan] = i;
            data->length_nonan += 1;
            if(i< data->n_obs){
                data->n_obs_nonan += 1;
            }
        }
    }

    data->rows = rows;


    ssm_data_adapt_to_simul(data, jdata, nav, opts);

    return data;
}
예제 #27
0
파일: JValue.hpp 프로젝트: iSLC/VCMP-SqMod
 /* --------------------------------------------------------------------------------------------
  * See whether the managed value is number.
 */
 bool IsNumber() const
 {
     return json_is_number(m_Ptr);
 }
예제 #28
0
/*
 * resolve and validate an access_token against the configured Authorization Server
 */
static apr_byte_t oidc_oauth_resolve_access_token(request_rec *r, oidc_cfg *c,
		const char *access_token, json_t **token, char **response) {

	json_t *result = NULL;
	const char *json = NULL;

	/* see if we've got the claims for this access_token cached already */
	c->cache->get(r, OIDC_CACHE_SECTION_ACCESS_TOKEN, access_token, &json);

	if (json == NULL) {

		/* not cached, go out and validate the access_token against the Authorization server and get the JSON claims back */
		if (oidc_oauth_validate_access_token(r, c, access_token, &json) == FALSE) {
			oidc_error(r,
					"could not get a validation response from the Authorization server");
			return FALSE;
		}

		/* decode and see if it is not an error response somehow */
		if (oidc_util_decode_json_and_check_error(r, json, &result) == FALSE)
			return FALSE;

		json_t *active = json_object_get(result, "active");
		if (active != NULL) {

			if ((!json_is_boolean(active)) || (!json_is_true(active))) {
				oidc_debug(r,
						"no \"active\" boolean object with value \"true\" found in response JSON object");
				json_decref(result);
				return FALSE;
			}

			json_t *exp = json_object_get(result, "exp");
			if ((exp != NULL) && (json_is_number(exp))) {
				/* set it in the cache so subsequent request don't need to validate the access_token and get the claims anymore */
				c->cache->set(r, OIDC_CACHE_SECTION_ACCESS_TOKEN, access_token, json,
						apr_time_from_sec(json_integer_value(exp)));
			} else if (json_integer_value(exp) <= 0) {
				oidc_debug(r,
						"response JSON object did not contain an \"exp\" integer number; introspection result will not be cached");
			}

		} else {

			/* assume PingFederate validation: get and check the expiry timestamp */
			json_t *expires_in = json_object_get(result, "expires_in");
			if ((expires_in == NULL) || (!json_is_number(expires_in))) {
				oidc_error(r,
						"response JSON object did not contain an \"expires_in\" number");
				json_decref(result);
				return FALSE;
			}
			if (json_integer_value(expires_in) <= 0) {
				oidc_warn(r,
						"\"expires_in\" number <= 0 (%" JSON_INTEGER_FORMAT "); token already expired...",
						json_integer_value(expires_in));
				json_decref(result);
				return FALSE;
			}

			/* set it in the cache so subsequent request don't need to validate the access_token and get the claims anymore */
			c->cache->set(r, OIDC_CACHE_SECTION_ACCESS_TOKEN, access_token, json,
					apr_time_now() + apr_time_from_sec(json_integer_value(expires_in)));
		}


	} else {

		/* we got the claims for this access_token in our cache, decode it in to a JSON structure */
		json_error_t json_error;
		result = json_loads(json, 0, &json_error);
		if (result == NULL) {
			oidc_error(r, "cached JSON was corrupted: %s", json_error.text);
			return FALSE;
		}
	}

	/* return the access_token JSON object */
	json_t *tkn = json_object_get(result, "access_token");
	if ((tkn != NULL) && (json_is_object(tkn))) {

		/*
		 * assume PingFederate validation: copy over those claims from the access_token
		 * that are relevant for authorization purposes
		 */
		json_object_set(tkn, "client_id", json_object_get(result, "client_id"));
		json_object_set(tkn, "scope", json_object_get(result, "scope"));

		//oidc_oauth_spaced_string_to_array(r, result, "scope", tkn, "scopes");

		/* return only the pimped access_token results */
		*token = json_deep_copy(tkn);
		char *s_token = json_dumps(*token, 0);
		*response = apr_pstrdup(r->pool, s_token);
		free(s_token);

		json_decref(result);

	} else  {

		//oidc_oauth_spaced_string_to_array(r, result, "scope", result, "scopes");

		/* assume spec compliant introspection */
		*token = result;
		*response = apr_pstrdup(r->pool, json);

	}

	return TRUE;
}
예제 #29
0
/* Call the simple functions not covered by other tests of the public API */
int main()
{
    json_t *value;

    value = json_integer(1);
    if(json_typeof(value) != JSON_INTEGER)
        fail("json_typeof failed");

    if(json_is_object(value))
        fail("json_is_object failed");

    if(json_is_array(value))
        fail("json_is_array failed");

    if(json_is_string(value))
        fail("json_is_string failed");

    if(!json_is_integer(value))
        fail("json_is_integer failed");

    if(json_is_real(value))
        fail("json_is_real failed");

    if(!json_is_number(value))
        fail("json_is_number failed");

    if(json_is_true(value))
        fail("json_is_true failed");

    if(json_is_false(value))
        fail("json_is_false failed");

    if(json_is_boolean(value))
        fail("json_is_boolean failed");

    if(json_is_null(value))
        fail("json_is_null failed");

    json_decref(value);


    value = json_string("foo");
    if(!value)
        fail("json_string failed");
    if(strcmp(json_string_value(value), "foo"))
        fail("invalid string value");

    if(json_string_set(value, "bar"))
        fail("json_string_set failed");
    if(strcmp(json_string_value(value), "bar"))
        fail("invalid string value");

    json_decref(value);

    value = json_string(NULL);
    if(value)
        fail("json_string(NULL) failed");

    /* invalid UTF-8  */
    value = json_string("a\xefz");
    if(value)
        fail("json_string(<invalid utf-8>) failed");

    value = json_string_nocheck("foo");
    if(!value)
        fail("json_string_nocheck failed");
    if(strcmp(json_string_value(value), "foo"))
        fail("invalid string value");

    if(json_string_set_nocheck(value, "bar"))
        fail("json_string_set_nocheck failed");
    if(strcmp(json_string_value(value), "bar"))
        fail("invalid string value");

    json_decref(value);

    /* invalid UTF-8 */
    value = json_string_nocheck("qu\xff");
    if(!value)
        fail("json_string_nocheck failed");
    if(strcmp(json_string_value(value), "qu\xff"))
        fail("invalid string value");

    if(json_string_set_nocheck(value, "\xfd\xfe\xff"))
        fail("json_string_set_nocheck failed");
    if(strcmp(json_string_value(value), "\xfd\xfe\xff"))
        fail("invalid string value");

    json_decref(value);


    value = json_integer(123);
    if(!value)
        fail("json_integer failed");
    if(json_integer_value(value) != 123)
        fail("invalid integer value");
    if(json_number_value(value) != 123.0)
        fail("invalid number value");

    if(json_integer_set(value, 321))
        fail("json_integer_set failed");
    if(json_integer_value(value) != 321)
        fail("invalid integer value");
    if(json_number_value(value) != 321.0)
        fail("invalid number value");

    json_decref(value);

    value = json_real(123.123);
    if(!value)
        fail("json_real failed");
    if(json_real_value(value) != 123.123)
        fail("invalid integer value");
    if(json_number_value(value) != 123.123)
        fail("invalid number value");

    if(json_real_set(value, 321.321))
        fail("json_real_set failed");
    if(json_real_value(value) != 321.321)
        fail("invalid real value");
    if(json_number_value(value) != 321.321)
        fail("invalid number value");

    json_decref(value);

    value = json_true();
    if(!value)
        fail("json_true failed");
    json_decref(value);

    value = json_false();
    if(!value)
        fail("json_false failed");
    json_decref(value);

    value = json_null();
    if(!value)
        fail("json_null failed");
    json_decref(value);

    /* Test reference counting on singletons (true, false, null) */
    value = json_true();
    if(value->refcount != (size_t)-1)
      fail("refcounting true works incorrectly");
    json_decref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting true works incorrectly");
    json_incref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting true works incorrectly");

    value = json_false();
    if(value->refcount != (size_t)-1)
      fail("refcounting false works incorrectly");
    json_decref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting false works incorrectly");
    json_incref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting false works incorrectly");

    value = json_null();
    if(value->refcount != (size_t)-1)
      fail("refcounting null works incorrectly");
    json_decref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting null works incorrectly");
    json_incref(value);
    if(value->refcount != (size_t)-1)
      fail("refcounting null works incorrectly");

    return 0;
}
예제 #30
0
파일: build.c 프로젝트: IlariaD/ssm
ssm_nav_t *ssm_nav_new(json_t *jparameters, ssm_options_t *opts)
{
    char str[SSM_STR_BUFFSIZE];

    ssm_nav_t *nav = malloc(sizeof (ssm_nav_t));
    if (nav == NULL) {
        ssm_print_err("Allocation impossible for ssm_nav_t *");
        exit(EXIT_FAILURE);
    }

    nav->implementation = opts->implementation;
    nav->noises_off = opts->noises_off;
    nav->print = opts->print;

    nav->parameters = _ssm_parameters_new(&nav->parameters_length);
    nav->states = _ssm_states_new(&nav->states_length, nav->parameters);
    nav->observed = _ssm_observed_new(&nav->observed_length);

    nav->states_sv = ssm_it_states_sv_new(nav->states);
    nav->states_remainders = ssm_it_states_remainders_new(nav->states);
    nav->states_inc = ssm_it_states_inc_new(nav->states);
    nav->states_sv_inc = ssm_it_states_sv_inc_new(nav->states);
    nav->states_diff = ssm_it_states_diff_new(nav->states);

    nav->par_all = ssm_it_parameters_all_new(nav->parameters);
    nav->par_noise = ssm_it_parameters_noise_new(nav->parameters);
    nav->par_disp = ssm_it_parameters_disp_new(nav->parameters);
    nav->par_icsv = ssm_it_parameters_icsv_new(nav->parameters);
    nav->par_icdiff = ssm_it_parameters_icdiff_new(nav->parameters);

    //theta: we over-allocate the iterators
    nav->theta_all = _ssm_it_parameters_new(nav->par_all->length);
    nav->theta_no_icsv_no_icdiff = _ssm_it_parameters_new(nav->par_all->length);
    nav->theta_icsv_icdiff = _ssm_it_parameters_new(nav->par_all->length);

    //json_t jparameters with diagonal covariance term to 0.0 won't be infered: re-compute length and content
    nav->theta_all->length = 0;
    nav->theta_no_icsv_no_icdiff->length = 0;
    nav->theta_icsv_icdiff->length = 0;


    int index, i;
    json_t *jresource = json_object_get(jparameters, "resources");

    for(index=0; index< json_array_size(jresource); index++){
        json_t *el = json_array_get(jresource, index);

        const char *name = json_string_value(json_object_get(el, "name"));
        if (strcmp(name, "covariance") == 0) {

            json_t *values = json_object_get(el, "data");

            //for all the parameters: if covariance term and covariance term >0.0, fill theta_*
            for(i=0; i<nav->par_all->length; i++){
		json_t *jcov_i = json_object_get(values, nav->par_all->p[i]->name);
                if(jcov_i){
                    json_t *jcov_ii = json_object_get(jcov_i, nav->par_all->p[i]->name);
                    if(jcov_ii){
                        if(!json_is_number(jcov_ii)) {
                            snprintf(str, SSM_STR_BUFFSIZE, "error: parameters.covariance.%s.%s is not a number\n", nav->par_all->p[i]->name, nav->par_all->p[i]->name);
                            ssm_print_err(str);
                            exit(EXIT_FAILURE);
                        }

                        if(json_number_value(jcov_ii) > 0.0){

                            if( ssm_in_par(nav->par_noise, nav->par_all->p[i]->name) ) {
                                if(!(nav->noises_off & SSM_NO_WHITE_NOISE)){
                                    nav->theta_all->p[nav->theta_all->length] = nav->par_all->p[i];
                                    nav->theta_all->p[nav->theta_all->length]->offset_theta = nav->theta_all->length;
                                    nav->theta_all->length += 1;
                                }
                            } else if( ssm_in_par(nav->par_disp, nav->par_all->p[i]->name) ) {
                                if(!(nav->noises_off & SSM_NO_DIFF)){
                                    nav->theta_all->p[nav->theta_all->length] = nav->par_all->p[i];
                                    nav->theta_all->p[nav->theta_all->length]->offset_theta = nav->theta_all->length;
                                    nav->theta_all->length += 1;
                                }
                            } else {
                                nav->theta_all->p[nav->theta_all->length] = nav->par_all->p[i];
                                nav->theta_all->p[nav->theta_all->length]->offset_theta = nav->theta_all->length;
                                nav->theta_all->length += 1;
                            }

                            int in_icsv = ssm_in_par(nav->par_icsv, nav->par_all->p[i]->name);
                            int in_icdiff =ssm_in_par(nav->par_icdiff, nav->par_all->p[i]->name);

                            if(!in_icsv && !in_icdiff){
                                nav->theta_no_icsv_no_icdiff->p[nav->theta_no_icsv_no_icdiff->length] = nav->par_all->p[i];
                                nav->theta_no_icsv_no_icdiff->length += 1;
                            } else if (in_icsv || in_icdiff){
                                if(in_icdiff){
                                    if(!(nav->noises_off & SSM_NO_DIFF)){ //diffusion is allowed
                                        nav->theta_icsv_icdiff->p[nav->theta_icsv_icdiff->length] = nav->par_all->p[i];
                                        nav->theta_icsv_icdiff->length += 1;
                                    } else {
                                        nav->theta_no_icsv_no_icdiff->p[nav->theta_no_icsv_no_icdiff->length] = nav->par_all->p[i];
                                        nav->theta_no_icsv_no_icdiff->length += 1;
                                    }
                                } else {
                                    nav->theta_icsv_icdiff->p[nav->theta_icsv_icdiff->length] = nav->par_all->p[i];
                                    nav->theta_icsv_icdiff->length += 1;
                                }
                            }

                        }


                    }
                }
            }

            break;
        }
    }

    //files (CSV open and print headers)
    if(opts->print & SSM_PRINT_TRACE){
#if SSM_JSON
        nav->trace = stdout;
#else
        snprintf(str, SSM_STR_BUFFSIZE, "%s/trace_%d.csv", opts->root,  opts->id);
        nav->trace = fopen(str, "w");
        ssm_print_header_trace(nav->trace, nav);
#endif
    } else {
        nav->trace = NULL;
    }

    if(opts->print & SSM_PRINT_X){
#if SSM_JSON
        nav->X = stdout;
#else
snprintf(str, SSM_STR_BUFFSIZE, "%s/X_%d.csv", opts->root,  opts->id);
 nav->X = fopen(str, "w");
 ssm_print_header_X(nav->X, nav);
#endif
    } else {
        nav->X = NULL;
    }

    if(opts->print & SSM_PRINT_HAT){
#if SSM_JSON
        nav->hat = stdout;
#else
        snprintf(str, SSM_STR_BUFFSIZE, "%s/hat_%d.csv", opts->root,  opts->id);
        nav->hat = fopen(str, "w");
        ssm_print_header_hat(nav->hat, nav);
#endif
    } else {
        nav->hat = NULL;
    }

    if(opts->print & SSM_PRINT_DIAG){
#if SSM_JSON
        nav->diag = stdout;
#else
        snprintf(str, SSM_STR_BUFFSIZE, "%s/diag_%d.csv", opts->root,  opts->id);
        nav->diag = fopen(str, "w");
        if(opts->algo & (SSM_SMC | SSM_KALMAN)){
            ssm_print_header_pred_res(nav->diag, nav);
        } else if (opts->algo & (SSM_PMCMC | SSM_KMCMC)){
            ssm_print_header_ar(nav->diag);
        } else if (opts->algo & SSM_MIF){
            ssm_mif_print_header_mean_var_theoretical_ess(nav->diag, nav);
        }
#endif
    } else {
        nav->diag = NULL;
    }

    return nav;
}