コード例 #1
0
ファイル: parseJSON.c プロジェクト: samarkanov/gsoc13
Analogsignal*
parseJSON(char* responseGnode){
	yajl_val node;
    char errbuf[1024];

    node = yajl_tree_parse((const char *) responseGnode, errbuf, sizeof(errbuf));

    const char * path[] = { "selected", 0 };
    yajl_val v = yajl_tree_get(node, path, yajl_t_array);
    yajl_val node2 = YAJL_GET_ARRAY(v)->values[0];

    const char * path2[] = { "permalink", 0 };
    yajl_val v2 = yajl_tree_get(node2, path2, yajl_t_string);
    // if (v2) printf("%s: %s\n", path2[0], YAJL_GET_STRING(v2));

    yajl_val node3 = YAJL_GET_OBJECT(v2);
    const char * path3[] = { "fields", 0 };
    yajl_val v3 = yajl_tree_get(node2, path3, yajl_t_object);

    const char * path4[] = { "description", 0 };
    yajl_val v4 = yajl_tree_get(v3, path4, yajl_t_string);

    Analogsignal *analog = (Analogsignal *)malloc(sizeof(Analogsignal));
    
    strcpy (analog->permalink, YAJL_GET_STRING(v2));
    strcpy (analog->description, YAJL_GET_STRING(v4));

    yajl_tree_free(node);

	return analog;
}
コード例 #2
0
bson* bson_from_json_str(const char* str)
{
    yajl_val root;
    char* errbuf;
    bson *b;

    errbuf = malloc( sizeof(char) * 1024 );
    root = yajl_tree_parse( str, errbuf, 1024 );

    if( !root )
    {
        puts( "Parse error: " );
        if( strlen( errbuf ) )
            puts( errbuf );
        else
            puts( "unknown error." );

        yajl_tree_free( root );
        free( errbuf );
        return NULL;
    }

    free( errbuf );

    assert( YAJL_IS_OBJECT( root ) );

    b = malloc( sizeof( bson ) );
    bson_init( b );
    bson_from_json_object( b, root );
    bson_finish( b );

    yajl_tree_free( root );
    return b;
}
コード例 #3
0
ファイル: etcd-api.c プロジェクト: jdoliner/etcd-api
size_t
parse_watch_response (void *ptr, size_t size, size_t nmemb, void *stream)
{
        yajl_val                node;
        yajl_val                value;
        etcd_watch_t            *watch  = stream;
        static const char       *i_path[] = { "node", "modifiedIndex", NULL };
        static const char       *k_path[] = { "node", "key", NULL };
        static const char       *v_path[] = { "node", "value", NULL };

        node = yajl_tree_parse(ptr,NULL,0);
        if (node) {
                value = my_yajl_tree_get(node,i_path,yajl_t_number);
                if (value) {
                        watch->index_out = strtoul(YAJL_GET_NUMBER(value),
                                                   NULL,10);
                }
                value = my_yajl_tree_get(node,k_path,yajl_t_string);
                if (value) {
                        watch->key = strdup(MY_YAJL_GET_STRING(value));
                }
                value = my_yajl_tree_get(node,v_path,yajl_t_string);
                if (value) {
                        watch->value = strdup(MY_YAJL_GET_STRING(value));
                }
        }

        return size*nmemb;
}
コード例 #4
0
ファイル: etcd-api.c プロジェクト: jdoliner/etcd-api
size_t
parse_get_response (void *ptr, size_t size, size_t nmemb, void *stream)
{
        yajl_val        node;
        yajl_val        value;

        node = yajl_tree_parse(ptr,NULL,0);
        if (node) {
                value = my_yajl_tree_get(node,value_path,yajl_t_string);
                if (value) {
                        /* 
                         * YAJL probably copied it once, now we're going to
                         * copy it again.  If anybody really cares for such
                         * small and infrequently used values, we'd have to do
                         * do something much more complicated (like using the
                         * stream interface) to avoid the copy.  Right now it's
                         * just not worth it.
                         */
                        *((char **)stream) = strdup(MY_YAJL_GET_STRING(value));
                }
                else {
                        /* Might as well try this. */
                        *((char **)stream) = parse_array_response(node);
                }
                yajl_tree_free(node);
        }

        return size*nmemb;
}
コード例 #5
0
TEST_F(Yajl, yajl_tree_parse) {
	for (size_t i = 0; i < kTrialCount; i++) {
		yajl_val root = yajl_tree_parse(json_, NULL, 0);
		ASSERT_TRUE(root != NULL);
		yajl_tree_free(root);
	}
}
コード例 #6
0
ファイル: server.c プロジェクト: bitcars/amble-gps
/* 
 * Parse the json package
 */
