示例#1
0
static json_object*
findMemberByName(json_object* poObj, const char* pszName )
{
	json_object* poTmp;
	json_object_iter it;

	poTmp = poObj;

	if( NULL == pszName || NULL == poObj)
		return NULL;

	it.key = NULL;
	it.val = NULL;
	it.entry = NULL;

	if( NULL != json_object_get_object(poTmp) )
	{
		assert( NULL != json_object_get_object(poTmp)->head );

		for( it.entry = json_object_get_object(poTmp)->head;
		        ( it.entry ?
		          ( it.key = (char*)it.entry->k,
		            it.val = (json_object*)it.entry->v, it.entry) : 0);
		        it.entry = it.entry->next)
		{
			if( strcasecmp((char *)it.key, pszName )==0 )
				return it.val;
		}
	}

	return NULL;
}
示例#2
0
CJSONStructIterator::CJSONStructIterator(const CJSONEntry& oEntry)
{
    m_rootObject = 0;

    m_struct = json_object_get_object( oEntry.getObject() );
    m_curEntry = m_struct->head;
}
示例#3
0
gint jobdesc_streams_count (gchar *job, gchar *pipeline)
{
        JSON_Value *val;
        JSON_Object *obj;
        JSON_Array *array;
        gsize size, i;
        gint count, index;
        gchar *bin, *ptype;

        val = json_parse_string_with_comments (job);
        obj = json_value_get_object (val);
        if (g_str_has_prefix (pipeline, "encoder")) {
                ptype = "appsrc";
                array = json_object_dotget_array (obj, "encoders");
                sscanf (pipeline, "encoder.%d", &index);
                obj = json_array_get_object (array, index);

        } else if (g_str_has_prefix (pipeline, "source")) {
                ptype = "appsink";
                obj = json_object_get_object (obj, "source");
        }
        array = json_object_dotget_array (obj, "bins");
        size = json_array_get_count (array);
        count = 0;
        for (i = 0; i < size; i++) {
                bin = (gchar *)json_array_get_string (array, i);
                if (g_strrstr (bin, ptype) != NULL)
                        count += 1;
        }
        json_value_free (val);

        return count;
}
示例#4
0
gchar * jobdesc_element_caps (gchar *job, gchar *element)
{
        JSON_Value *val;
        JSON_Object *obj;
        JSON_Array *array;
        gchar *p, *caps;
        gint index;

        val = json_parse_string_with_comments (job);
        obj = json_value_get_object (val);
        if (g_str_has_prefix (element, "encoder")) {
                array = json_object_dotget_array (obj, "encoders");
                sscanf (element, "encoder.%d", &index);
                obj = json_array_get_object (array, index);

        } else {
                obj = json_object_get_object (obj, "source");
        }
        p = g_strrstr (element, "elements");
        caps = (gchar *)json_object_dotget_string (obj, p);
        if (caps == NULL) {
                p = NULL;

        } else {
	        p = g_strdup (caps);
        }
        json_value_free (val);

        return p;
}
int parse_gateway_configuration(const char * conf_file) {
	const char conf_obj[] = "gateway_conf";
	JSON_Value *root_val;
	JSON_Object *root = NULL;
	JSON_Object *conf = NULL;
	const char *str; /* pointer to sub-strings in the JSON data */
	unsigned long long ull = 0;

	/* try to parse JSON */
	root_val = json_parse_file_with_comments(conf_file);
	root = json_value_get_object(root_val);
	if (root == NULL) {
		MSG("ERROR: %s id not a valid JSON file\n", conf_file);
		exit(EXIT_FAILURE);
	}
	conf = json_object_get_object(root, conf_obj);
	if (conf == NULL) {
		MSG("INFO: %s does not contain a JSON object named %s\n", conf_file, conf_obj);
		return -1;
	} else {
		MSG("INFO: %s does contain a JSON object named %s, parsing gateway parameters\n", conf_file, conf_obj);
	}

	/* getting network parameters (only those necessary for the packet logger) */
	str = json_object_get_string(conf, "gateway_ID");
	if (str != NULL) {
		sscanf(str, "%llx", &ull);
		lgwm = ull;
		MSG("INFO: gateway MAC address is configured to %016llX\n", ull);
	}

	json_value_free(root_val);
	return 0;
}
示例#6
0
文件: mjson.c 项目: kingiol/cmoon
void mjson_str2hdf(HDF *node, struct json_object *o)
{
    if (!node) return;
    
    char *s = hdf_obj_value(node);
    
    struct json_object *obj;
    struct array_list *list;
    enum json_type type;
    HDF *cnode;
    char tok[64];
    int i;
    
    char *key; struct json_object *val; struct lh_entry *entry;
    
    obj = o;

    if (!obj && s && *s) {
        obj = json_tokener_parse(s);
    }
    if (!obj || obj < 0) return;

    type = json_object_get_type(obj);

    switch (type) {
    case json_type_boolean:
        hdf_set_int_value(node, NULL, json_object_get_boolean(obj));
        return;
    case json_type_int:
        hdf_set_int_value(node, NULL, json_object_get_int(obj));
        return;
    case json_type_double:
        sprintf(tok, "%f", json_object_get_double(obj));
        hdf_set_value(node, NULL, tok);
        return;
    case json_type_string:
        hdf_set_value(node, NULL, json_object_get_string(obj));
        return;
    case json_type_array:
        list = json_object_get_array(obj);
        for (i = 0; i < list->length; i++) {
            sprintf(tok, "%d", i);
            hdf_get_node(node, tok, &cnode);
            mjson_str2hdf(cnode, (struct json_object*)list->array[i]);
        }
        return;
    case json_type_object:
        for(entry = json_object_get_object(obj)->head;
            (entry ? (key = (char*)entry->k,
                      val = (struct json_object*)entry->v, entry) : 0);
            entry = entry->next) {
            hdf_get_node(node, key, &cnode);
            mjson_str2hdf(cnode, val);
        }
        return;
    default:
        return;
    }
}
示例#7
0
void _PollResultArrayForeach(JsonArray *array,
                                     guint index_,
                                     JsonNode *element_node,
                                     gpointer user_data)
{
    JsonObject *jo;
    const gchar *tmpCCStr;
    GWQSession *wqs;
    QQRecvMsg *rMsg = NULL;
    
    wqs = (GWQSession*)user_data;
    if (!(jo = json_node_get_object(element_node))) {
        GWQ_ERR_OUT(ERR_OUT, "\n");
    }
    if (!(tmpCCStr = json_object_get_string_member(jo, "poll_type"))) {
        GWQ_ERR("poll no pool_type found");
    }
    if (tmpCCStr) {
        if(g_strcmp0(tmpCCStr, "message") == 0
                && (jo=json_object_get_object(jo, "value"))){
            //buddy message
            rMsg = gwq_create_buddy_message(jo);
        }else if(g_strcmp0(tmpCCStr, "buddies_status_change") == 0
                && (jo=json_object_get_object(jo, "value"))){
            //buddy status change
            rMsg = gwq_create_status_change_message(jo);
        }else if(g_strcmp0(tmpCCStr, "group_message") == 0
                && (jo=json_object_get_object(jo, "value"))){
            //group message
            rMsg = gwq_create_group_message(jo);
        }else if(g_strcmp0(tmpCCStr, "kick_message") == 0
                && (jo=json_object_get_object(jo, "value"))){
            //kick message
            rMsg = gwq_create_kick_message(jo);
        }
        if (rMsg) {
            if (wqs->messageRecieved) {
                wqs->messageRecieved(wqs, rMsg);
            }
            qq_recvmsg_free(rMsg);
        }
    }
    return;
ERR_OUT:
    return;
}
示例#8
0
void cellophane_io_json_response_parse(char * json_string, WsEventInfo * info_rsponse){

    json_object * jobj = json_tokener_parse(json_string);


    char *key; struct json_object *val;
    struct lh_entry *entry;

    for(entry = json_object_get_object(jobj)->head; ({ if(entry) { key = (char*)entry->k; val = (struct json_object*)entry->v; } ; entry; }); entry = entry->next ){
gboolean mmsvc_core_msg_json_deserialize_len(char *key, char* buf, int *parse_len, void *data, mused_msg_parse_err_e *err)
{
	int type;
	json_object *val, *jobj;

	g_return_val_if_fail(key != NULL, FALSE);
	g_return_val_if_fail(buf != NULL, FALSE);
	g_return_val_if_fail(data != NULL, FALSE);
	g_return_val_if_fail(parse_len != NULL, FALSE);

	jobj = _mmsvc_core_msg_json_tokener_parse_len(buf, parse_len, err);
	g_return_val_if_fail(jobj != NULL, FALSE);

	val = _mmsvc_core_msg_json_find_obj(jobj, key);
	if (!val) {
		LOGE("\"%s\" key is not founded", key);
		return FALSE;
	}

	type = json_object_get_type(val);
	switch (type) {
	case json_type_null:
		LOGD("json_type_null\n");
		break;
	case json_type_boolean:
		LOGD("json_type_boolean (%s)          value: %d", key, json_object_get_boolean(val));
		break;
	case json_type_double:
		*(double *)data = json_object_get_double(val);
		LOGD("json_type_double (%s)          value: %p", key, (double *)data);
		break;
	case json_type_int:
		*(int *)data = json_object_get_int(val);
		LOGD("json_type_int (%s)          value: %p", key, (int *)data);
		break;
	case json_type_object:
		LOGD("json_type_object (%s)          value: %d", key, json_object_get_object(val));
		break;
	case json_type_string:
		strncpy((char *)data, json_object_get_string(val), strlen(json_object_get_string(val)));
		LOGD("json_type_string (%s)          value: %s", key, (char *)data);
		break;
	case json_type_array:
		LOGD("json_type_array (%s)", key);
		int i, len;
		int *int_data = (int *)data;
		len = json_object_array_length(val);
		for (i = 0; i < len; i++)
			int_data[i] = json_object_get_int(json_object_array_get_idx(val, i));
		break;
	}
	json_object_put(jobj);
	return TRUE;
}
示例#10
0
文件: config.c 项目: aranhoide/bud
void bud_config_read_pool_conf(JSON_Object* obj,
                               const char* key,
                               bud_config_http_pool_t* pool) {
  JSON_Object* p;

  p = json_object_get_object(obj, key);
  if (p != NULL) {
    pool->enabled = json_object_get_boolean(p, "enabled");
    pool->port = (uint16_t) json_object_get_number(p, "port");
    pool->host = json_object_get_string(p, "host");
    pool->query_fmt = json_object_get_string(p, "query");
  }
}
INT32 tg_shared_preferences_get_child_count(SharedPreferences* thiz,const CHAR* key_path,INT32* count)
{
    struct json_object *jso = tg_shared_preferences_find_leaf_obj(thiz,key_path);
    struct lh_table* lh = NULL;
    return_val_if_fail((jso),SharedPreferences_KEY_NOT_EXIST);
    lh =  json_object_get_object(jso);
    if (!lh)
        *count = 0;
    else
        *count = lh->count;
    return SharedPreferences_SUCC;

}
示例#12
0
CJSONStructIterator::CJSONStructIterator(const CJSONEntry& oEntry, const char* strName)
{
    m_struct = 0;
    m_curEntry = 0;
    m_rootObject = 0;

    CJSONEntry oItem = oEntry.getEntry(strName);
    if ( !oItem.isEmpty() )
    {
        m_struct = json_object_get_object( oItem.getObject() );
        m_curEntry = m_struct->head;
    }
}
示例#13
0
CJSONStructIterator::CJSONStructIterator(const char* szData)
{
    m_struct = 0;
    m_curEntry = 0;
    m_rootObject = json_tokener_parse(const_cast<char*>(szData));

	if ( !m_rootObject || is_error(m_rootObject) ) 
        m_rootObject = 0;
    else
    {
        m_struct = json_object_get_object((struct json_object *)m_rootObject);
        m_curEntry = m_struct->head;
    }
}
示例#14
0
int loadParamList(char *fn, nameValuePair_t list[], int alen) {
    int ret = 0;
    json_object *root = json_object_from_file(fn);
    if (NULL != root) {
        /*const char *str = json_object_to_json_string(root);
        if (NULL != str) {
            printf("file is\n%s\n", str);
        } else {
            ret = 1;
            printf("failed to get json string\n");
        }
        dumpJsonObj(root);*/

        json_object *node = root;
        if (!json_object_is_type(node, json_type_object)) {
            printf("the paramlist file is wrong\n");
        } else {
            node = json_object_object_get(node, "ParamList");
            if (NULL == node) {
                printf("can NOT find ParamList\n");
            } else {
                /* try to get name/value pairs */
                char *key; struct json_object *val;
                struct lh_entry *entry = NULL;
                int count = 0;
                for (entry = json_object_get_object(node)->head;
                entry && count < alen; entry = entry->next) {
                    key = (char*)entry->k;
                    val = (struct json_object*)entry->v;
                    /* get name */
                    //printf("key is [%s]\n", key);
                    strncpy(list[count].name, key, MAX_NAME_LEN);
                    list[count].nameLen = strlen(list[count].name);
                    /* get value */
                    //printf("value is [%s]\n", json_object_to_json_string(val));
                    strncpy(list[count].value, json_object_get_string(val), MAX_VALUE_LEN);
                    list[count].valueLen = strlen(list[count].value);
                    count++;
                }
            }
        }
        json_object_put(root);
    } else {
        printf("failed to get json obj from file\n");
        ret = 1;
    }

    return ret;
}
示例#15
0
static json_object*
findMemberByName(json_object* poObj, const char* pszName )
{
	json_object* poTmp;
	json_object_iter it;

	poTmp = poObj;

	if( NULL == pszName || NULL == poObj)
		return NULL;

	it.key = NULL;
	it.val = NULL;
	it.entry = NULL;

	if( NULL != json_object_get_object(poTmp) )
	{
		if( NULL == json_object_get_object(poTmp)->head )
		{
			geojson_lwerror("invalid GeoJSON representation", 2);
			return NULL;
		}

		for( it.entry = json_object_get_object(poTmp)->head;
		        ( it.entry ?
		          ( it.key = (char*)it.entry->k,
		            it.val = (json_object*)it.entry->v, it.entry) : 0);
		        it.entry = it.entry->next)
		{
			if( strcasecmp((char *)it.key, pszName )==0 )
				return it.val;
		}
	}

	return NULL;
}
示例#16
0
/**
 * ****************************************************************************
 */
struct json_object_iterator
json_object_iter_begin(struct json_object* obj)
{
    struct json_object_iterator iter;
    struct lh_table* pTable;

    /// @note json_object_get_object will return NULL if passed NULL
    ///       or a non-json_type_object instance
    pTable = json_object_get_object(obj);
    JASSERT(NULL != pTable);

    /// @note For a pair-less Object, head is NULL, which matches our
    ///       definition of the "end" iterator
    iter.opaque_ = pTable->head;
    return iter;
}
示例#17
0
int parse_blueprint_root(JSON_Object *root, blueprint bp)
{
	bp->version = json_object_get_number(root, "Version");

	bp->Name = bfromcstr(json_object_get_string(root, "Name"));

	JSON_Object *blueprint = json_object_get_object(root, "Blueprint");
	if (blueprint == NULL)
		return 1;

	int retval;
	if ((retval = parse_blueprint_json(blueprint, bp)) != 0)
		return retval;

	return 0;
}
示例#18
0
gboolean jobdesc_m3u8streaming (gchar *job)
{
        JSON_Value *val;
        JSON_Object *obj;
        gboolean m3u8streaming;

        val = json_parse_string_with_comments (job);
        obj = json_value_get_object (val);
        if (json_object_get_object (obj, "m3u8streaming") != NULL) {
                m3u8streaming = TRUE;

        } else {
                m3u8streaming = FALSE;
        }
        json_value_free (val);

        return m3u8streaming;
}
示例#19
0
int dumpJsonObj(struct json_object *root) {
    json_type type = json_object_get_type(root);

    if (type == json_type_null) {
        return 0;
    } else if (type == json_type_object) {
        char *key; struct json_object *val;
        struct lh_entry *entry = NULL;
        for (entry = json_object_get_object(root)->head; entry; entry = entry->next) {
            key = (char*)entry->k;
            val = (struct json_object*)entry->v;
            printf("Object=%s: \n", key);
            dumpJsonObj(val);
        }
    } else if (type == json_type_string) {
        printf("string=%s\n", json_object_to_json_string(root));
    } else {
        printf("unsupported type\n");
    }

    return 0;
}
示例#20
0
OSStatus  _properties_notify(mico_Context_t * const inContext, struct mico_service_t service_table[])
{
  OSStatus err = kUnknownErr;
  json_object *notify_obj = NULL;
  const char *notify_json_string = NULL;
  
  require_action(inContext, exit, err = kParamErr);
  
  notify_obj = json_object_new_object();
  require_action(notify_obj, exit, err = kParamErr);
  
  // properties update check
  err = mico_properties_notify_check(inContext, service_table, notify_obj);
  require_noerr(err, exit);
  
  // send notify message to cloud
  if( NULL != (json_object_get_object(notify_obj)->head) ){
    notify_json_string = json_object_to_json_string(notify_obj);
    // notify to topic: <device_id>/out/read
    err = MicoFogCloudMsgSend(inContext, FOGCLOUD_MSG_TOPIC_OUT_NOTIFY, 
                              (unsigned char*)notify_json_string, strlen(notify_json_string));
  }
  else{
    // no update msg
    err = kNoErr;
  }
  
exit:
  if(kNoErr != err){
    msg_dispatch_log("ERROR: _properties_notify error, err = %d", err);
  }
  if(NULL != notify_obj){
    json_object_put(notify_obj);
    notify_obj = NULL;
  }
  return err;
}
INT32 tg_shared_preferences_produce_child_path_by_idx(SharedPreferences* thiz,const CHAR* key_path,INT32 index,CHAR** ret)
{
    struct json_object *jso = tg_shared_preferences_find_leaf_obj(thiz,key_path);
    struct lh_table* lh = NULL;
    INT32 len = 0;
    CHAR* path = NULL;
    CHAR* key = NULL;
    return_val_if_fail((jso),SharedPreferences_KEY_NOT_EXIST);
    lh =  json_object_get_object(jso);
    if (!lh || lh->count<=index)
        return SharedPreferences_KEY_NOT_EXIST;
    key=(CHAR*)lh_table_get_key_by_idx(lh,index);
    if (!key)
        return SharedPreferences_KEY_NOT_EXIST;
    path = TG_CALLOC_V2(strlen(key_path)+strlen(key)+2);
    len =strlen(key_path);
    if (key_path[len-1]=='/')
        sprintf(path,"%s%s",key_path,key);
    else
        sprintf(path,"%s/%s",key_path,key);
    *ret=path;
    return SharedPreferences_SUCC;

}
示例#22
0
static dpl_status_t
convert_obj_to_value(dpl_ctx_t *ctx,
                     struct json_object *obj,
                     int level,
                     dpl_value_t **valp)
{
  int ret, ret2;
  dpl_value_t *val = NULL;
  char *key; 
  struct lh_entry *entry;
  json_object *child;
  dpl_dict_t *subdict = NULL;
  dpl_vec_t *vector = NULL;

  DPRINTF("convert_obj_to_value level=%d type=%d\n", level, json_object_get_type(obj));

  val = malloc(sizeof (*val));
  if (NULL == val)
    {
      ret = DPL_ENOMEM;
      goto end;
    }
  memset(val, 0, sizeof (*val));

  switch (json_object_get_type(obj))
    {
    case json_type_null:
      return DPL_ENOTSUPP;
    case json_type_array:
      {
        int n_items = json_object_array_length(obj);
        int i;

        vector = dpl_vec_new(2, 2);
        if (NULL == vector)
          {
            ret = DPL_ENOMEM;
            goto end;
          }

        for (i = 0;i < n_items;i++)
          {
            child = json_object_array_get_idx(obj, i);
            dpl_value_t *subval;

            ret2 = convert_obj_to_value(ctx, child, level+1, &subval);
            if (DPL_SUCCESS != ret2)
              {
                ret = ret2;
                goto end;
              }
            
            ret2 = dpl_vec_add_value(vector, subval);

            dpl_value_free(subval);
            
            if (DPL_SUCCESS != ret2)
              {
                ret = ret2;
                goto end;
              }
          }

        val->type = DPL_VALUE_VECTOR;
        val->vector = vector;
        vector = NULL;
        break ;
      }
    case json_type_object:
      {
        subdict = dpl_dict_new(13);
        if (NULL == subdict)
          {
            ret = DPL_ENOMEM;
            goto end;
          }
        
        for (entry = json_object_get_object(obj)->head; (entry ? (key = (char*)entry->k, child = (struct json_object*)entry->v, entry) : 0); entry = entry->next)
          {
            dpl_value_t *subval;

            DPRINTF("key='%s'\n", key);

            ret2 = convert_obj_to_value(ctx, child, level+1, &subval);
            if (DPL_SUCCESS != ret2)
              {
                ret = ret2;
                goto end;
              }
            
            ret2 = dpl_dict_add_value(subdict, key, subval, 0);

            dpl_value_free(subval);

            if (DPL_SUCCESS != ret2)
              {
                ret = ret2;
                goto end;
              }
          }

        val->type = DPL_VALUE_SUBDICT;
        val->subdict = subdict;
        subdict = NULL;
        break ;
      }
    case json_type_boolean:
    case json_type_double:
    case json_type_int:
    case json_type_string:
      {
        pthread_mutex_lock(&ctx->lock); //lock for objects other than string
        val->string = strdup((char *) json_object_get_string(obj));
        pthread_mutex_unlock(&ctx->lock);

        if (NULL == val->string)
          {
            ret = DPL_ENOMEM;
            goto end;
          }
        val->type = DPL_VALUE_STRING;
        break ;
      }
    }

  if (NULL != valp)
    {
      *valp = val;
      val = NULL;
    }

  ret = DPL_SUCCESS;
  
 end:

  if (NULL != vector)
    dpl_vec_free(vector);

  if (NULL != subdict)
    dpl_dict_free(subdict);

  if (NULL != val)
    dpl_value_free(val);

  DPRINTF("level=%d ret=%d\n", level, ret);

  return ret;
}
示例#23
0
文件: config.c 项目: indutny/bud
bud_error_t bud_config_load(bud_config_t* config) {
  int i;
  bud_error_t err;
  JSON_Value* json;
  JSON_Value* val;
  JSON_Object* frontend;
  JSON_Object* obj;
  JSON_Object* log;
  JSON_Object* avail;
  JSON_Array* contexts;

  if (config->piped) {
    char* content;

    ASSERT(config->loop != NULL, "Loop should be present");
    err = bud_read_file_by_fd(config->loop, 0, &content);
    if (!bud_is_ok(err))
      goto end;

    err = bud_hashmap_insert(&config->files.hashmap,
                             kPipedConfigPath,
                             strlen(kPipedConfigPath),
                             content);
    if (!bud_is_ok(err)) {
      free(content);
      goto end;
    }

    json = json_parse_string(content);
  } else if (config->inlined) {
    json = json_parse_string(config->path);
  } else {
    const char* contents;

    err = bud_config_load_file(config, config->path, &contents);
    if (!bud_is_ok(err))
      goto end;
    json = json_parse_string(contents);
  }

  if (json == NULL) {
    err = bud_error_dstr(kBudErrJSONParse, config->path);
    goto end;
  }

  obj = json_value_get_object(json);
  if (obj == NULL) {
    err = bud_error(kBudErrJSONNonObjectRoot);
    goto failed_alloc_path;
  }

  err = bud_config_load_tracing(&config->trace,
                                json_object_get_object(obj, "tracing"));
  if (!bud_is_ok(err))
    goto failed_alloc_path;

  /* Allocate contexts and backends */
  contexts = json_object_get_array(obj, "contexts");
  config->context_count = contexts == NULL ? 0 : json_array_get_count(contexts);
  config->contexts = calloc(config->context_count + 1,
                            sizeof(*config->contexts));
  if (config->contexts == NULL) {
    err = bud_error_str(kBudErrNoMem, "bud_context_t");
    goto failed_alloc_contexts;
  }

  config->json = json;

  /* Workers configuration */
  config->worker_count = -1;
  config->restart_timeout = -1;
  config->master_ipc = -1;
  val = json_object_get_value(obj, "workers");
  if (val != NULL)
    config->worker_count = json_value_get_number(val);
  val = json_object_get_value(obj, "restart_timeout");
  if (val != NULL)
    config->restart_timeout = json_value_get_number(val);
  val = json_object_get_value(obj, "master_ipc");
  if (val != NULL)
    config->master_ipc = json_value_get_boolean(val);

  /* Logger configuration */
  log = json_object_get_object(obj, "log");
  config->log.stdio = -1;
  config->log.syslog = -1;
  if (log != NULL) {
    config->log.level = json_object_get_string(log, "level");
    config->log.facility = json_object_get_string(log, "facility");

    val = json_object_get_value(log, "stdio");
    if (val != NULL)
      config->log.stdio = json_value_get_boolean(val);
    val = json_object_get_value(log, "syslog");
    if (val != NULL)
      config->log.syslog = json_value_get_boolean(val);
  }

  /* Availability configuration */
  avail = json_object_get_object(obj, "availability");
  config->availability.death_timeout = -1;
  config->availability.revive_interval = -1;
  config->availability.retry_interval = -1;
  config->availability.max_retries = -1;
  if (avail != NULL) {
    val = json_object_get_value(avail, "death_timeout");
    if (val != NULL)
      config->availability.death_timeout = json_value_get_number(val);
    val = json_object_get_value(avail, "revive_interval");
    if (val != NULL)
      config->availability.revive_interval = json_value_get_number(val);
    val = json_object_get_value(avail, "retry_interval");
    if (val != NULL)
      config->availability.retry_interval = json_value_get_number(val);
    val = json_object_get_value(avail, "max_retries");
    if (val != NULL)
      config->availability.max_retries = json_value_get_number(val);
  }

  /* Frontend configuration */
  frontend = json_object_get_object(obj, "frontend");
  err = bud_config_load_frontend(frontend, &config->frontend);
  if (!bud_is_ok(err))
    goto failed_alloc_contexts;

  /* Load frontend's context */
  err = bud_context_load(frontend, &config->contexts[0]);
  if (!bud_is_ok(err))
    goto failed_alloc_contexts;

  /* Backend configuration */
  config->balance = json_object_get_string(obj, "balance");
  err = bud_config_load_backend_list(config,
                                      obj,
                                      &config->contexts[0].backend);
  if (!bud_is_ok(err))
    goto failed_alloc_contexts;

  /* User and group configuration */
  config->user = json_object_get_string(obj, "user");
  config->group = json_object_get_string(obj, "group");

  /* SNI configuration */
  bud_config_read_pool_conf(obj, "sni", &config->sni);

  /* OCSP Stapling configuration */
  bud_config_read_pool_conf(obj, "stapling", &config->stapling);

  /* SSL Contexts */

  /* TODO(indutny): sort them and do binary search */
  for (i = 0; i < config->context_count; i++) {
    bud_context_t* ctx;

    /* NOTE: contexts[0] - is a default context */
    ctx = &config->contexts[i + 1];
    obj = json_array_get_object(contexts, i);
    if (obj == NULL) {
      err = bud_error(kBudErrJSONNonObjectCtx);
      goto failed_load_context;
    }

    err = bud_context_load(obj, ctx);
    if (!bud_is_ok(err))
      goto failed_load_context;

    err = bud_config_load_backend_list(config, obj, &ctx->backend);
    if (!bud_is_ok(err))
      goto failed_load_context;
  }

  bud_config_set_defaults(config);

  return bud_config_init(config);

failed_load_context:
  /* Deinitalize contexts */
  for (i++; i >= 0; i--) {
    bud_context_t* ctx;

    ctx = &config->contexts[i];
    free(ctx->backend.list);
    ctx->backend.list = NULL;
  }

failed_alloc_contexts:
  free(config->contexts);
  config->contexts = NULL;
  free(config->trace.dso);
  config->trace.dso = NULL;

failed_alloc_path:
  json_value_free(json);
  config->json = NULL;

end:
  return err;
}
static MODULE_HANDLE NativeModuleHost_Create(BROKER_HANDLE broker, const void* configuration)
{
    MODULE_HOST * result;
    if (broker == NULL || configuration == NULL)
    {
        /*Codes_SRS_NATIVEMODULEHOST_17_008: [ NativeModuleHost_Create shall return NULL if broker is NULL. ]*/
        /*Codes_SRS_NATIVEMODULEHOST_17_009: [ NativeModuleHost_Create shall return NULL if configuration does not contain valid JSON. ]*/
        LogError("broker [%p] or configuration [%p] is NULL, both are required", broker, configuration);
        result = NULL;
    }
    else
    {
        /*Codes_SRS_NATIVEMODULEHOST_17_010: [ NativeModuleHost_Create shall intialize the Module_Loader. ]*/
        if (ModuleLoader_Initialize() != MODULE_LOADER_SUCCESS)
        {
            /*Codes_SRS_NATIVEMODULEHOST_17_026: [ If any step above fails, then NativeModuleHost_Create shall free all resources allocated and return NULL. ]*/
            LogError("ModuleLoader_Initialize failed");
            result = NULL;
        }
        else
        {
            /*Codes_SRS_NATIVEMODULEHOST_17_011: [ NativeModuleHost_Create shall parse the configuration JSON. ]*/
            char * outprocess_module_args = (char *)configuration;
            JSON_Value *root_value = json_parse_string(outprocess_module_args);
            JSON_Object * module_host_args;
            if ((root_value == NULL) ||
                ((module_host_args = json_value_get_object(root_value)) == NULL))
            {
                if (root_value != NULL)
                {
                    json_value_free(root_value);
                }
                LogError("NativeModuleHost_Create could not parse arguments as JSON");
                result = NULL;
            }
            else
            {
                /*Codes_SRS_NATIVEMODULEHOST_17_035: [ If the "outprocess.loaders" array exists in the configuration JSON, NativeModuleHost_Create shall initialize the Module_Loader from this array. ]*/
                JSON_Value * loaders_array = json_object_get_value(module_host_args, OOP_MODULE_LOADERS_ARRAY_KEY);
                if ((loaders_array != NULL) &&
                    (ModuleLoader_InitializeFromJson(loaders_array) != MODULE_LOADER_SUCCESS))
                {
                    LogError("NativeModuleHost_Create could not extract loaders array from module arguments.");
                    result = NULL;
                }
                else
                {
                    /*Codes_SRS_NATIVEMODULEHOST_17_012: [ NativeModuleHost_Create shall get the "outprocess.loader" object from the configuration JSON. ]*/
                    JSON_Object * loader_args = json_object_get_object(module_host_args, OOP_MODULE_LOADER_KEY);
                    if (loader_args == NULL)
                    {
                        LogError("NativeModuleHost_Create could not get loader arguments.");
                        result = NULL;
                    }
                    else
                    {
                        GATEWAY_MODULE_LOADER_INFO loader_info;
                        if (parse_loader(loader_args, &loader_info) != 0)
                        {
                            /*Codes_SRS_NATIVEMODULEHOST_17_026: [ If any step above fails, then NativeModuleHost_Create shall free all resources allocated and return NULL. ]*/
                            LogError("NativeModuleHost_Create could not extract loader information from loader arguments.");
                            result = NULL;
                        }
                        else
                        {
                            // Have loader and entrypoint now, get module.
                            result = (MODULE_HOST*)malloc(sizeof(MODULE_HOST));
							if (result == NULL)
							{
								LogError("NativeModuleHost_Create could not allocate module.");
								result = NULL;
							}
							else
							{
								/*Codes_SRS_NATIVEMODULEHOST_17_018: [ NativeModuleHost_Create shall get the "module.args" object from the configuration JSON. ]*/
								JSON_Value * module_args = json_object_get_value(module_host_args, OOP_MODULE_ARGS_KEY);
								char * module_args_string = json_serialize_to_string(module_args);
								if (module_create(result, broker, &loader_info, module_args_string) != 0)
								{
									/*Codes_SRS_NATIVEMODULEHOST_17_026: [ If any step above fails, then NativeModuleHost_Create shall free all resources allocated and return NULL. ]*/
									LogError("NativeModuleHost_Create could not load module.");
									free(result);
									result = NULL;
								}
								/*Codes_SRS_NATIVEMODULEHOST_17_024: [ NativeModuleHost_Create shall free all resources used during module loading. ]*/
								json_free_serialized_string(module_args_string);
							}
                            loader_info.loader->api->FreeEntrypoint(loader_info.loader, loader_info.entrypoint);
                        }
                    }
                }
                /*Codes_SRS_NATIVEMODULEHOST_17_024: [ NativeModuleHost_Create shall free all resources used during module loading. ]*/
                json_value_free(root_value);
            }
            if (result == NULL)
            {
                // failed to create a module, give up entirely.
                /*Codes_SRS_NATIVEMODULEHOST_17_026: [ If any step above fails, then NativeModuleHost_Create shall free all resources allocated and return NULL. ]*/
                ModuleLoader_Destroy();
            }
        }
    }
    return result;
}
示例#25
0
int main(int argc, char **argv)
{
	struct json_object *json;
	struct array_list *tests;
	struct lh_entry *entry;
	char *key;
	struct json_object *val;
	int i;
	context ctx;

	if (argc != 2) {
		printf("Usage: %s <filename>\n", argv[0]);
		return 1;
	}

	json = json_object_from_file(argv[1]);
	assert(!is_error(json));

	assert(strcmp((char *) ((json_object_get_object(json)->head)->k),
			"tests") == 0);

	/* Get array of tests */
	tests = json_object_get_array((struct json_object *)
			(json_object_get_object(json)->head)->v);

	for (i = 0; i < array_list_length(tests); i++) {
		/* Get test */
		struct json_object *test =
			(struct json_object *) array_list_get_idx(tests, i);

		ctx.last_start_tag = NULL;
		ctx.content_model = NULL;
		ctx.process_cdata = false;

		/* Extract settings */
		for (entry = json_object_get_object(test)->head; entry;
				entry = entry->next) {
			key = (char *) entry->k;
			val = (struct json_object *) entry->v;

			if (strcmp(key, "description") == 0) {
				printf("Test: %s\n",
					json_object_get_string(val));
			} else if (strcmp(key, "input") == 0) {
				ctx.input = (const uint8_t *)
					json_object_get_string(val);
				ctx.input_len =	json_object_get_string_len(val);
			} else if (strcmp(key, "output") == 0) {
				ctx.output = json_object_get_array(val);
				ctx.output_index = 0;
				ctx.char_off = 0;
			} else if (strcmp(key, "lastStartTag") == 0) {
				ctx.last_start_tag = (const char *)
						json_object_get_string(val);
			} else if (strcmp(key, "contentModelFlags") == 0) {
				ctx.content_model =
						json_object_get_array(val);
			} else if (strcmp(key, "processCDATA") == 0) {
				ctx.process_cdata =
					json_object_get_boolean(val);
			}
		}

		/* And run the test */
		run_test(&ctx);
	}

	json_object_put(json);

	printf("PASS\n");

	return 0;
}
示例#26
0
hubbub_error token_handler(const hubbub_token *token, void *pw)
{
	static const char *token_names[] = {
		"DOCTYPE", "StartTag", "EndTag",
		"Comment", "Character", "EOF"
	};
	size_t i;
	context *ctx = (context *) pw;
	struct json_object *obj = NULL;
	struct array_list *items;

	for (; ctx->output_index < array_list_length(ctx->output);
			ctx->output_index++) {
		/* Get object for index */
		obj = (struct json_object *)
				array_list_get_idx(ctx->output,
						ctx->output_index);

		/* If it's not a string, we've found the expected output */
		if (json_object_get_type(obj) != json_type_string)
			break;

		/* Otherwise, it must be a parse error */
		assert(strcmp(json_object_get_string(obj),
				 "ParseError") == 0);
	}

	/* If we've run off the end, this is an error -- the tokeniser has
	 * produced more tokens than expected. We allow for the generation
	 * of a terminating EOF token, however. */
	assert("too many tokens" &&
			(ctx->output_index < array_list_length(ctx->output) ||
			token->type == HUBBUB_TOKEN_EOF));

	/* Got a terminating EOF -- no error */
	if (ctx->output_index >= array_list_length(ctx->output))
		return HUBBUB_OK;

	/* Now increment the output index so we don't re-expect this token */
	ctx->output_index++;

	/* Expected output must be an array */
	assert(json_object_get_type(obj) == json_type_array);

	items = json_object_get_array(obj);

	printf("got %s: expected %s\n", token_names[token->type],
			json_object_get_string((struct json_object *)
				array_list_get_idx(items, 0)));

	/* Make sure we got the token we expected */
	assert(strcmp(token_names[token->type],
			json_object_get_string((struct json_object *)
				array_list_get_idx(items, 0))) == 0);

	switch (token->type) {
	case HUBBUB_TOKEN_DOCTYPE:
	{
		const char *expname = json_object_get_string(
				array_list_get_idx(items, 1));
		const char *exppub = json_object_get_string(
				array_list_get_idx(items, 2));
		const char *expsys = json_object_get_string(
				array_list_get_idx(items, 3));
		bool expquirks = !json_object_get_boolean(
				array_list_get_idx(items, 4));
		const char *gotname = (const char *)token->data.doctype.name.ptr;
		const char *gotpub, *gotsys;

		printf("'%.*s' %sids:\n",
				(int) token->data.doctype.name.len,
				gotname,
				token->data.doctype.force_quirks ?
						"(force-quirks) " : "");

		if (token->data.doctype.public_missing) {
			gotpub = NULL;
			printf("\tpublic: missing\n");
		} else {
			gotpub = (const char *) token->data.doctype.public_id.ptr;
			printf("\tpublic: '%.*s' (%d)\n",
				(int) token->data.doctype.public_id.len,
				gotpub,
				(int) token->data.doctype.public_id.len);
		}

		if (token->data.doctype.system_missing) {
			gotsys = NULL;
			printf("\tsystem: missing\n");
		} else {
			gotsys = (const char *) token->data.doctype.system_id.ptr;
			printf("\tsystem: '%.*s' (%d)\n",
				(int) token->data.doctype.system_id.len,
				gotsys,
				(int) token->data.doctype.system_id.len);
		}

		assert(token->data.doctype.name.len == strlen(expname));
		assert(strncmp(gotname, expname, strlen(expname)) == 0);

		assert((exppub == NULL) ==
				(token->data.doctype.public_missing == true));
		if (exppub) {
			assert(token->data.doctype.public_id.len == strlen(exppub));
			assert(strncmp(gotpub, exppub, strlen(exppub)) == 0);
		}

		assert((expsys == NULL) ==
				(token->data.doctype.system_missing == true));
		if (gotsys) {
			assert(token->data.doctype.system_id.len == strlen(expsys));
			assert(strncmp(gotsys, expsys, strlen(expsys)) == 0);
		}

		assert(expquirks == token->data.doctype.force_quirks);
	}
		break;
	case HUBBUB_TOKEN_START_TAG:
	{
		const char *expname = json_object_get_string(
				array_list_get_idx(items, 1));
		struct lh_entry *expattrs = json_object_get_object(
				array_list_get_idx(items, 2))->head;
		bool self_closing = json_object_get_boolean(
				array_list_get_idx(items, 3));

		const char *tagname = (const char *)
				token->data.tag.name.ptr;

		printf("expected: '%s' %s\n",
				expname,
				(self_closing) ? "(self-closing) " : "");

		printf("     got: '%.*s' %s\n",
				(int) token->data.tag.name.len,
				tagname,
				(token->data.tag.self_closing) ?
						"(self-closing) " : "");

		if (token->data.tag.n_attributes > 0) {
			printf("attributes:\n");
		}

		assert(token->data.tag.name.len == strlen(expname));
		assert(strncmp(tagname, expname, strlen(expname)) == 0);

		assert((token->data.tag.n_attributes == 0) ==
				(expattrs == NULL));

		assert(self_closing == token->data.tag.self_closing);

		for (i = 0; i < token->data.tag.n_attributes; i++) {
			char *expname = (char *) expattrs->k;
			const char *expval = json_object_get_string(
					(struct json_object *) expattrs->v);
			const char *gotname = (const char *)
				token->data.tag.attributes[i].name.ptr;
			size_t namelen =
				token->data.tag.attributes[i].name.len;
			const char *gotval = (const char *)
				token->data.tag.attributes[i].value.ptr;
			size_t vallen =
				token->data.tag.attributes[i].value.len;

			printf("\t'%.*s' = '%.*s'\n",
					(int) namelen, gotname,
					(int) vallen, gotval);

			assert(namelen == strlen(expname));
			assert(strncmp(gotname, expname,
						strlen(expname)) == 0);
			assert(vallen == strlen(expval));
			assert(strncmp(gotval, expval, strlen(expval)) == 0);

			expattrs = expattrs->next;
		}

		assert(expattrs == NULL);
	}
		break;
	case HUBBUB_TOKEN_END_TAG:
	{
		const char *expname = json_object_get_string(
				array_list_get_idx(items, 1));
		const char *tagname = (const char *)
				token->data.tag.name.ptr;

		printf("'%.*s' %s\n",
				(int) token->data.tag.name.len,
				tagname,
				(token->data.tag.n_attributes > 0) ?
						"attributes:" : "");

		assert(token->data.tag.name.len == strlen(expname));
		assert(strncmp(tagname, expname, strlen(expname)) == 0);
	}
		break;
	case HUBBUB_TOKEN_COMMENT:
	{
		const char *expstr = json_object_get_string(
				array_list_get_idx(items, 1));
		const char *gotstr = (const char *)
				token->data.comment.ptr;

		printf("expected: '%s'\n", expstr);
		printf("     got: '%.*s'\n",
				(int) token->data.comment.len, gotstr);

		assert(token->data.comment.len == strlen(expstr));
		assert(strncmp(gotstr, expstr, strlen(expstr)) == 0);
	}
		break;
	case HUBBUB_TOKEN_CHARACTER:
	{
		int expstrlen = json_object_get_string_len(
				array_list_get_idx(items, 1));
		const char *expstr =json_object_get_string( 
				array_list_get_idx(items, 1));
		const char *gotstr = (const char *)
				token->data.character.ptr;
		size_t len = min(token->data.character.len,
				expstrlen - ctx->char_off);

		printf("expected: '%.*s'\n", (int) len, expstr + ctx->char_off);
		printf("     got: '%.*s'\n", 
				(int) token->data.character.len, gotstr);

		assert(memcmp(gotstr, expstr + ctx->char_off, len) == 0);

		if (len < token->data.character.len) {
			/* Expected token only contained part of the data
			 * Calculate how much is left, then try again with
			 * the next expected token */
			hubbub_token t;

			t.type = HUBBUB_TOKEN_CHARACTER;
			t.data.character.ptr += len;
			t.data.character.len -= len;

			ctx->char_off = 0;

			token_handler(&t, pw);
		} else if (strlen(expstr + ctx->char_off) >
				token->data.character.len) {
			/* Tokeniser output only contained part of the data
			 * in the expected token; calculate the offset into
			 * the token and process the remainder next time */
			ctx->char_off += len;
			ctx->output_index--;
		} else {
			/* Exact match - clear offset */
			ctx->char_off = 0;
		}
	}
		break;
	case HUBBUB_TOKEN_EOF:
		printf("\n");
		break;
	}

	return HUBBUB_OK;
}
示例#27
0
文件: config.c 项目: aranhoide/bud
bud_config_t* bud_config_load(uv_loop_t* loop,
                              const char* path,
                              bud_error_t* err) {
  int i;
  int context_count;
  JSON_Value* json;
  JSON_Value* val;
  JSON_Object* obj;
  JSON_Object* log;
  JSON_Object* frontend;
  JSON_Object* backend;
  JSON_Array* contexts;
  bud_config_t* config;
  bud_context_t* ctx;

  json = json_parse_file(path);
  if (json == NULL) {
    *err = bud_error_str(kBudErrJSONParse, path);
    goto end;
  }

  obj = json_value_get_object(json);
  if (obj == NULL) {
    *err = bud_error(kBudErrJSONNonObjectRoot);
    goto failed_get_object;
  }
  contexts = json_object_get_array(obj, "contexts");
  context_count = contexts == NULL ? 0 : json_array_get_count(contexts);

  config = calloc(1,
                  sizeof(*config) +
                      context_count * sizeof(*config->contexts));
  if (config == NULL) {
    *err = bud_error_str(kBudErrNoMem, "bud_config_t");
    goto failed_get_object;
  }

  config->loop = loop;
  config->json = json;

  /* Workers configuration */
  config->worker_count = -1;
  config->restart_timeout = -1;
  val = json_object_get_value(obj, "workers");
  if (val != NULL)
    config->worker_count = json_value_get_number(val);
  val = json_object_get_value(obj, "restart_timeout");
  if (val != NULL)
    config->restart_timeout = json_value_get_number(val);

  /* Logger configuration */
  log = json_object_get_object(obj, "log");
  config->log.stdio = -1;
  config->log.syslog = -1;
  if (log != NULL) {
    config->log.level = json_object_get_string(log, "level");
    config->log.facility = json_object_get_string(log, "facility");

    val = json_object_get_value(log, "stdio");
    if (val != NULL)
      config->log.stdio = json_value_get_boolean(val);
    val = json_object_get_value(log, "syslog");
    if (val != NULL)
      config->log.syslog = json_value_get_boolean(val);
  }

  /* Frontend configuration */

  frontend = json_object_get_object(obj, "frontend");
  config->frontend.proxyline = -1;
  config->frontend.keepalive = -1;
  config->frontend.server_preference = -1;
  config->frontend.ssl3 = -1;
  if (frontend != NULL) {
    config->frontend.port = (uint16_t) json_object_get_number(frontend, "port");
    config->frontend.host = json_object_get_string(frontend, "host");
    config->frontend.security = json_object_get_string(frontend, "security");
    config->frontend.npn = json_object_get_array(frontend, "npn");
    config->frontend.ciphers = json_object_get_string(frontend, "ciphers");
    config->frontend.cert_file = json_object_get_string(frontend, "cert");
    config->frontend.key_file = json_object_get_string(frontend, "key");
    config->frontend.reneg_window = json_object_get_number(frontend,
                                                           "reneg_window");
    config->frontend.reneg_limit = json_object_get_number(frontend,
                                                          "reneg_limit");

    *err = bud_config_verify_npn(config->frontend.npn);
    if (!bud_is_ok(*err))
      goto failed_get_index;

    val = json_object_get_value(frontend, "proxyline");
    if (val != NULL)
      config->frontend.proxyline = json_value_get_boolean(val);
    val = json_object_get_value(frontend, "keepalive");
    if (val != NULL)
      config->frontend.keepalive = json_value_get_number(val);
    val = json_object_get_value(frontend, "server_preference");
    if (val != NULL)
      config->frontend.server_preference = json_value_get_boolean(val);
    val = json_object_get_value(frontend, "ssl3");
    if (val != NULL)
      config->frontend.ssl3 = json_value_get_boolean(val);
  }

  /* Backend configuration */
  backend = json_object_get_object(obj, "backend");
  config->backend.keepalive = -1;
  if (backend != NULL) {
    config->backend.port = (uint16_t) json_object_get_number(backend, "port");
    config->backend.host = json_object_get_string(backend, "host");
    val = json_object_get_value(backend, "keepalive");
    if (val != NULL)
      config->backend.keepalive = json_value_get_number(val);
  }

  /* SNI configuration */
  bud_config_read_pool_conf(obj, "sni", &config->sni);

  /* OCSP Stapling configuration */
  bud_config_read_pool_conf(obj, "stapling", &config->stapling);

  /* SSL Contexts */

  /* TODO(indutny): sort them and do binary search */
  for (i = 0; i < context_count; i++) {
    /* NOTE: contexts[0] - is a default context */
    ctx = &config->contexts[i + 1];
    obj = json_array_get_object(contexts, i);
    if (obj == NULL) {
      *err = bud_error(kBudErrJSONNonObjectCtx);
      goto failed_get_index;
    }

    ctx->servername = json_object_get_string(obj, "servername");
    ctx->servername_len = ctx->servername == NULL ? 0 : strlen(ctx->servername);
    ctx->cert_file = json_object_get_string(obj, "cert");
    ctx->key_file = json_object_get_string(obj, "key");
    ctx->npn = json_object_get_array(obj, "npn");
    ctx->ciphers = json_object_get_string(obj, "ciphers");

    *err = bud_config_verify_npn(ctx->npn);
    if (!bud_is_ok(*err))
      goto failed_get_index;
  }
  config->context_count = context_count;

  bud_config_set_defaults(config);

  *err = bud_ok();
  return config;

failed_get_index:
  free(config);

failed_get_object:
  json_value_free(json);

end:
  return NULL;
}
示例#28
0
resrc_flow_t *resrc_flow_new_from_json (JSON o, resrc_flow_t *parent)
{
    JSON jhierarchyo = NULL; /* json hierarchy object */
    const char *basename = NULL;
    const char *name = NULL;
    const char *hierarchy = NULL;
    const char *path = NULL;
    const char *hierarchy_path = NULL;
    const char *tmp = NULL;
    const char *type = NULL;
    int64_t id;
    int64_t ssize;
    resrc_flow_t *resrc_flow = NULL;
    resrc_t *flow_resrc;
    resrc_t *resrc = NULL;
    size_t size = 1;
    uuid_t uuid;

    if (!Jget_str (o, "type", &type))
        goto ret;
    Jget_str (o, "basename", &basename);
    Jget_str (o, "name", &name);
    if (!(Jget_int64 (o, "id", &id)))
        id = -1;
    if (Jget_str (o, "uuid", &tmp))
        uuid_parse (tmp, uuid);
    else
        uuid_clear(uuid);
    if (Jget_int64 (o, "size", &ssize))
        size = (size_t) ssize;
    if ((jhierarchyo = Jobj_get (o, "hierarchy"))) {
        struct json_object *val = NULL;
        struct lh_entry *entry = json_object_get_object (jhierarchyo)->head;

        if (entry) {
            hierarchy = (char*)entry->k;
            val = (struct json_object*)entry->v;
            hierarchy_path = json_object_get_string (val);
        }
    }
    if (!Jget_str (o, "path", &path)) {
        if (hierarchy_path)
            path = xstrdup (hierarchy_path);
    }
    if (!path) {
        if (parent)
            path = xasprintf ("%s/%s", resrc_path (parent->flow_resrc), name);
        else
            path = xasprintf ("/%s", name);
    }

    if (!(flow_resrc = resrc_new_resource (type, path, basename, name, NULL, id,
                                           uuid, size)))
        goto ret;

    if (!strncmp (type, "node", 5)) {
        resrc = resrc_lookup (name);
    }
    if ((resrc_flow = resrc_flow_new (parent, flow_resrc, resrc))) {
        /* add time window if we are given a start time */
        int64_t starttime;
        if (Jget_int64 (o, "starttime", &starttime)) {
            JSON    w = Jnew ();
            char    *json_str;
            int64_t endtime;
            int64_t wall_time;

            Jadd_int64 (w, "starttime", starttime);

            if (!Jget_int64 (o, "endtime", &endtime)) {
                if (Jget_int64 (o, "walltime", &wall_time))
                    endtime = starttime + wall_time;
                else
                    endtime = TIME_MAX;
            }
            Jadd_int64 (w, "endtime", endtime);

            json_str = xstrdup (Jtostr (w));
            resrc_twindow_insert (resrc_flow->flow_resrc, "0",
                                  (void *) json_str);
            Jput (w);
        }
    }
    if (resrc)
        resrc_graph_insert (resrc, hierarchy, resrc_flow);
ret:
    return resrc_flow;
}
int parse_SX1301_configuration(const char * conf_file) {
	int i;
	const char conf_obj[] = "SX1301_conf";
	char param_name[32]; /* used to generate variable parameter names */
	const char *str; /* used to store string value from JSON object */
	struct lgw_conf_board_s boardconf;
	struct lgw_conf_rxrf_s rfconf;
	struct lgw_conf_rxif_s ifconf;
	JSON_Value *root_val;
	JSON_Object *root = NULL;
	JSON_Object *conf = NULL;
	JSON_Value *val;
	uint32_t sf, bw;
	
	/* try to parse JSON */
	root_val = json_parse_file_with_comments(conf_file);
	root = json_value_get_object(root_val);
	if (root == NULL) {
		MSG("ERROR: %s id not a valid JSON file\n", conf_file);
		exit(EXIT_FAILURE);
	}
	conf = json_object_get_object(root, conf_obj);
	if (conf == NULL) {
		MSG("INFO: %s does not contain a JSON object named %s\n", conf_file, conf_obj);
		return -1;
	} else {
		MSG("INFO: %s does contain a JSON object named %s, parsing SX1301 parameters\n", conf_file, conf_obj);
	}

	/* set board configuration */
	memset(&boardconf, 0, sizeof boardconf); /* initialize configuration structure */
	val = json_object_get_value(conf, "lorawan_public"); /* fetch value (if possible) */
	if (json_value_get_type(val) == JSONBoolean) {
		boardconf.lorawan_public = (bool)json_value_get_boolean(val);
	} else {
		MSG("WARNING: Data type for lorawan_public seems wrong, please check\n");
		boardconf.lorawan_public = false;
	}
	val = json_object_get_value(conf, "clksrc"); /* fetch value (if possible) */
	if (json_value_get_type(val) == JSONNumber) {
		boardconf.clksrc = (uint8_t)json_value_get_number(val);
	} else {
		MSG("WARNING: Data type for clksrc seems wrong, please check\n");
		boardconf.clksrc = 0;
	}
	MSG("INFO: lorawan_public %d, clksrc %d\n", boardconf.lorawan_public, boardconf.clksrc);
	/* all parameters parsed, submitting configuration to the HAL */
        if (lgw_board_setconf(boardconf) != LGW_HAL_SUCCESS) {
                MSG("WARNING: Failed to configure board\n");
	}

	/* set configuration for RF chains */
	for (i = 0; i < LGW_RF_CHAIN_NB; ++i) {
		memset(&rfconf, 0, sizeof(rfconf)); /* initialize configuration structure */
		sprintf(param_name, "radio_%i", i); /* compose parameter path inside JSON structure */
		val = json_object_get_value(conf, param_name); /* fetch value (if possible) */
		if (json_value_get_type(val) != JSONObject) {
			MSG("INFO: no configuration for radio %i\n", i);
			continue;
		}
		/* there is an object to configure that radio, let's parse it */
		sprintf(param_name, "radio_%i.enable", i);
		val = json_object_dotget_value(conf, param_name);
		if (json_value_get_type(val) == JSONBoolean) {
			rfconf.enable = (bool)json_value_get_boolean(val);
		} else {
			rfconf.enable = false;
		}
		if (rfconf.enable == false) { /* radio disabled, nothing else to parse */
			MSG("INFO: radio %i disabled\n", i);
		} else  { /* radio enabled, will parse the other parameters */
			snprintf(param_name, sizeof param_name, "radio_%i.freq", i);
			rfconf.freq_hz = (uint32_t)json_object_dotget_number(conf, param_name);
			snprintf(param_name, sizeof param_name, "radio_%i.rssi_offset", i);
			rfconf.rssi_offset = (float)json_object_dotget_number(conf, param_name);
			snprintf(param_name, sizeof param_name, "radio_%i.type", i);
			str = json_object_dotget_string(conf, param_name);
			if (!strncmp(str, "SX1255", 6)) {
				rfconf.type = LGW_RADIO_TYPE_SX1255;
			} else if (!strncmp(str, "SX1257", 6)) {
				rfconf.type = LGW_RADIO_TYPE_SX1257;
			} else {
				MSG("WARNING: invalid radio type: %s (should be SX1255 or SX1257)\n", str);
			}
			snprintf(param_name, sizeof param_name, "radio_%i.tx_enable", i);
			val = json_object_dotget_value(conf, param_name);
			if (json_value_get_type(val) == JSONBoolean) {
				rfconf.tx_enable = (bool)json_value_get_boolean(val);
			} else {
				rfconf.tx_enable = false;
			}
			MSG("INFO: radio %i enabled (type %s), center frequency %u, RSSI offset %f, tx enabled %d\n", i, str, rfconf.freq_hz, rfconf.rssi_offset, rfconf.tx_enable);
		}
		/* all parameters parsed, submitting configuration to the HAL */
		if (lgw_rxrf_setconf(i, rfconf) != LGW_HAL_SUCCESS) {
			MSG("WARNING: invalid configuration for radio %i\n", i);
		}
	}
	
	/* set configuration for LoRa multi-SF channels (bandwidth cannot be set) */
	for (i = 0; i < LGW_MULTI_NB; ++i) {
		memset(&ifconf, 0, sizeof(ifconf)); /* initialize configuration structure */
		sprintf(param_name, "chan_multiSF_%i", i); /* compose parameter path inside JSON structure */
		val = json_object_get_value(conf, param_name); /* fetch value (if possible) */
		if (json_value_get_type(val) != JSONObject) {
			MSG("INFO: no configuration for LoRa multi-SF channel %i\n", i);
			continue;
		}
		/* there is an object to configure that LoRa multi-SF channel, let's parse it */
		sprintf(param_name, "chan_multiSF_%i.enable", i);
		val = json_object_dotget_value(conf, param_name);
		if (json_value_get_type(val) == JSONBoolean) {
			ifconf.enable = (bool)json_value_get_boolean(val);
		} else {
			ifconf.enable = false;
		}
		if (ifconf.enable == false) { /* LoRa multi-SF channel disabled, nothing else to parse */
			MSG("INFO: LoRa multi-SF channel %i disabled\n", i);
		} else  { /* LoRa multi-SF channel enabled, will parse the other parameters */
			sprintf(param_name, "chan_multiSF_%i.radio", i);
			ifconf.rf_chain = (uint32_t)json_object_dotget_number(conf, param_name);
			sprintf(param_name, "chan_multiSF_%i.if", i);
			ifconf.freq_hz = (int32_t)json_object_dotget_number(conf, param_name);
			// TODO: handle individual SF enabling and disabling (spread_factor)
			MSG("INFO: LoRa multi-SF channel %i enabled, radio %i selected, IF %i Hz, 125 kHz bandwidth, SF 7 to 12\n", i, ifconf.rf_chain, ifconf.freq_hz);
		}
		/* all parameters parsed, submitting configuration to the HAL */
		if (lgw_rxif_setconf(i, ifconf) != LGW_HAL_SUCCESS) {
			MSG("WARNING: invalid configuration for LoRa multi-SF channel %i\n", i);
		}
	}
	
	/* set configuration for LoRa standard channel */
	memset(&ifconf, 0, sizeof(ifconf)); /* initialize configuration structure */
	val = json_object_get_value(conf, "chan_Lora_std"); /* fetch value (if possible) */
	if (json_value_get_type(val) != JSONObject) {
		MSG("INFO: no configuration for LoRa standard channel\n");
	} else {
		val = json_object_dotget_value(conf, "chan_Lora_std.enable");
		if (json_value_get_type(val) == JSONBoolean) {
			ifconf.enable = (bool)json_value_get_boolean(val);
		} else {
			ifconf.enable = false;
		}
		if (ifconf.enable == false) {
			MSG("INFO: LoRa standard channel %i disabled\n", i);
		} else  {
			ifconf.rf_chain = (uint32_t)json_object_dotget_number(conf, "chan_Lora_std.radio");
			ifconf.freq_hz = (int32_t)json_object_dotget_number(conf, "chan_Lora_std.if");
			bw = (uint32_t)json_object_dotget_number(conf, "chan_Lora_std.bandwidth");
			switch(bw) {
				case 500000: ifconf.bandwidth = BW_500KHZ; break;
				case 250000: ifconf.bandwidth = BW_250KHZ; break;
				case 125000: ifconf.bandwidth = BW_125KHZ; break;
				default: ifconf.bandwidth = BW_UNDEFINED;
			}
			sf = (uint32_t)json_object_dotget_number(conf, "chan_Lora_std.spread_factor");
			switch(sf) {
				case  7: ifconf.datarate = DR_LORA_SF7;  break;
				case  8: ifconf.datarate = DR_LORA_SF8;  break;
				case  9: ifconf.datarate = DR_LORA_SF9;  break;
				case 10: ifconf.datarate = DR_LORA_SF10; break;
				case 11: ifconf.datarate = DR_LORA_SF11; break;
				case 12: ifconf.datarate = DR_LORA_SF12; break;
				default: ifconf.datarate = DR_UNDEFINED;
			}
			MSG("INFO: LoRa standard channel enabled, radio %i selected, IF %i Hz, %u Hz bandwidth, SF %u\n", ifconf.rf_chain, ifconf.freq_hz, bw, sf);
		}
		if (lgw_rxif_setconf(8, ifconf) != LGW_HAL_SUCCESS) {
			MSG("WARNING: invalid configuration for LoRa standard channel\n");
		}
	}
	
	/* set configuration for FSK channel */
	memset(&ifconf, 0, sizeof(ifconf)); /* initialize configuration structure */
	val = json_object_get_value(conf, "chan_FSK"); /* fetch value (if possible) */
	if (json_value_get_type(val) != JSONObject) {
		MSG("INFO: no configuration for FSK channel\n");
	} else {
		val = json_object_dotget_value(conf, "chan_FSK.enable");
		if (json_value_get_type(val) == JSONBoolean) {
			ifconf.enable = (bool)json_value_get_boolean(val);
		} else {
			ifconf.enable = false;
		}
		if (ifconf.enable == false) {
			MSG("INFO: FSK channel %i disabled\n", i);
		} else  {
			ifconf.rf_chain = (uint32_t)json_object_dotget_number(conf, "chan_FSK.radio");
			ifconf.freq_hz = (int32_t)json_object_dotget_number(conf, "chan_FSK.if");
			bw = (uint32_t)json_object_dotget_number(conf, "chan_FSK.bandwidth");
			if      (bw <= 7800)   ifconf.bandwidth = BW_7K8HZ;
			else if (bw <= 15600)  ifconf.bandwidth = BW_15K6HZ;
			else if (bw <= 31200)  ifconf.bandwidth = BW_31K2HZ;
			else if (bw <= 62500)  ifconf.bandwidth = BW_62K5HZ;
			else if (bw <= 125000) ifconf.bandwidth = BW_125KHZ;
			else if (bw <= 250000) ifconf.bandwidth = BW_250KHZ;
			else if (bw <= 500000) ifconf.bandwidth = BW_500KHZ;
			else ifconf.bandwidth = BW_UNDEFINED;
			ifconf.datarate = (uint32_t)json_object_dotget_number(conf, "chan_FSK.datarate");
			MSG("INFO: FSK channel enabled, radio %i selected, IF %i Hz, %u Hz bandwidth, %u bps datarate\n", ifconf.rf_chain, ifconf.freq_hz, bw, ifconf.datarate);
		}
		if (lgw_rxif_setconf(9, ifconf) != LGW_HAL_SUCCESS) {
			MSG("WARNING: invalid configuration for FSK channel\n");
		}
	}
	json_value_free(root_val);
	return 0;
}
示例#30
0
/**
 * @brief This parses configuration file such as (default.conf) and returns the instance of expr::ConfData class.
 */
expr::ConfData* expr::ConfigManager::parse_conf_json(std::string json_conf)
{
    json_object* jobj = NULL;
    json_object* confjobj = NULL;
    json_object* subjobj = NULL;

    char* payload = NULL;
    payload = g_strdup(json_conf.c_str());

    jobj = json_tokener_parse(payload);

    if((jobj == NULL) || is_error(jobj))
    {
        return NULL;
    }

    bool parsed = true;
    expr::error_type e_type = expr::CONFIG;
    expr::error_code e_code = expr::CONFIG_PARSE;

    if(!json_object_object_get_ex(jobj, "conf", &confjobj))
    {
        std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
        error_input_param->set_error_desc("cannot find conf");
        expr::ErrorMessagePool::getInstance()->add(error_input_param);

        parsed = false;
    }
    else
    {
        if(!json_object_object_get_ex(confjobj, "log_port", &subjobj))
        {
        }
        else
        {
            int port = json_object_get_int(subjobj);
            expr::ConfData::getInstance()->set_log_port(port);
        }

        if(!json_object_object_get_ex(confjobj, "control_port", &subjobj))
        {
        }
        else
        {
            int port = json_object_get_int(subjobj);
            expr::ConfData::getInstance()->set_ctl_port(port);
        }

        if(!json_object_object_get_ex(confjobj, "log_priority", &subjobj))
        {
            std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
            error_input_param->set_error_desc("cannot find log_priority");
            expr::ErrorMessagePool::getInstance()->add(error_input_param);
            parsed = false;
        }
        else
        {
            std::string priority(json_object_get_string(subjobj));
            expr::PRIORITY level = this->get_priority(priority);

            if(level == NOT_DEFINED)
            {
                std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
                error_input_param->set_error_desc("invalid Priority");
                expr::ErrorMessagePool::getInstance()->add(error_input_param);
                parsed = false;
            }
            else
            {
                expr::ConfData::getInstance()->set_log_priority(level);
            }
        }

        if(!json_object_object_get_ex(confjobj, "export_period", &subjobj))
        {
            std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
            error_input_param->set_error_desc("cannot find export_period");
            expr::ErrorMessagePool::getInstance()->add(error_input_param);
            parsed = false;
        }
        else
        {
            expr::ConfData::getInstance()->set_export_period(json_object_get_int(subjobj));
        }

        if(!json_object_object_get_ex(confjobj, "max_log_buffer_size", &subjobj))
        {
            std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
            error_input_param->set_error_desc("cannot find max_log_buffer_size");
            expr::ErrorMessagePool::getInstance()->add(error_input_param);
            parsed = false;
        }
        else
        {
            expr::ConfData::getInstance()->set_max_log_buffer_size(json_object_get_int(subjobj));
        }

        if(!json_object_object_get_ex(confjobj, "mapping", &subjobj))
        {
            std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
            error_input_param->set_error_desc("cannot find mapping");
            expr::ErrorMessagePool::getInstance()->add(error_input_param);
            parsed = false;
        }
        else
        {
            struct array_list* arr_obj;
            struct lh_entry* entry;

            arr_obj = json_object_get_array(subjobj);

            if(arr_obj == NULL)
            {
                std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
                error_input_param->set_error_desc("mapping list error");
                expr::ErrorMessagePool::getInstance()->add(error_input_param);
                parsed = false;
            }

            int arr_size = array_list_length(arr_obj);
            
            if(arr_size < 1)
            {
                std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
                error_input_param->set_error_desc("please set mapping table");
                expr::ErrorMessagePool::getInstance()->add(error_input_param);
                parsed = false;
            }

            json_object* arr_item = NULL;
            int arr_index;
            std::string key;
            std::string value;

            std::string ps_log_id;
            std::string log_d_id;
            std::string log_F_path;

            for(arr_index = 0; arr_index < arr_size; arr_index++)
            {
                arr_item = static_cast<json_object*>(array_list_get_idx(arr_obj, arr_index));
                entry = json_object_get_object(static_cast<struct json_object*>(arr_item))->head;

                ps_log_id.clear();
                log_d_id.clear();
                log_F_path.clear();

                while(entry)
                {
                    key.assign(static_cast<const char*>(entry->k));
                    value.assign(json_object_get_string((struct json_object*)entry->v));

                    if(key.compare("process_log_id") == 0)
                    {
                        ps_log_id = value;
                    }
                    else if(key.compare("log_file_id") == 0)
                    {
                        log_d_id = value;
                    }
                    else if(key.compare("log_file_path") == 0)
                    {
                        log_F_path = value;
                    }
                    else
                    {
                        std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
                        error_input_param->set_error_desc("Invalid key: " + key);
                        expr::ErrorMessagePool::getInstance()->add(error_input_param);
                        parsed = false;
                    }

                    entry = entry->next;
                } //while

                if(ps_log_id.empty())
                {
                    std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
                    error_input_param->set_error_desc("process_log_id key is NOT found at array[" + std::to_string(arr_index) + "]");
                    expr::ErrorMessagePool::getInstance()->add(error_input_param);
                    parsed = false;
                }

                if(log_d_id.empty())
                {
                    std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
                    error_input_param->set_error_desc("log_file_id key is NOT found at array[" + std::to_string(arr_index) + "]");
                    expr::ErrorMessagePool::getInstance()->add(error_input_param);
                    parsed = false;

                }

                if(log_F_path.empty())
                {
                    std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
                    error_input_param->set_error_desc("log_file_path key is NOT found at array[" + std::to_string(arr_index) + "]");
                    expr::ErrorMessagePool::getInstance()->add(error_input_param);
                    parsed = false;
                }

                if( (ps_log_id.empty() == false) && (log_d_id.empty() == false) && (log_F_path.empty() == false) )
                {
                    expr::ConfData::getInstance()->add_to_table(ps_log_id, log_d_id, log_F_path);
                }
            } //for
        }
    }

    if(jobj)
    {
        json_object_put(jobj);
    }
    
    if(payload)
    {
        g_free(payload);
        payload = NULL;
    }

    expr::ConfData::getInstance()->set_parsed(parsed);
    return expr::ConfData::getInstance();
}