コード例 #1
0
ファイル: capmc_resume.c プロジェクト: jwhite530/slurm
static bool _check_node_state(int nid, char *nid_str, char *state)
{
	bool node_state_ok = false;
	char *argv[10], *resp_msg;
	int i, nid_cnt, status = 0;
	uint32_t *nid_array;
	json_object *j;

	argv[0] = "capmc";
	argv[1] = "node_status";
	argv[2] = "-n";
	argv[3] = nid_str;
	argv[4] = NULL;
	resp_msg = _run_script(argv, &status);
	if (status != 0) {
		error("%s: capmc(%s,%s,%s): %d %s", log_file,
			argv[1], argv[2], argv[3], status, resp_msg);
	}
	j = json_tokener_parse(resp_msg);
	if (j == NULL) {
		error("%s: json parser failed on %s", log_file, resp_msg);
		xfree(resp_msg);
		return node_state_ok;
	}
	xfree(resp_msg);

	nid_cnt = 0;
	nid_array = _json_parse_nids(j, "off", &nid_cnt);
	json_object_put(j);	/* Frees json memory */
	for (i = 0; i < nid_cnt; i++) {
		if (nid_array[i] == nid) {
			node_state_ok = true;
			break;
		}
	}
	xfree(nid_array);

	return node_state_ok;
}
コード例 #2
0
ファイル: stat_file.cpp プロジェクト: ishida-w/map646
json_object* stat_file::get_jobj(){
   std::fstream fs;
   fs.open((dirname+"/"+filename).c_str(), std::ios::in);

   std::string stat, buf;

   while(fs && getline(fs, buf)){
      stat += buf;
   }

   json_object* jobj = json_tokener_parse(stat.c_str());

   if(is_error(jobj)){
      std::cout << "parse failed" << std::endl;
      return NULL;
   }

   fs.close();

   return jobj;

}
コード例 #3
0
ファイル: bot.cpp プロジェクト: timschwartz/metabot
    void bot::thread()
    {
        std::string message;

        while(!this->quit)
        {
            message = this->janus_servers[this->server]->read();
            if(message.size())
            {
                json_object *json_command = NULL, *temp = NULL;
                json_command = json_tokener_parse(message.c_str());

                std::string method;

                try
                {
                    if(!json_object_object_get_ex(json_command, "method", &temp))  throw "'method' not found in command: " + message;
                }
                catch(std::string e)
                {
                    output(e);
                    json_object_put(json_command);
                    json_object_put(temp);
                    return;
                }
                method = json_object_get_string(temp);

                json_object_put(json_command);
                json_object_put(temp);

                if(this->server_method[method] != NULL) (this->server_method[method])(this, message);
                else output("Unknown method " + method);
            }

            this->update_pos();
            usleep(200000);
        }
    }