int parse_gps_json(const char * buffer, struct gps_package * data) {
    yajl_val node;
    char errbuf[1024];

    /* null plug buffers */
    errbuf[0] = 0;

    /* we have the whole config file in memory.  let's parse it ... */
    node = yajl_tree_parse((const char *) buffer, errbuf, sizeof(errbuf));

    /* parse error handling */
    /*if (node == NULL) {
        fprintf(stderr, "parse_error: ");
        if (strlen(errbuf)) fprintf(stderr, " %s", errbuf);
        else fprintf(stderr, "unknown error");
        fprintf(stderr, "\n");
        return 0;
    }*/

    /* ... and extract a nested value from the json file */
    {
        const char * lat_path[] = { "lat", (const char *) 0 };
        const char * lon_path[] = { "lon", (const char *) 0 };
        yajl_val lat = yajl_tree_get(node, lat_path, yajl_t_number);
        yajl_val lon = yajl_tree_get(node, lon_path, yajl_t_number);
        if (lat) data->lat = YAJL_GET_DOUBLE(lat);
        else return 0;
        if (lon) data->lon = YAJL_GET_DOUBLE(lon);
        else return 0;
    }

    yajl_tree_free(node);

    return 1;
}
コード例 #7
0
ファイル: i3-exec-wait.c プロジェクト: drbig/i3-exec-wait
/*
 * Get the window ID from the JSON response.
 * Returns a signed long integer.
 *
 */
long get_window_id(char *json) {
  const char *path[] = { "container", "window", (const char *) 0 };
  yajl_val node;
  char errbuf[1024];
  long window_id;

  if ((node = yajl_tree_parse((const char *) json, errbuf, sizeof(errbuf))) == NULL) {
    dbg(if (strlen(errbuf)) fprintf(stderr, "%s", errbuf));
    die("JSON response parse error");
  }
コード例 #8
0
ファイル: JSONParser.cpp プロジェクト: Silex/rtags
bool JSONParser::parse(const String& json)
{
    char errbuf[128];
    yajl_val value = yajl_tree_parse(json.constData(), errbuf, sizeof(errbuf));
    if (!value) {
        mRoot = Value(); // just in case
        return false;
    }
    mRoot = yajlValueToValue(value);
    yajl_tree_free(value);
    return isValid();
}
コード例 #9
0
ファイル: ovs.c プロジェクト: collectd/collectd
/* Handle JSON data (one request) and call
 * appropriate event OVS DB handler. Currently,
 * update callback 'ovs_db_table_update_cb' and
 * result callback 'ovs_db_result_cb' is supported.
 */
static int ovs_db_json_data_process(ovs_db_t *pdb, const char *data,
                                    size_t len) {
  const char *method = NULL;
  char yajl_errbuf[OVS_YAJL_ERROR_BUFFER_SIZE];
  const char *method_path[] = {"method", NULL};
  const char *result_path[] = {"result", NULL};
  char *sjson = NULL;
  yajl_val jnode, jval;

  /* duplicate the data to make null-terminated string
   * required for yajl_tree_parse() */
  if ((sjson = calloc(1, len + 1)) == NULL)
    return -1;

  sstrncpy(sjson, data, len + 1);
  OVS_DEBUG("[len=%" PRIsz "] %s", len, sjson);

  /* parse json data */
  jnode = yajl_tree_parse(sjson, yajl_errbuf, sizeof(yajl_errbuf));
  if (jnode == NULL) {
    OVS_ERROR("yajl_tree_parse() %s", yajl_errbuf);
    sfree(sjson);
    return -1;
  }

  /* get method name */
  if ((jval = yajl_tree_get(jnode, method_path, yajl_t_string)) != NULL) {
    if ((method = YAJL_GET_STRING(jval)) == NULL) {
      yajl_tree_free(jnode);
      sfree(sjson);
      return -1;
    }
    if (strcmp("echo", method) == 0) {
      /* echo request from the server */
      if (ovs_db_table_echo_cb(pdb, jnode) < 0)
        OVS_ERROR("handle echo request failed");
    } else if (strcmp("update", method) == 0) {
      /* update notification */
      if (ovs_db_table_update_cb(pdb, jnode) < 0)
        OVS_ERROR("handle update notification failed");
    }
  } else if ((jval = yajl_tree_get(jnode, result_path, yajl_t_any)) != NULL) {
    /* result notification */
    if (ovs_db_result_cb(pdb, jnode) < 0)
      OVS_ERROR("handle result reply failed");
  } else
    OVS_ERROR("connot find method or result failed");

  /* release memory */
  yajl_tree_free(jnode);
  sfree(sjson);
  return 0;
}
コード例 #10
0
ファイル: request.c プロジェクト: ihrwein/webhdfs
yajl_val webhdfs_req_json_response (webhdfs_req_t *req) {
    char err[1024];
    yajl_val node;

    if (req->buffer.size == 0)
        return(NULL);

    if ((node = yajl_tree_parse(req->buffer.blob, err, sizeof(err))) == NULL)
        fprintf(stderr, "response-parse: %s\n", err);

    return(node);
}
コード例 #11
0
ファイル: json.cpp プロジェクト: bluemarvin/webrtc-player
JSONParser::JSONParser(const char* data) : mState(NULL)
{
  const int errorSize = 1024;
  char error[errorSize];
  mState = new State;

  mState->mTree = yajl_tree_parse(data, error, errorSize);

  if (!mState->mTree) {
    mState->mValid = false;
    mState->mError = error;
  }
}
コード例 #12
0
ファイル: utils.c プロジェクト: lclc/mcu
void utils_decrypt_report(const char *report)
{
    int decrypt_len;
    char *dec;

    memset(decrypted_report, 0, sizeof(decrypted_report));

    yajl_val json_node = yajl_tree_parse(report, NULL, 0);

    if (!json_node) {
        strcpy(decrypted_report, "/* error: Failed to parse report. */");
        return;
    }

    size_t i, r = json_node->u.object.len;
    for (i = 0; i < r; i++) {
        const char *ciphertext_path[] = { cmd_str(CMD_ciphertext), (const char *) 0 };
        const char *echo_path[] = { "echo", (const char *) 0 };
        const char *ciphertext = YAJL_GET_STRING(yajl_tree_get(json_node, ciphertext_path,
                                 yajl_t_string));
        const char *echo = YAJL_GET_STRING(yajl_tree_get(json_node, echo_path, yajl_t_string));
        if (ciphertext) {
            dec = aes_cbc_b64_decrypt((const unsigned char *)ciphertext, strlens(ciphertext),
                                      &decrypt_len, PASSWORD_STAND);
            if (!dec) {
                strcpy(decrypted_report, "/* error: Failed to decrypt. */");
                goto exit;
            }

            sprintf(decrypted_report, "/* ciphertext */ %.*s", decrypt_len, dec);
            free(dec);
            goto exit;
        } else if (echo) {
            dec = aes_cbc_b64_decrypt((const unsigned char *)echo, strlens(echo), &decrypt_len,
                                      PASSWORD_VERIFY);
            if (!dec) {
                strcpy(decrypted_report, "/* error: Failed to decrypt echo. */");
                goto exit;
            }

            sprintf(decrypted_report, "/* echo */ %.*s", decrypt_len, dec);
            free(dec);
            goto exit;
        }
    }
    strcpy(decrypted_report, report);
exit:
    yajl_tree_free(json_node);
    return;
}
コード例 #13
0
ファイル: verify.c プロジェクト: v1ka5/mod_authn_persona
/*
 * process an assertion using the hosted verifier.
 *
 * TODO: local verification
 */
VerifyResult processAssertion(request_rec *r, const char *assertion)
{
  VerifyResult res = apr_pcalloc(r->pool, sizeof(struct _VerifyResult));
  yajl_val parsed_result = NULL;

  char *assertionResult = verifyAssertionRemote(r, (char*) assertion);

  if (assertionResult) {
    char errorBuffer[256];
    parsed_result = yajl_tree_parse(assertionResult, errorBuffer, 255);
    if (!parsed_result) {
      res->errorResponse = apr_psprintf(r->pool, jsonErrorResponse,
                                       "malformed payload", errorBuffer);
      return res;
    }
  } else {
    // XXX: verifyAssertionRemote should return specific error message.
    res->errorResponse = apr_psprintf(r->pool, jsonErrorResponse,
                                     "communication error", "can't contact verification server");
    return res;
  }

  char *parsePath[2];
  parsePath[0] = "email";
  parsePath[1] = NULL;
  yajl_val foundEmail = yajl_tree_get(parsed_result, (const char**)parsePath, yajl_t_string);

  if (!foundEmail) {
    res->errorResponse = apr_pstrdup(r->pool, assertionResult);
    return res;
  }

  parsePath[0] = "issuer";
  parsePath[1] = NULL;
  yajl_val identityIssuer = yajl_tree_get(parsed_result, (const char**)parsePath, yajl_t_string);

  if (!identityIssuer) {
    res->errorResponse = apr_pstrdup(r->pool, assertionResult);
    return res;
  }

  res->verifiedEmail = apr_pstrdup(r->pool, foundEmail->u.string);
  res->identityIssuer = apr_pstrdup(r->pool, identityIssuer->u.string);

  return res;
}
コード例 #14
0
ファイル: parse_config.c プロジェクト: phatmanace/kingsbridge
int
main(void)
{
	size_t rd;
	yajl_val node;
	char errbuf[1024];

	/* null plug buffers */
	fileData[0] = errbuf[0] = 0;

	/* read the entire config file */
	rd = fread((void*)fileData, 1, sizeof(fileData) - 1, stdin);

	/* file read error handling */
	if (rd == 0 && !feof(stdin)) {
		fprintf(stderr, "error encountered on file read\n");
		return 1;
	} else if (rd >= sizeof(fileData) - 1) {
		fprintf(stderr, "config file too big\n");
		return 1;
	}

	/* we have the whole config file in memory.  let's parse it ... */
	node = yajl_tree_parse((const char*)fileData, errbuf, sizeof(errbuf));

	/* parse error handling */
	if (node == NULL) {
		fprintf(stderr, "parse_error: ");
		if (strlen(errbuf)) fprintf(stderr, " %s", errbuf);
		else fprintf(stderr, "unknown error");
		fprintf(stderr, "\n");
		return 1;
	}

	/* ... and extract a nested value from the config file */
	{
		const char * path[] = { "Logging", "timeFormat", (const char*)0 };
		yajl_val v = yajl_tree_get(node, path, yajl_t_string);
		if (v) printf("%s/%s: %s\n", path[0], path[1], YAJL_GET_STRING(v));
		else printf("no such node: %s/%s\n", path[0], path[1]);
	}

	yajl_tree_free(node);

	return 0;
}
コード例 #15
0
ファイル: ldm.c プロジェクト: carriercomm/libguestfs
static yajl_val
parse_json (const char *json, const char *func)
{
  yajl_val tree;
  char parse_error[1024];

  if (verbose)
    fprintf (stderr, "%s: parsing json: %s\n", func, json);

  tree = yajl_tree_parse (json, parse_error, sizeof parse_error);
  if (tree == NULL) {
    reply_with_error ("parse error: %s",
                      strlen (parse_error) ? parse_error : "unknown error");
    return NULL;
  }

  /* Caller should free this by doing 'yajl_tree_free (tree);'. */
  return tree;
}
コード例 #16
0
ファイル: conf_mgr.c プロジェクト: yquant/ws-node
static yajl_val parse_config_file_()
{
  NULL;
  int len;
  char errbuf[1024];
  
  char *content = wsn_read_all(all_configs_.conf_file, &len);
  if (content == NULL) {
    wsn_report_err(WSN_ERR_READ_CONF_FILE, "Failed to read config file %s", all_configs_.conf_file);
    return NULL;
  }

  yajl_val js_configs = yajl_tree_parse(content, errbuf, sizeof(errbuf));
  if (js_configs == NULL) {
    wsn_report_err(WSN_ERR_PARSE_CONF_FILE, "Failed to parse config file %s, %s", all_configs_.conf_file, errbuf);
  }
  
  free(content);
  return js_configs;
}
コード例 #17
0
ファイル: yajl_utils.c プロジェクト: CliffsDover/cdogs-sdl
yajl_val YAJLReadFile(const char *filename)
{
	yajl_val node = NULL;
	char errbuf[1024];
	char *buf = ReadFile(filename);
	if (buf == NULL)
	{
		fprintf(stderr, "Error reading JSON file '%s'\n", filename);
		goto bail;
	}
	node = yajl_tree_parse(buf, errbuf, sizeof errbuf);
	if (node == NULL)
	{
		fprintf(stderr, "Error parsing font JSON '%s': %s\n", filename, errbuf);
		goto bail;
	}

bail:
	free(buf);
	return node;
}
コード例 #18
0
ファイル: parse.c プロジェクト: SvenDowideit/clearlinux
SEXP R_parse(SEXP x, SEXP bigint_as_char) {
    /* get data from R */
    const char* json = translateCharUTF8(asChar(x));
    const int bigint = asLogical(bigint_as_char);

    /* ignore BOM as suggested by RFC */
    if(json[0] == '\xEF' && json[1] == '\xBB' && json[2] == '\xBF'){
      warning("JSON string contains (illegal) UTF8 byte-order-mark!");
      json = json + 3;
    }

    /* parse json */
    char errbuf[1024];
    yajl_val node = yajl_tree_parse(json, errbuf, sizeof(errbuf));

    /* parser error */
    if (!node) {
      error(errbuf);
    }
    SEXP out = ParseValue(node, bigint);
    yajl_tree_free(node);
    return(out);
}
コード例 #19
0
ファイル: etcd-api.c プロジェクト: jdoliner/etcd-api
size_t
parse_set_response (void *ptr, size_t size, size_t nmemb, void *stream)
{
        yajl_val        node;
        yajl_val        value;
        etcd_result     res     = ETCD_PROTOCOL_ERROR;
        /*
         * Success responses contain prevValue and index.  Failure responses
         * contain errorCode and cause.  Among all these, index seems to be the
         * one we're most likely to need later, so look for that.
         */
        static const char       *path[] = { "node", "modifiedIndex", NULL };

        node = yajl_tree_parse(ptr,NULL,0);
        if (node) {
                value = my_yajl_tree_get(node,path,yajl_t_number);
                if (value) {
                        res = ETCD_OK;
                }
        }

        *((etcd_result *)stream) = res;
        return size*nmemb;
}
コード例 #20
0
	virtual void SetUp() {
		PerfTest::SetUp();
		root_ = yajl_tree_parse(json_, NULL, 0);
		ASSERT_TRUE(root_ != NULL);
	}
コード例 #21
0
ファイル: click_events.c プロジェクト: arthurzam/i3status
void* events_thread(void* args)
{
    char input[2048] = {0};
    char errbuf[1024] = {0};
    char* walker;

    yajl_val node;
    yajl_val val;
    char name[512], instance[512];
    int button, x, y;

    while(fgets(input, sizeof(input), stdin)) {
        walker = input;
        if(*walker == '[')
            walker++;
        if(*walker == '\0')
            continue;
        if(*walker == ',')
            walker++;

        node = yajl_tree_parse(walker, errbuf, sizeof(errbuf));
        if (node == NULL) {
            fprintf(stderr, "parse_error: ");
            if (strlen(errbuf)) fprintf(stderr, " %s", errbuf);
            else fprintf(stderr, "unknown error");
            fprintf(stderr, "\n");
            continue;
        }

        val = yajl_tree_get(node, events_paths[0], yajl_t_string);
        if(val && YAJL_IS_STRING(val))
            strncpy(name, val->u.string, 512);
        else
            name[0] = '\0';

        val = yajl_tree_get(node, events_paths[1], yajl_t_string);
        if(val && YAJL_IS_STRING(val))
            strncpy(instance, val->u.string, 512);
        else
            instance[0] = '\0';

        val = yajl_tree_get(node, events_paths[2], yajl_t_number);
        button = (val ? YAJL_GET_INTEGER(val) : -1);

        val = yajl_tree_get(node, events_paths[3], yajl_t_number);
        x = (val ? YAJL_GET_INTEGER(val) : -1);

        val = yajl_tree_get(node, events_paths[4], yajl_t_number);
        y = (val ? YAJL_GET_INTEGER(val) : -1);

        yajl_tree_free(node);

        if(strcmp(name, "volume") == 0) {
            char* mixer = strchr(instance, '.');
            if(mixer == NULL)
                continue;
            *(mixer++) = '\0';
            char* mixer_id = strchr(mixer, '.');
            if(mixer_id == NULL)
                continue;
            *(mixer_id++) = '\0';
            mouse_volume(button, instance, mixer, atoi(mixer_id));
        }
    }
    return NULL;
}
コード例 #22
0
ファイル: ovs.c プロジェクト: collectd/collectd
int ovs_db_send_request(ovs_db_t *pdb, const char *method, const char *params,
                        ovs_db_result_cb_t cb) {
  int ret = 0;
  yajl_gen_status yajl_gen_ret;
  yajl_val jparams;
  yajl_gen jgen;
  ovs_callback_t *new_cb = NULL;
  uint64_t uid;
  char uid_buff[OVS_UID_STR_SIZE];
  const char *req = NULL;
  size_t req_len = 0;
  struct timespec ts;

  /* sanity check */
  if (!pdb || !method || !params)
    return -1;

  if ((jgen = yajl_gen_alloc(NULL)) == NULL)
    return -1;

  /* try to parse params */
  if ((jparams = yajl_tree_parse(params, NULL, 0)) == NULL) {
    OVS_ERROR("params is not a JSON string");
    yajl_gen_clear(jgen);
    return -1;
  }

  /* generate method field */
  OVS_YAJL_CALL(yajl_gen_map_open, jgen);

  OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "method");
  OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, method);

  /* generate params field */
  OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "params");
  OVS_YAJL_CALL(ovs_yajl_gen_val, jgen, jparams);
  yajl_tree_free(jparams);

  /* generate id field */
  OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "id");
  uid = ovs_uid_generate();
  snprintf(uid_buff, sizeof(uid_buff), "%" PRIX64, uid);
  OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, uid_buff);

  OVS_YAJL_CALL(yajl_gen_map_close, jgen);

  if (cb) {
    /* register result callback */
    if ((new_cb = calloc(1, sizeof(*new_cb))) == NULL)
      goto yajl_gen_failure;

    /* add new callback to front */
    sem_init(&new_cb->result.sync, 0, 0);
    new_cb->result.call = cb;
    new_cb->uid = uid;
    ovs_db_callback_add(pdb, new_cb);
  }

  /* send the request */
  OVS_YAJL_CALL(yajl_gen_get_buf, jgen, (const unsigned char **)&req, &req_len);
  OVS_DEBUG("%s", req);
  if (!ovs_db_data_send(pdb, req, req_len)) {
    if (cb) {
      /* wait for result */
      clock_gettime(CLOCK_REALTIME, &ts);
      ts.tv_sec += OVS_DB_SEND_REQ_TIMEOUT;
      if (sem_timedwait(&new_cb->result.sync, &ts) < 0) {
        OVS_ERROR("%s() no replay received within %d sec", __FUNCTION__,
                  OVS_DB_SEND_REQ_TIMEOUT);
        ret = (-1);
      }
    }
  } else {
    OVS_ERROR("ovs_db_data_send() failed");
    ret = (-1);
  }