コード例 #4
0
OSStatus ConfigIncommingJsonMessage( const char *input, mico_Context_t * const inContext )
{
  OSStatus err = kNoErr;
  json_object *new_obj;
  config_delegate_log_trace();

  new_obj = json_tokener_parse(input);
  require_action(new_obj, exit, err = kUnknownErr);
  config_delegate_log("Recv config object=%s", json_object_to_json_string(new_obj));
  mico_rtos_lock_mutex(&inContext->flashContentInRam_mutex);
  json_object_object_foreach(new_obj, key, val) {
    if(!strcmp(key, "Device Name")){
      strncpy(inContext->flashContentInRam.micoSystemConfig.name, json_object_get_string(val), maxNameLen);
    }else if(!strcmp(key, "RF power save")){
      inContext->flashContentInRam.micoSystemConfig.rfPowerSaveEnable = json_object_get_boolean(val);
    }else if(!strcmp(key, "MCU power save")){
      inContext->flashContentInRam.micoSystemConfig.mcuPowerSaveEnable = json_object_get_boolean(val);
    }else if(!strcmp(key, "Bonjour")){
      inContext->flashContentInRam.micoSystemConfig.bonjourEnable = json_object_get_boolean(val);
    }else if(!strcmp(key, "Connect SPP Server")){
      inContext->flashContentInRam.appConfig.remoteServerEnable = json_object_get_boolean(val);
    }else if(!strcmp(key, "SPP Server")){
      strncpy(inContext->flashContentInRam.appConfig.remoteServerDomain, json_object_get_string(val), 64);
    }else if(!strcmp(key, "SPP Server Port")){
      inContext->flashContentInRam.appConfig.remoteServerPort = json_object_get_int(val);
    }else if(!strcmp(key, "Baurdrate")){
      inContext->flashContentInRam.appConfig.USART_BaudRate = json_object_get_int(val);
    }
  }
  json_object_put(new_obj);
  mico_rtos_unlock_mutex(&inContext->flashContentInRam_mutex);

  inContext->flashContentInRam.micoSystemConfig.configured = allConfigured;
  MICOUpdateConfiguration(inContext);

exit:
  return err; 
}
コード例 #5
0
TEST(MeterOCRTesseract, basic_two_boxes_same_id)
{
	std::list<Option> options;
	options.push_back(Option("file", (char*)"tests/meterOCR/sensus_test1_nronly2.png"));
	ASSERT_THROW( MeterOCR m2(options), vz::VZException); // missing boundingboxes parameter
	struct json_object *jsa = json_tokener_parse("[{\"boundingboxes\":[{\"identifier\": \"id1\"},{\"identifier\": \"id1\"}]}]");
	ASSERT_TRUE(jsa!=0);
	options.push_back(Option("recognizer", jsa));
	json_object_put(jsa);
	MeterOCR m(options);

	ASSERT_EQ(SUCCESS, m.open());

	std::vector<Reading> rds;
	rds.resize(1);
	EXPECT_EQ(1, m.read(rds, 1));

	double value = rds[0].value();
	EXPECT_EQ(2.0*432, value);

	ASSERT_EQ(0, m.close());

}
コード例 #6
0
ファイル: ef-lib.c プロジェクト: Excito/easyfind-client
char* get_ip() {
    struct curl_data_st data;
    data.payload = malloc(1);
    data.size = 0;
    curl_easy_setopt(curl, CURLOPT_URL, IP_URL);
    curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&data);

    res = curl_easy_perform(curl);
    if ( res == CURLE_OK ) {
        json_object* jip = json_tokener_parse(data.payload);
        free(data.payload);
        char *r_ip = NULL;
        json_object_object_foreach(jip, key, val) {
            if (strcmp(key, "ip_address") == 0) {
                const char* ip = json_object_get_string(val);
                r_ip = malloc(strlen(ip)+1);
                strcpy(r_ip, ip);
            }
        }
        json_object_put(jip);
        return r_ip;
    } else {
コード例 #7
0
ファイル: util.cpp プロジェクト: kjmikkel/LonelyRunner
len_array read_json_file_array(char* filename) {
  std::string content = read_entire_file(filename);
  
  json_object * jobj = json_tokener_parse(content.c_str());
  
  int speed_number = 0;   
  int length = json_object_array_length(jobj);
  int* array = NULL;
  array = new int[length];
  
  json_object * jvalue;
  
  for (int index = 0; index < length; index++){
    jvalue = json_object_array_get_idx(jobj, index); /*Getting the array element at position index*/
    array[index] = json_object_get_int(jvalue); 
  }
  
  len_array result;
  result.array = array;
  result.len = length;

  return result;
}
コード例 #8
0
ファイル: main.c プロジェクト: i7otep9wka/sway
char *get_focused_output(int socketfd) {
	uint32_t len = 0;
	char *res = ipc_single_command(socketfd, IPC_GET_WORKSPACES, NULL, &len);
	json_object *workspaces = json_tokener_parse(res);

	int length = json_object_array_length(workspaces);
	json_object *workspace, *focused, *json_output;
	char *output = NULL;
	int i;
	for (i = 0; i < length; ++i) {
		workspace = json_object_array_get_idx(workspaces, i);
		json_object_object_get_ex(workspace, "focused", &focused);
		if (json_object_get_boolean(focused) == TRUE) {
			json_object_object_get_ex(workspace, "output", &json_output);
			output = strdup(json_object_get_string(json_output));
			break;
		}
	}

	json_object_put(workspaces);
	free(res);
	return output;
}
コード例 #9
0
ファイル: json.c プロジェクト: carrierwrt/easycwmp
int json_handle_deviceid(char *line)
{
	json_object *js_obj;
	char *param_name, *param_permission, *fault_code, *c;

	js_obj=json_tokener_parse(line);
	if (js_obj == NULL || is_error(js_obj) || json_object_get_type(js_obj) != json_type_object)
			return -1;

	cwmp_free_deviceid();

	c= json_common_get_string(js_obj, "product_class");
	cwmp->deviceid.product_class = c ? strdup(c) : c;
	c= json_common_get_string(js_obj, "serial_number");
	cwmp->deviceid.serial_number = c ? strdup(c) : c;
	c = json_common_get_string(js_obj, "manufacturer");
	cwmp->deviceid.manufacturer = c ? strdup(c) : c;
	c = json_common_get_string(js_obj, "oui");
	cwmp->deviceid.oui = c ? strdup(c) : c;

	json_object_put(js_obj);
	return 0;
}
コード例 #10
0
OSStatus getMVDOTARequestData(const char *input, MVDOTARequestData_t *OTAData)
{
  OSStatus err = kUnknownErr;
  json_object *new_obj;
  config_delegate_log_trace();
  new_obj = json_tokener_parse(input);
  require_action(new_obj, exit, err = kUnknownErr);
  config_delegate_log("Recv OTA request object=%s", json_object_to_json_string(new_obj));
  json_object_object_foreach(new_obj, key, val) {
    if(!strcmp(key, "login_id")){
      strncpy(OTAData->loginId, json_object_get_string(val), MAX_SIZE_LOGIN_ID);
    }
    else if(!strcmp(key, "dev_passwd")){
      strncpy(OTAData->devPasswd, json_object_get_string(val), MAX_SIZE_DEV_PASSWD);
    }
    else {
    }
  }
  json_object_put(new_obj);
  err = kNoErr;
exit:
  return err;
}
コード例 #11
0
/** 
 * @brief Checks if the message has subscription field with
 * subscribe=true
 * 
 * @param message
 * 
 * @retval true if has subscribe=true, false otherwise
 */
bool
LSMessageIsSubscription(LSMessage *message)
{
    bool ret = false;
    struct json_object *sub_object = NULL;
    const char *payload = LSMessageGetPayload(message);

    struct json_object *object = json_tokener_parse(payload);
    if (JSON_ERROR(object))
        goto exit;
   
    if (!json_object_object_get_ex(object, "subscribe", &sub_object) || JSON_ERROR(sub_object))
        goto exit;

    _LSErrorIfFail(json_object_get_type(sub_object) == json_type_boolean, NULL);
    
    ret = json_object_get_boolean(sub_object);

exit:
    if (!JSON_ERROR(object))
        json_object_put(object);
    return ret;
}
コード例 #12
0
ファイル: nss_lcmapsd.c プロジェクト: msalle/nss_lcmapsd
/**
 * Parses memory as lcmapsd json. Looks for a valid uid.
 * \return 1 when uid is found, otherwise 0
 */
static int _lcmapsd_parse_json(char *memory, uid_t *uid)    {
    struct json_object *obj,*cred_obj;
    int rc;

    /* Find lcmaps/mapping/posix object */
    if ( (obj=json_tokener_parse(memory)) &&
         (cred_obj=json_object_object_get(obj, "lcmaps")) &&
         (cred_obj=json_object_object_get(cred_obj, "mapping")) &&
         (cred_obj=json_object_object_get(cred_obj, "posix")) &&
	 (cred_obj=json_object_object_get(cred_obj, "uid")) &&
	 (cred_obj=json_object_object_get(cred_obj, "id")) &&
	 json_object_is_type(cred_obj,json_type_int) ) {
	/* uid found and is integer */
	*uid=json_object_get_int(cred_obj);
	rc=1;
    } else
	rc=0;

    /* Cleanup json data */
    json_object_put(obj);

    return rc;
}
コード例 #13
0
/*
 * Create a JSON object from already opened file descriptor.
 *
 * This function can be helpful, when you opened the file already,
 * e.g. when you have a temp file.
 * Note, that the fd must be readable at the actual position, i.e.
 * use lseek(fd, 0, SEEK_SET) before.
 */
struct json_object* json_object_from_fd(int fd)
{
  struct printbuf *pb;
  struct json_object *obj;
  char buf[JSON_FILE_BUF_SIZE];
  int ret;

  if(!(pb = printbuf_new())) {
    MC_ERROR("json_object_from_file: printbuf_new failed\n");
    return NULL;
  }
  while((ret = read(fd, buf, JSON_FILE_BUF_SIZE)) > 0) {
    printbuf_memappend(pb, buf, ret);
  }
  if(ret < 0) {
    MC_ERROR("json_object_from_fd: error reading fd %d: %s\n", fd, strerror(errno));
    printbuf_free(pb);
    return NULL;
  }
  obj = json_tokener_parse(pb->buf);
  printbuf_free(pb);
  return obj;
}
コード例 #14
0
ファイル: bot.cpp プロジェクト: timschwartz/metabot
        void user_moved(bot *b, std::string command)
        {
            std::string pos_string, dir_string;
            std::string userId;
            float x, y , z, d;

            json_object *json_command, *temp, *temp2, *temp3;
            json_command = json_tokener_parse(command.c_str());
            if(!json_object_object_get_ex(json_command, "data", &temp)) output("No data!\n" + command);

            if(!json_object_object_get_ex(temp, "userId", &temp2))  output("No userId\n" + command);
            userId = json_object_get_string(temp2);

            if(!json_object_object_get_ex(temp, "position", &temp2))  output("No position\n" + command);

            if(!json_object_object_get_ex(temp2, "pos", &temp3))  output("No pos\n" + command);
            pos_string = json_object_get_string(temp3);

            if(!json_object_object_get_ex(temp2, "dir", &temp3))  output("No dir\n" + command);
            dir_string = json_object_get_string(temp3);

            if(b->players[userId] == NULL)
            {
                metabot::avatar *new_av = new metabot::avatar();
                b->players[userId] = new_av;
                b->players[userId]->userId = userId;
            }

            b->players[userId]->pos = metabot::stofv(pos_string);
            b->players[userId]->dir = metabot::stofv(dir_string);
            b->players[userId]->last_update = time(0);

            json_object_put(json_command);
            json_object_put(temp);
            json_object_put(temp2);
            json_object_put(temp3);
        }
コード例 #15
0
ファイル: afb-api-dbus.c プロジェクト: Tarnyko/afb-daemon
/* callback when received answer */
static int api_dbus_client_on_reply(sd_bus_message *message, void *userdata, sd_bus_error *ret_error)
{
	int rc;
	struct dbus_memo *memo;
	const char *first, *second;
	uint8_t type;
	uint32_t flags;

	/* retrieve the recorded data */
	memo = userdata;

	/* get the answer */
	rc = sd_bus_message_read(message, "yssu", &type, &first, &second, &flags);
	if (rc < 0) {
		/* failing to have the answer */
		afb_req_fail(memo->req, "error", "dbus error");
	} else {
		/* report the answer */
		memo->context->flags = (unsigned)flags;
		switch(type) {
		case RETOK:
			afb_req_success(memo->req, json_tokener_parse(first), second);
			break;
		case RETERR:
			afb_req_fail(memo->req, first, second);
			break;
		case RETRAW:
			afb_req_send(memo->req, first, strlen(first));
			break;
		default:
			afb_req_fail(memo->req, "error", "dbus link broken");
			break;
		}
	}
	api_dbus_client_free_memo(memo);
	return 1;
}
コード例 #16
0
ファイル: capmc_resume.c プロジェクト: jwhite530/slurm
/* Wait for all identified computed nodes to enter "on" state */
static void _wait_all_nodes_on(void)
{
	char *argv[10], *resp_msg;
	int i, nid_cnt = 0, status = 0;
	json_object *j;
	uint32_t *nid_array;
	time_t start_time = time(NULL);

	while ((difftime(time(NULL), start_time) < (30 * 60)) &&
	       (bit_set_count(node_bitmap) > 0)) {
		sleep(20);
		argv[0] = "capmc";
		argv[1] = "node_status";
		argv[2] = NULL;
		resp_msg = _run_script(argv, &status);
		if (status != 0) {
			error("%s: capmc(%s,%s,%s): %d %s", log_file,
				argv[1], argv[2], argv[3], status, resp_msg);
			break;
		}
		j = json_tokener_parse(resp_msg);
		if (j == NULL) {
			error("%s: json parser failed on %s",
			      log_file, resp_msg);
			xfree(resp_msg);
			break;
		}
		xfree(resp_msg);
		nid_cnt = 0;
		nid_array = _json_parse_nids(j, "on", &nid_cnt);
		json_object_put(j);	/* Frees json memory */
		for (i = 0; i < nid_cnt; i++) {
			bit_clear(node_bitmap, nid_array[i]);
		}
		xfree(nid_array);
	}
}
コード例 #17
0
ファイル: luna_methods.c プロジェクト: Herrie82/lumberjack
//
// Run command to set Logging context level.
//
bool setLogging_method(LSHandle* lshandle, LSMessage *message, void *ctx) {
  LSError lserror;
  LSErrorInit(&lserror);

  // Local buffer to store the update command
  char command[MAXLINLEN];

  // Extract the context argument from the message
  json_object *object = json_tokener_parse(LSMessageGetPayload(message));
  json_object *context = json_object_object_get(object, "context");
  if (!context || !json_object_is_type(context, json_type_string) || (strspn(json_object_get_string(context), ALLOWED_CHARS) != strlen(json_object_get_string(context)))) {
    if (!LSMessageReply(lshandle, message,
			"{\"returnValue\": false, \"errorCode\": -1, \"errorText\": \"Invalid or missing context\"}",
			&lserror)) goto error;
    return true;
  }

  // Extract the level argument from the message
  json_object *level = json_object_object_get(object, "level");
  if (!level || (!json_object_is_type(level, json_type_string)) || (strspn(json_object_get_string(level), ALLOWED_CHARS) != strlen(json_object_get_string(level)))) {
    if (!LSMessageReply(lshandle, message,
			"{\"returnValue\": false, \"errorCode\": -1, \"errorText\": \"Invalid or missing level\"}",
			&lserror)) goto error;
    return true;
  }

  // Store the command, so it can be used in the error report if necessary
  sprintf(command, "PmLogCtl set %s %s 2>&1", json_object_get_string(context), json_object_get_string(level));
  
  return simple_command(lshandle, message, command);

 error:
  LSErrorPrint(&lserror, stderr);
  LSErrorFree(&lserror);
 end:
  return false;
}
コード例 #18
0
struct str_t* json_parse_file_list(const char *path, struct str_t* json_str, struct dci_state* state)
{
	struct json_object* json = json_tokener_parse(json_str->str);

	union func_u func;

	struct json_object* file;
	struct dc_entry_t *tmp = dci_last_entry(state);

	size_t count = 0;

	if(json != NULL) {
		int length = json_object_array_length(json);
		int i;


		for(i = 0; i < length; i++)
		{	
			file = json_object_array_get_idx(json, i);

			if(!tmp)
			{
				tmp = dc_entry_from_json(file);
				state->head = tmp;
			} 
			else
			{
				tmp->next = dc_entry_from_json(file);
				tmp = tmp->next;
			}
			++count;
		}
		state->num_files += count;

	}
	return NULL;
}
コード例 #19
0
ファイル: u1db_query.c プロジェクト: Kazade/Tasks
int
u1db__update_indexes(u1database *db, const char *doc_id, const char *content)
{
    struct evaluate_index_context context;
    int status;

    if (content == NULL) {
        // No new fields to add to the database.
        return U1DB_OK;
    }
    context.db = db;
    context.doc_id = doc_id;
    context.content = content;
    context.obj = json_tokener_parse(content);
    if (context.obj == NULL
            || !json_object_is_type(context.obj, json_type_object))
    {
        return U1DB_INVALID_JSON;
    }
    status = iter_field_definitions(db, &context,
            evaluate_index_and_insert_into_db);
    json_object_put(context.obj);
    return status;
}
コード例 #20
0
ファイル: bodhi.c プロジェクト: vrutkovs/abrt
static GHashTable *bodhi_query_list(const char *query, const char *release)
{
    char *bodhi_url_bugs = xasprintf("%s/list", bodhi_url);

    post_state_t *post_state = new_post_state(POST_WANT_BODY
                                              | POST_WANT_SSL_VERIFY
                                              | POST_WANT_ERROR_MSG);

    const char *headers[] = {
        "Accept: application/json",
        NULL
    };

    post_string(post_state, bodhi_url_bugs, "application/x-www-form-urlencoded",
                     headers, query);

    if (post_state->http_resp_code != 200)
    {
        char *errmsg = post_state->curl_error_msg;
        if (errmsg && errmsg[0])
            error_msg_and_die("%s '%s'", errmsg, bodhi_url_bugs);
    }
    free(bodhi_url_bugs);

//    log("%s", post_state->body);

    json_object *json = json_tokener_parse(post_state->body);
    if (is_error(json))
        error_msg_and_die("fatal: unable parse response from bodhi server");

    GHashTable *bodhi_table = bodhi_parse_json(json, release);
    json_object_put(json);
    free_post_state(post_state);

    return bodhi_table;
}
コード例 #21
0
ファイル: commands.c プロジェクト: jukkahonkela-owo/powerd
/** 
* @brief Helper that translates from jsonized message into form for use
*        with callback.
* 
* @param  sh 
* @param  message 
* @param  ctx 
* 
* @retval
*/
static bool
_ClientBatteryStatusCallback(LSHandle *sh, LSMessage *message, void *ctx)
{
    CBH *helper = (CBH *)ctx;
    if (!helper || !helper->callback) return true;

    const char *payload = LSMessageGetPayload(message);
    struct json_object *object = json_tokener_parse(payload);
    if (is_error(object)) {
     	goto end;
    }

    int percent;
    int temp_C;
    int current_mA;
    int voltage_mV;

    percent = json_object_get_int(
            json_object_object_get(object, "percent"));

    temp_C = json_object_get_int(
            json_object_object_get(object, "temperature_C"));

    current_mA = json_object_get_int(
            json_object_object_get(object, "current_mA"));

    voltage_mV = json_object_get_int(
            json_object_object_get(object, "voltage_mV"));

    ((PowerdCallback_Int32_4)helper->callback)
                (percent, temp_C, current_mA, voltage_mV);

end:
	if (!is_error(object)) json_object_put(object);
    return true;
}
コード例 #22
0
ファイル: Meteo.c プロジェクト: whoo/Meteo
size_t parsemeteo(struct MemoryStruct *ptr)
{
	json_object *new_obj,*list;

	if (!(new_obj = json_tokener_parse(ptr->memory))) return 0;

	list=json_object_object_get(new_obj,"list");

	for (int a=0;a<json_object_array_length(list);a++)
	{
		json_object *w,*m,*c1;

		c1=json_object_array_get_idx(list,a);

		// LIST[0]->name
		// LIST[0]->weather[0]->description
		// LIST[0]->main['temp']

		w=	json_object_array_get_idx(json_object_object_get(c1,"weather"),0);
		m= 	json_object_object_get(c1,"main");
		char *txt=malloc(100);
		sprintf(txt,"%s - %s : Temp %dC (min %d/max %d) %d %%\n",
				json_object_get_string(json_object_object_get(c1,"name")),
				json_object_get_string(json_object_object_get(w,"description")),
				json_object_get_int(json_object_object_get(m,"temp")),
				json_object_get_int(json_object_object_get(m,"temp_min")),
				json_object_get_int(json_object_object_get(m,"temp_max")),
				json_object_get_int(json_object_object_get(m,"humidity"))
		       );

		//	printf("%s",strupr(txt));
		printf("%s",Supper(txt));

	}
	return 0;
}
コード例 #23
0
ファイル: json.c プロジェクト: carrierwrt/easycwmp
int json_handle_set_parameter_value(char *line)
{
	json_object *js_obj;
	char *param_name, *fault_code, *status, *cfg_load;


	js_obj = json_tokener_parse(line);
	if (js_obj == NULL || is_error(js_obj) || json_object_get_type(js_obj) != json_type_object)
		return -1;

	if (status = json_common_get_string(js_obj, "status")) {
		cfg_load = json_common_get_string(js_obj, "config_load");
		if (cfg_load && atoi(cfg_load))
			cwmp->end_session |= ENDS_RELOAD_CONFIG;
		external_set_param_val_resp_status(status);
	}
	else {
		param_name = json_common_get_string(js_obj, "parameter");
		fault_code = json_common_get_string(js_obj, "fault_code");
		external_add_list_paramameter(param_name, NULL, NULL, fault_code);
	}
	json_object_put(js_obj);
	return 0;
}
コード例 #24
0
ファイル: uhost.c プロジェクト: pengxiaojun/ucloud-c-sdk
/* ---------------uhost instance--------------- */
int ucloud_uhost_terminate(const char *region, const char *host_id)
{
	ucloud_http_params_t *param;
	param = ucloud_http_params_init();
	if (param == NULL)
	{
		return UCLOUDE_ALLOC_MEMORY;
	}

	if (region == NULL || host_id == NULL)
	{
		return UCLOUDE_INVALID_PARAM;
	}
	ucloud_http_params_add(param, "Action", "TerminateUHostInstance");
	ucloud_http_params_add(param, "Region", region);
	ucloud_http_params_add(param, "UHostId", host_id);

	ucloud_uhttp_response_t *resp;
	resp = ucloud_uhttp_response_init();
	int ret = ucloud_uhttp_request(param, resp);
	if (ret != UCLOUDE_OK)
	{
		goto error;
	}

	//handle response
	json_object *jobj = json_tokener_parse(resp->result);
	ret = ucloud_uhttp_handle_resp_header(jobj);
	ucloud_http_params_deinit(param);
	ucloud_uhttp_response_deinit(resp);
	return ret == 0 ? UCLOUDE_OK : UCLOUDE_ERROR;
error:
	ucloud_http_params_deinit(param);
	ucloud_uhttp_response_deinit(resp);
	return UCLOUDE_ERROR;
}
コード例 #25
0
ファイル: stream_filter.c プロジェクト: GoCatalyst/simplehttp
/*
 * for each message.
 */
void process_message(const char *source)
{
    struct json_object *json_in, *element;
    const char *field_key, *raw_string, *json_out;
    char *encrypted_string;
    int i;
    
    json_in = json_tokener_parse(source);
    
    if (json_in == NULL) {
        msgFail++;
        if (verbose) {
            fprintf(stderr, "ERR: unable to parse json '%s'\n", source);
        }
        return;
    }
    
    // filter messages
    if (expected_value && !filter_message_simple(expected_key, expected_value, json_in)) {
        json_object_put(json_in);
        return;
    }
    
    // remove the blacklisted fields
    delete_fields(blacklisted_fields, num_blacklisted_fields, json_in);
    
    // fields we need to encrypt
    encrypt_fields(encrypted_fields, num_encrypted_fields, json_in);
    
    json_out = json_object_to_json_string(json_in);
    
    /* new line terminated */
    printf("%s\n", json_out);
    
    json_object_put(json_in);
}
コード例 #26
0
void ApplicationDescription::initializeFromData(const QString &data)
{
    struct json_object* root = json_tokener_parse( data.toUtf8().constData() );
    if( !root || is_error( root ) )
    {
        qWarning() << "Failed to parse application description";
        return;
    }

    fromJsonObject(root);

	struct json_object* label = json_object_object_get(root,"useLuneOSStyle");
	if (label && !(is_error(label))) {
		mUseLuneOSStyle = json_object_get_boolean(label);
	}

        label = json_object_object_get(root,"useWebEngine");
        if (label && !(is_error(label))) {
                mUseWebEngine = json_object_get_boolean(label);
        }

    if(root && !is_error(root))
        json_object_put(root);
}
コード例 #27
0
static size_t 
remotedb_curl( void *ptr, size_t size, size_t nmemb, void *userdata)
{
        REQUEST *request = (REQUEST *) userdata;
		
	json_object * jobj = json_tokener_parse(ptr);
	
	if ((int) jobj < 0) {
                printf("Invalid json\n");
		return nmemb * size;
	}

	struct json_object *jvlan;
	struct json_object *jpassword;
	
	if (json_object_get_type(jobj) != json_type_object) {
		printf("Wrong type in field\n");
		return nmemb * size;
	}
	
	if ((jvlan = json_object_object_get(jobj, "vlan")) == NULL) {
		printf("vlan field needed\n");
		return nmemb * size;
	}

	if ((jpassword = json_object_object_get(jobj, "password")) == NULL) {
		printf("password field needed\n");
		return nmemb * size;
	}

        remotedb_answer_builder(request, json_object_get_string(jpassword), json_object_get_string(jvlan));
        
	json_object_put(jobj);
	
	return nmemb * size;
}
コード例 #28
0
ファイル: format.c プロジェクト: OS2World/MM-SOUND-PM123
pa_bool_t pa_format_info_get_prop_string(pa_format_info *f, const char *key, char **v) {
    const char *str = NULL;
    json_object *o;

    pa_assert(f);
    pa_assert(key);
    pa_assert(v);

    str = pa_proplist_gets(f->plist, key), FALSE;
    if (!str)
        return FALSE;

    o = json_tokener_parse(str);
    pa_return_val_if_fail(!is_error(o), FALSE);
    if (json_object_get_type(o) != json_type_string) {
        json_object_put(o);
        return FALSE;
    }

    *v = pa_xstrdup(json_object_get_string(o));
    json_object_put(o);

    return TRUE;
}
コード例 #29
0
void *run_request_server(void * ){
	try{
		int server_sockfd, client_sockfd;
		socklen_t server_len, client_len;
		struct sockaddr_in server_address;
		struct sockaddr_in client_address;
		int result;
		fd_set readfds, testfds;

		// Create and name a socket for the server:
		server_sockfd = socket(AF_INET, SOCK_STREAM, 0);

		int on=1;
		setsockopt(server_sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

		server_address.sin_family = AF_INET;
		//server_address.sin_addr.s_addr = htonl(INADDR_ANY);
		server_address.sin_addr.s_addr = inet_addr(settings.request_ip.c_str());
		server_address.sin_port = htons(settings.request_port);
		server_len = sizeof(server_address);

		bind(server_sockfd, (struct sockaddr *)&server_address, server_len);

		//Create a connection queue and initialize readfds to handle input from server_sockfd:
		listen(server_sockfd, 5);

		FD_ZERO(&readfds);
		FD_SET(server_sockfd, &readfds);

		//Now wait for clients and requests. Because you have passed a null pointer as the timeout parameter, no timeout will occur. The program will exit and report an error if select returns a value less than 1:
		while(1) {
			int fd;
			int nread;
			testfds = readfds;

			debug("requestserver is waiting for connections");
			result = select(FD_SETSIZE, &testfds, (fd_set *)0, (fd_set *)0, (struct timeval *) 0);
//			debug("proxyfether done waiting");


			if(result < 1) {
				error_log("Error in requestserver.cpp : run");
				exit(1);
			}

			//Once you know you’ve got activity, you can find which descriptor it’s on by checking each in turn using FD_ISSET:
			for(fd = 0; fd < FD_SETSIZE; fd++) {
				if(FD_ISSET(fd,&testfds)) {

				//If the activity is on server_sockfd, it must be a request for a new connection, and you add the associated client_sockfd to the descriptor set:

					if(fd == server_sockfd) {
						debug("requestserver: new client - read");
						client_len = sizeof(client_address);
						client_sockfd = accept(server_sockfd,
						(struct sockaddr *)&client_address, &client_len);
						FD_SET(client_sockfd, &readfds);
						debug("requestserver: adding client on fd:"+toString(client_sockfd));

						//If it isn’t the server, it must be client activity. If close is received, the client has gone away, and you remove it from the descriptor set. Otherwise, you “serve” the client as in the previous examples.
					}else{
//						debug("old client - read");
						ioctl(fd, FIONREAD, &nread);
						if(nread == 0) {
							close(fd);
							FD_CLR(fd, &readfds);
							debug("requestserver: removing client on fd:"+toString(fd));
						}else{
							char buffer[100000]="";
							if (nread!=read(fd, &buffer, nread)){
								error_log("Error in requestserver.cpp : run_request_server(): Not all data has been read from proxy-fetcher-client");
							}
//							debug("serving client - read");
//							debug("serving client on fd"+toString(fd));
							string recv_msg=buffer;
//							error_log("Received a msg from the client:"+recv_msg);
//							char send_buffer[10]="";
							debug("trying to add distfile via requestserver");
							json_object* json_obj_distfile=json_tokener_parse(buffer);
							string distfile_name=json_object_get_string(json_object_object_get(json_obj_distfile,"name"));
							int result=proxy_fetcher_pkg.find_distfile(distfile_name);
							debug("search for distfile ended");
							switch (result){
								case R_PF_NOT_REQUESTED_YET:
								case R_PF_ERROR_ADDING_TO_PROXY_QUEUE: // if error - try with request_server
								{
									debug("Search in proxy_fetcher distfiles list");
									result=proxy_fetcher_pkg.find_distfile(distfile_name);
									debug("ENDED search in proxy_fetcher distfiles list");
									switch (result){
										case R_PF_NOT_REQUESTED_YET:{
											debug("push_back distfile to the queue");
											result=request_server_pkg.push_back_distfile(json_obj_distfile);
											break;
										}
										default: break;
									}
									break;
								}
								default: break;
							}
							debug("Ended trying to add distfile");
							string send_response=toString(result);
//							if (write(sockfd, send_buffer, strlen(send_buffer))!=(int)msg.length()){
							if (write(fd, send_response.c_str(), send_response.length())!=(int)send_response.length()){
								error_log("Error in requestserver.cpp: run_request_server(): response msg size and sent data size are different.");
							};
						}
					}
				}
			}
		}
	}catch(...){
		error_log("Error in requestserver.cpp: run_request_server()");
		return (void*)1;
	}
}
コード例 #30
0
ファイル: rpc.c プロジェクト: lynnard/RPC
int main(int argc, char *argv[])
{
    int channels_len;
    fm_channel_t* channels;
    if (read_channels(&channels, &channels_len) != 0) {
        printf("Failed to retrieve the channel list. Try again later.\n");
        return -1;
    }

    char *addr = "localhost";
    char *port = "10098";
    int c;

    while ((c = getopt(argc, argv, "a:p:")) != -1) {
        switch (c) {
            case 'a':
                addr = optarg;
                break;
            case 'p':
                port = optarg;
                break;
            default:
                break;
        }
    }

    char input_buf[64] = "";
    char output_format[512] = "";
    char output_buf[1024] = "";
    int buf_size;

    if (optind < argc) {
        strcpy(input_buf, argv[optind]);
        int i;
        char *buf = strcmp(input_buf, "info") == 0 ? output_format : input_buf;
        for (i = optind + 1; i < argc; i++) {
            strcat(buf, " ");
            strcat(buf, argv[i]);
        }
    } else {
        strcpy(input_buf, "info");
    }

    int open_webpage = 0;
    if (strcmp(input_buf, "channels") == 0) {
        print_channels(channels, channels_len);
        return 0;
    }
    else if (strcmp(input_buf, "help") == 0) {
        print_usage();
        return 0;
    }
    else if (strcmp(input_buf, "launch") == 0) {
        // forcefully restart RPD
        system("pgrep rpd && /usr/local/bin/rpc end && sleep 30; /usr/local/bin/rpd");
        return 0;
    } 
    else if (strncmp(input_buf, "webpage", 7) == 0) {
        // client told to trigger a webpage
        strcpy(input_buf, "info");
        open_webpage = 1;
    }

    struct addrinfo hints, *results, *p;
    int sock_fd;

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;

    if (getaddrinfo(addr, port, &hints, &results) != 0) {
        return -1;
    }

    for (p = results; p != NULL; p = p->ai_next) {
        sock_fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
        if (sock_fd < 0) {
            continue;
        }
        if (connect(sock_fd, p->ai_addr, p->ai_addrlen) == 0) {
            break;
        }
        close(sock_fd);
    }
    if (p == NULL) {
        perror("connect");
        return -1;
    }

    freeaddrinfo(results);

    send(sock_fd, input_buf, strlen(input_buf), 0);
    buf_size = recv(sock_fd, output_buf, sizeof(output_buf), 0);
    if (buf_size == 0) {
        close(sock_fd);
        return 0;
    }
    output_buf[buf_size] = '\0';
    close(sock_fd);

    json_object *obj = json_tokener_parse(output_buf);
    char *status = obj ? strdup(json_object_get_string(json_object_object_get(obj, "status"))) : "error", 
         *channel = "", *artist = "", *title = "", pos[16] = "", len[16] = "", kbps[8] = "", *album = "", *cover = "", year[8] = "", *douban_url = "", *like = "";
    if (strcmp(status, "error") != 0) {
        char *chl = strdup(json_object_get_string(json_object_object_get(obj, "channel")));
        long int cid;
        if (strcmp(chl, LOCAL_CHANNEL) == 0) {
            channel = get_local_channel_name();
        } else if (strcmp(chl, JING_TOP_CHANNEL) == 0) {
            channel = JING_TOP_CHANNEL_NAME;
        } else if (strcmp(chl, JING_PSN_CHANNEL) == 0) {
            channel = JING_PSN_CHANNEL_NAME;
        } else {
            // determining if it is an integer number
            char *address;
            cid = strtol(chl, &address, 10);
            if (*address == '\0') {
                // this is valid number
                // loop through the array to get the correct name for the channel
                int i;
                for (i=0; i<channels_len; i++) {
                    if (channels[i].id == cid) {
                        channel = channels[i].name;
                        break;
                    }
                }
                if (channel[0] == '\0') {
                    channel = "未知兆赫";
                }
            } else {
                channel = chl;
            }
        }
        sprintf(kbps, "%d", json_object_get_int(json_object_object_get(obj, "kbps")));
        if (strcmp(status, "stop") != 0) {
            time_str(json_object_get_int(json_object_object_get(obj, "pos")), pos);
            time_str(json_object_get_int(json_object_object_get(obj, "len")), len);
            like = json_object_get_int(json_object_object_get(obj, "like")) ? "1" : "0";
            artist = strdup(json_object_get_string(json_object_object_get(obj, "artist")));
            title = strdup(json_object_get_string(json_object_object_get(obj, "title")));
            album = strdup(json_object_get_string(json_object_object_get(obj, "album")));
            sprintf(year, "%d", json_object_get_int(json_object_object_get(obj, "year")));
            cover = strdup(json_object_get_string(json_object_object_get(obj, "cover")));
            douban_url = strdup(json_object_get_string(json_object_object_get(obj, "url")));
        }
    }

    if (output_format[0] == '\0') {
        if (strcmp(status, "error") == 0) {
            if (obj)
                printf("%s\n", json_object_get_string(json_object_object_get(obj, "message")));
            else
                printf("Unkown error with buf content %s\n", output_buf);
        } else if (open_webpage) {
            // open the designated webpage
            char sh[1280];
            // the url can become rather long after escaping
            char url[1024];
            if (escapesh(url, douban_url)[0] == '\0') {
                // we need to make a custom url to open
                sprintf(url, "%s %s", artist, album);
                // first obtain a curl instance to escape the query
                CURL *curl = curl_easy_init();
                char *st = curl_easy_escape(curl, url, 0);
                sprintf(url, "https://music.douban.com/subject_search?search_text=%s&cat=1003", st);
                curl_free(st);
                curl_easy_cleanup(curl);
            }
            /* printf("url is %s\n", url); */
            sprintf(sh, "%s $'%s' &", "$BROWSER", url);
            /* printf("cmd is %s\n", sh); */
            system(sh);
        } else {
            printf("RPD %s - %s / %s kbps\n", strcmp(status, "play") == 0? "Playing": (strcmp(status, "pause") == 0? "Paused": "Stopped"), channel, kbps);

            if (strcmp(status, "stop") != 0) {
                printf("%s%s - %s\n%s / %s\n", 
                        like[0] == '1' ? "[Like] ": "", artist, title, 
                        pos, len);
            }
        }
    } else {
        char info[1024], *arg = "";
        int l = strlen(output_format) + 1;
        // we must print out the information the user wants
        // trim the space in front 
        int i = 1, pi = 0;
        while ( i < l) {
            char ch = output_format[i++];
            if (i < l - 1 && ch == '%') {
                char spec = output_format[i++];
                switch (spec) {
                    case 'a': arg = artist; break;
                    case 't': arg = title; break;
                    case 'b': arg = album; break;
                    case 'y': arg = year; break;
                    case 'i': arg = cover; break;
                    case 'd': arg = douban_url; break;
                    case 'c': arg = channel; break;
                    case 'p': arg = pos; break;
                    case 'l': arg = len; break;
                    case 'u': arg = status; break;
                    case 'k': arg = kbps; break;
                    case 'r': arg = like; break;
                    case '%': arg = "%%"; break;
                    default: 
                        printf("Unknown specifier %c. Try help\n", spec);
                        return 1;
                }
                // loop through the arg and copy the chars
                while (*arg != '\0') {
                    info[pi++] = *arg;
                    arg++;
                }
            } else 
                info[pi++] = ch;
        }
        printf(info);
    }
    json_object_put(obj);
    // free the channel list
    free_channels(channels, channels_len);

    return 0;
}