yajl_gen_failure:
  if (new_cb) {
    /* destroy callback */
    sem_destroy(&new_cb->result.sync);
    ovs_db_callback_remove(pdb, new_cb);
  }

  /* release memory */
  yajl_gen_clear(jgen);
  return (yajl_gen_ret != yajl_gen_status_ok) ? (-1) : ret;
}
コード例 #23
0
Map * LoadMap(char * map_info){

	yajl_val node;
	char errbuf[1024];
	short x,y;
	short i;

	Map * map = (Map *) malloc(sizeof(Map));


	//logger("Parsing packet from JSON message");

	node = yajl_tree_parse(( char *) map_info, errbuf, sizeof(errbuf));

	 if (node == NULL) {
	        fprintf(stderr,"parse_error: ");
	        if (strlen(errbuf)){
	        	fprintf(stderr," %s", errbuf);
	        }else{
	        	fprintf(stderr,"unknown error");
			}
	        fprintf(stderr,"\n");
	        return false;
	    }

	 const char * path[] = { "map_id", ( char *) 0 };

	 map->area_id = YAJL_GET_INTEGER(yajl_tree_get(node, path, yajl_t_number));

	 path[0] = "cell_size";
	 map->cell_size = YAJL_GET_INTEGER(yajl_tree_get(node, path, yajl_t_number));

	 path[0] = "x_cells";
	 map->x_cells = YAJL_GET_INTEGER(yajl_tree_get(node, path, yajl_t_number));

	 path[0] = "y_cells";
	 map->y_cells = YAJL_GET_INTEGER(yajl_tree_get(node, path, yajl_t_number));

	 map->cells = (Cell **) malloc(map->x_cells * sizeof(Cell *));
	 for (x = 0; x < map->x_cells; x++){
		 map->cells[x] = (Cell *) malloc(map->y_cells * sizeof(Cell));
	 }

	 path[0] = "cells";

	 for (x = 0; x < map->x_cells; x++)
		 for (y = 0; y < map->y_cells; y++){

			 map->cells[x][y].prob_location = 1;
			 map->cells[x][y].transition_cell = true;

			 yajl_val cell = YAJL_GET_ARRAY(YAJL_GET_ARRAY((yajl_tree_get(node,path, yajl_t_array)))->values[x])->values[y];

			 if (YAJL_IS_NUMBER(cell)){
				 map->cells[x][y].prob_location = YAJL_GET_INTEGER(YAJL_GET_ARRAY(YAJL_GET_ARRAY((yajl_tree_get(node,path, yajl_t_array)))->values[x])->values[y]);
			 	 map->cells[x][y].transition_cell = false;
			 }else if (YAJL_IS_NULL(cell)){
				 map->cells[x][y].transp.area_id = 0;
				 map->cells[x][y].transp.x_cell = 0;
				 map->cells[x][y].transp.y_cell = 0;
			 }else{
				 for (i = 0; i < YAJL_GET_OBJECT(cell)->len; i++){
					 if (!strcmp(YAJL_GET_OBJECT(cell)->keys[i], "area_id"))
						 map->cells[x][y].transp.area_id = YAJL_GET_INTEGER(YAJL_GET_OBJECT(cell)->values[i]);
					 else if (!strcmp(YAJL_GET_OBJECT(cell)->keys[i], "x_cell"))
						 map->cells[x][y].transp.x_cell = YAJL_GET_INTEGER(YAJL_GET_OBJECT(cell)->values[i]);
					 else if (!strcmp(YAJL_GET_OBJECT(cell)->keys[i], "y_cell"))
						 map->cells[x][y].transp.y_cell = YAJL_GET_INTEGER(YAJL_GET_OBJECT(cell)->values[i]);
				 }
			 }
		 }

	 return map;

}
コード例 #24
0
ファイル: curl.c プロジェクト: foss-teiwest/irc-bot
struct github *fetch_github_commits(yajl_val *root, const char *repo, int *commit_count) {

	CURL *curl;
	CURLcode code;
	yajl_val val;
	struct github *commits = NULL;
	struct mem_buffer mem = {NULL, 0};
	char API_URL[URLLEN], errbuf[1024];

	// Use per_page field to limit json reply to the amount of commits specified
	snprintf(API_URL, URLLEN, "https://api.github.com/repos/%s/commits?per_page=%d", repo, *commit_count);
	*commit_count = 0;

	curl = curl_easy_init();
	if (!curl)
		goto cleanup;

#ifdef TEST
	curl_easy_setopt(curl, CURLOPT_URL, getenv("IRCBOT_TESTFILE"));
#else
	curl_easy_setopt(curl, CURLOPT_URL, API_URL);
#endif
	curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
	curl_easy_setopt(curl, CURLOPT_USERAGENT, "irc-bot"); // Github requires a user-agent
	curl_easy_setopt(curl, CURLOPT_TIMEOUT, 8L);
	curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_memory);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &mem);

	code = curl_easy_perform(curl);
	if (code != CURLE_OK) {
		fprintf(stderr, "Error: %s\n", curl_easy_strerror(code));
		goto cleanup;
	}
	if (!mem.buffer) {
		fprintf(stderr, "Error: Body was empty");
		goto cleanup;
	}
	*root = yajl_tree_parse(mem.buffer, errbuf, sizeof(errbuf));
	if (!*root) {
		fprintf(stderr, "%s\n", errbuf);
		goto cleanup;
	}
	if (YAJL_IS_ARRAY(*root)) {
		*commit_count = YAJL_GET_ARRAY(*root)->len;
		commits = malloc_w(*commit_count * sizeof(*commits));
	}
	// Find the field we are interested in the json reply, save a reference to it & null terminate
	for (int i = 0; i < *commit_count; i++) {
		val = yajl_tree_get(YAJL_GET_ARRAY(*root)->values[i], CFG("sha"),                      yajl_t_string);
		if (!val) break;
		commits[i].sha  = YAJL_GET_STRING(val);

		val = yajl_tree_get(YAJL_GET_ARRAY(*root)->values[i], CFG("commit", "author", "name"), yajl_t_string);
		if (!val) break;
		commits[i].name = YAJL_GET_STRING(val);

		val = yajl_tree_get(YAJL_GET_ARRAY(*root)->values[i], CFG("commit", "message"),        yajl_t_string);
		if (!val) break;
		commits[i].msg  = YAJL_GET_STRING(val);
		null_terminate(commits[i].msg, '\n'); // Cut commit message at newline character if present

		val = yajl_tree_get(YAJL_GET_ARRAY(*root)->values[i], CFG("html_url"),                 yajl_t_string);
		if (!val) break;
		commits[i].url  = YAJL_GET_STRING(val);
	}
cleanup:
	free(mem.buffer);
	curl_easy_cleanup(curl);
	return commits;
}
コード例 #25
0
int maina(void)
{
    size_t rd;
    yajl_val node;
    char errbuf[1024];

    /* null plug buffers */
    fileData[0] = errbuf[0] = 0;

    /* read the entire config file */
    rd = fread((void *) fileData, 1, sizeof(fileData) - 1, stdin);

    /* file read error handling */
    if (rd == 0 && !feof(stdin)) {
        fprintf(stderr, "error encountered on file read\n");
        return 1;
    } else if (rd >= sizeof(fileData) - 1) {
        fprintf(stderr, "config file too big\n");
        return 1;
    }

    /* we have the whole config file in memory.  let's parse it ... */
    node = yajl_tree_parse((const char *) fileData, errbuf, sizeof(errbuf));

    /* parse error handling */
    if (node == NULL) {
        fprintf(stderr, "parse_error: ");
        if (strlen(errbuf)) fprintf(stderr, " %s", errbuf);
        else fprintf(stderr, "unknown error");
        fprintf(stderr, "\n");
        return 1;
    }

    /* ... and extract a nested value from the config file */
    {
	const char * path[] = { "wallet", (const char *) 0 };
        yajl_val v = yajl_tree_get(node, path, yajl_t_array);


	if(v) {
		yajl_val *objs = v->u.array.values;
		int i = 0;
		for(i; i < v->u.array.len; i++)
		{
			if(objs[i]) { /*A complete JSON object*/
				char **keys = objs[i]->u.object.keys; /*keys for JSON obj*/
				yajl_val *vals = objs[i]->u.object.values; /*values for JSON obj*/

				int j=0;
				for (j; j< objs[i]->u.object.len; j++) {
					printf("Object key : %s\n", keys[j]);
					if(YAJL_IS_INTEGER(vals[j])) {
						printf("Object value : %lli\n", YAJL_GET_INTEGER(vals[j]));
					}else if(YAJL_IS_DOUBLE(vals[j])) {
						printf("Object value : %lf\n", YAJL_GET_DOUBLE(vals[j]));
					}
					else {
						printf("Object value : %s\n", YAJL_GET_STRING(vals[j]));
					}
				}		
				
			}
		}
	}       
    }

    yajl_tree_free(node);

    return 0;
}