Ejemplo n.º 1
0
static void encode_nul_byte()
{
    json_t *json;
    char *result;

    json = json_stringn("nul byte \0 in string", 20);
    result = json_dumps(json, JSON_ENCODE_ANY);
    if(!result || memcmp(result, "\"nul byte \\u0000 in string\"", 27))
        fail("json_dumps failed to dump an embedded NUL byte");

    free(result);
    json_decref(json);
}
Ejemplo n.º 2
0
static void encode_null()
{
    if(json_dumps(NULL, JSON_ENCODE_ANY) != NULL)
        fail("json_dumps didn't fail for NULL");

    if(json_dumpf(NULL, stderr, JSON_ENCODE_ANY) != -1)
        fail("json_dumpf didn't fail for NULL");

    /* Don't test json_dump_file to avoid creating a file */

    if(json_dump_callback(NULL, encode_null_callback, NULL, JSON_ENCODE_ANY) != -1)
        fail("json_dump_callback didn't fail for NULL");
}
Ejemplo n.º 3
0
/**
	Send response data to client.
	Parameters:
		int success: Status about data
		json_t *data: Data for response
		int client_sockfd: connection
*/
void response_data(int success, json_t *data, int client_sockfd) {
	json_t *root = json_object();

	if (success == 1) json_object_set(root, "success", json_true());
	else json_object_set(root, "success", json_false());
	json_object_set(root, "data", data);
	
	char *decode = json_dumps(root, 1);

	write(client_sockfd, decode, 500);

	json_decref(root);
}
Ejemplo n.º 4
0
std::string Message::toJSON() {
	json_t* jsonMessage = json_object();
	json_object_set_new(jsonMessage, "action", json_string(action.c_str()));
	json_t* jsonObject = json_object();
	bundle.toJSON(jsonObject);
	json_object_set_new(jsonMessage, "data", jsonObject);
	char* jsonStrLocal = json_dumps(jsonMessage,
	JSON_COMPACT | JSON_ENSURE_ASCII);
	std::string jsonStr(jsonStrLocal);
	json_decref(jsonObject);
	json_decref(jsonMessage);
	return jsonStr;
}
Ejemplo n.º 5
0
static jobjectArray ExpandTypeScript(JNIEnv* env, jclass clazz, jstring tmplt_nm, jstring tmplt_type, jstring tmplt_arg_json)
{
	if ( tmplt_nm == NULL || tmplt_type == NULL) {
		gHook.last_error = "empty arguments when expand template";
		return NULL;
	}

	string tmplt_nm_str, tmplt_type_str;
	GET_CPPSTR_FROM_JSTR(env, tmplt_nm, tmplt_nm_str);
	GET_CPPSTR_FROM_JSTR(env, tmplt_type, tmplt_type_str);

	if ( tmplt_nm_str.size() == 0 || tmplt_type_str.size() == 0) {
		gHook.last_error = "empty arguments when expand template";
		return NULL;
	}

	vedit::ScriptType tp = vedit::AUDIO_RESOURCE_SCRIPT;
	for ( ; tp != vedit::INVALID_SCRIPT; tp = (vedit::ScriptType)((int)tp + 1) ) {
		if ( tmplt_type_str == string(Vm::proc_type_names[tp]) ) {
			break;
		}
	}

	if ( tp == vedit::INVALID_SCRIPT ) {
		gHook.last_error = "invalid template type when expand template";
		return NULL;
	}

	json_t* arg_js = NULL;
	if (tmplt_arg_json != NULL) {
		string fail;
		arg_js = LoadJsonFromJString(env, tmplt_arg_json, fail);
	}

	JsonWrap wrap(arg_js, 1);

	try {
		ScriptSerialized pair = Vm::call_script(tmplt_nm_str.c_str(), tp, arg_js);
		jobjectArray jaret = env->NewObjectArray(2, gHook.java_string_clazz, NULL);
		env->SetObjectArrayElement(jaret,0, env->NewStringUTF(pair.first));
		char* str =  json_dumps(pair.second.h, 0);
		env->SetObjectArrayElement(jaret, 1, env->NewStringUTF(str));
		free(str);
		return jaret;
	}
	catch(const vedit::Exception& e) {
		gHook.last_error = "expand template failed ,cause: ";
		gHook.last_error += e.what();
		return NULL;
	}
}
Ejemplo n.º 6
0
int pc__handshake_req(pc_client_t *client) {
  json_t *handshake_opts = client->handshake_opts;
  json_t *body = json_object();

  if(body == NULL) {
    fprintf(stderr, "Fail to create json_t for handshake request.\n");
    return -1;
  }

  // compose handshake package
  json_t *sys = json_object();
  if(sys == NULL) {
    fprintf(stderr, "Fail to create json_t for handshake request.\n");
    goto error;
  }

  json_object_set(body, "sys", sys);

  json_object_set(sys, "version", json_string(PC_VERSION));

  if(handshake_opts) {
    json_t *heartbeat = json_object_get(handshake_opts, "heartbeat");
    if(heartbeat) {
      json_object_set(sys, "heartbeat", heartbeat);
    }

    json_t *user = json_object_get(handshake_opts, "user");
    if(heartbeat) {
      json_object_set(body, "user", user);
    }
  }

  const char *data = json_dumps(body, JSON_COMPACT);
  if(data == NULL) {
    fprintf(stderr, "Fail to compose Pomelo handshake package.\n");
    goto error;
  }

  pc_buf_t buf = pc_pkg_encode(PC_PKG_HANDSHAKE, data, strlen(data));
  if(pc__binary_write(client, buf.base, buf.len, pc__handshake_req_cb)) {
    fprintf(stderr, "Fail to send handshake request.\n");
    goto error;
  }

  json_decref(body);

  return 0;
error:
  if(body) json_decref(body);
  return -1;
}
Ejemplo n.º 7
0
void *janus_rmq_out_thread(void *data) {
	if(rmq_client == NULL) {
		JANUS_LOG(LOG_ERR, "No RabbitMQ connection??\n");
		return NULL;
	}
	JANUS_LOG(LOG_VERB, "Joining RabbitMQ out thread\n");
	while(!rmq_client->destroy && !g_atomic_int_get(&stopping)) {
		/* We send messages from here as well, not only notifications */
		janus_rabbitmq_response *response = g_async_queue_pop(rmq_client->messages);
		if(response == NULL)
			continue;
		if(response == &exit_message)
			break;
		if(!rmq_client->destroy && !g_atomic_int_get(&stopping) && response->payload) {
			janus_mutex_lock(&rmq_client->mutex);
			/* Gotcha! Convert json_t to string */
			char *payload_text = json_dumps(response->payload, json_format);
			json_decref(response->payload);
			response->payload = NULL;
			JANUS_LOG(LOG_VERB, "Sending %s API message to RabbitMQ (%zu bytes)...\n", response->admin ? "Admin" : "Janus", strlen(payload_text));
			JANUS_LOG(LOG_VERB, "%s\n", payload_text);
			amqp_basic_properties_t props;
			props._flags = 0;
			props._flags |= AMQP_BASIC_REPLY_TO_FLAG;
			props.reply_to = amqp_cstring_bytes("Janus");
			if(response->correlation_id) {
				props._flags |= AMQP_BASIC_CORRELATION_ID_FLAG;
				props.correlation_id = amqp_cstring_bytes(response->correlation_id);
			}
			props._flags |= AMQP_BASIC_CONTENT_TYPE_FLAG;
			props.content_type = amqp_cstring_bytes("application/json");
			amqp_bytes_t message = amqp_cstring_bytes(payload_text);
			int status = amqp_basic_publish(rmq_client->rmq_conn, rmq_client->rmq_channel, rmq_client->janus_exchange,
				response->admin ? rmq_client->from_janus_admin_queue : rmq_client->from_janus_queue,
				0, 0, &props, message);
			if(status != AMQP_STATUS_OK) {
				JANUS_LOG(LOG_ERR, "Error publishing... %d, %s\n", status, amqp_error_string2(status));
			}
			g_free(response->correlation_id);
			response->correlation_id = NULL;
			free(payload_text);
			payload_text = NULL;
			g_free(response);
			response = NULL;
			janus_mutex_unlock(&rmq_client->mutex);
		}
	}
	g_async_queue_unref(rmq_client->messages);
	JANUS_LOG(LOG_INFO, "Leaving RabbitMQ out thread\n");
	return NULL;
}
Ejemplo n.º 8
0
void ConnectionInstance::sendDebugReply(string message) {
    string outstr("ZZZ ");
    json_t* topnode = json_object();
    json_t* messagenode = json_string(message.c_str());
    if (!messagenode)
        messagenode = json_string_nocheck("Failed to parse the debug reply as a valid UTF-8 string.");
    json_object_set_new_nocheck(topnode, "message", messagenode);
    const char* replystr = json_dumps(topnode, JSON_COMPACT);
    outstr += replystr;
    free((void*) replystr);
    json_decref(topnode);
    MessagePtr outMessage(MessageBuffer::FromString(outstr));
    send(outMessage);
}
Ejemplo n.º 9
0
static void escape_slashes()
{
    /* Test dump escaping slashes */

    json_t *json;
    char *result;

    json = json_object();
    json_object_set_new(json, "url", json_string("https://github.com/akheron/jansson"));

    result = json_dumps(json, 0);
    if(!result || strcmp(result, "{\"url\": \"https://github.com/akheron/jansson\"}"))
        fail("json_dumps failed to not escape slashes");

    free(result);

    result = json_dumps(json, JSON_ESCAPE_SLASH);
    if(!result || strcmp(result, "{\"url\": \"https:\\/\\/github.com\\/akheron\\/jansson\"}"))
        fail("json_dumps failed to escape slashes");

    free(result);
    json_decref(json);
}
Ejemplo n.º 10
0
void PomeloSocket::onPushDataCallback(pc_client_t *client, const char *event, void *data)
{
    json_t* json = (json_t* )data;
    json_object_set(json,"route",json_string("onTest"));

    json_incref(json);
    const char* msg = json_dumps(json, 0);
    log("receve data:%s,%s", event, msg);
    pthread_mutex_lock(&mMutex);
    messageQueue.push_back(json);
    pthread_mutex_unlock(&mMutex);

    return;
}
Ejemplo n.º 11
0
void janus_videocall_hangup_media(janus_plugin_session *handle) {
	JANUS_LOG(LOG_INFO, "No WebRTC media anymore\n");
	if(g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
		return;
	janus_videocall_session *session = (janus_videocall_session *)handle->plugin_handle;	
	if(!session) {
		JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
		return;
	}
	if(session->destroyed)
		return;
	if(g_atomic_int_add(&session->hangingup, 1))
		return;
	/* Get rid of the recorders, if available */
	if(session->arc) {
		janus_recorder_close(session->arc);
		JANUS_LOG(LOG_INFO, "Closed audio recording %s\n", session->arc->filename ? session->arc->filename : "??");
		janus_recorder_free(session->arc);
	}
	session->arc = NULL;
	if(session->vrc) {
		janus_recorder_close(session->vrc);
		JANUS_LOG(LOG_INFO, "Closed video recording %s\n", session->vrc->filename ? session->vrc->filename : "??");
		janus_recorder_free(session->vrc);
	}
	session->vrc = NULL;
	if(session->peer) {
		/* Send event to our peer too */
		json_t *call = json_object();
		json_object_set_new(call, "videocall", json_string("event"));
		json_t *calling = json_object();
		json_object_set_new(calling, "event", json_string("hangup"));
		json_object_set_new(calling, "username", json_string(session->username));
		json_object_set_new(calling, "reason", json_string("Remote hangup"));
		json_object_set_new(call, "result", calling);
		char *call_text = json_dumps(call, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
		json_decref(call);
		JANUS_LOG(LOG_VERB, "Pushing event to peer: %s\n", call_text);
		int ret = gateway->push_event(session->peer->handle, &janus_videocall_plugin, NULL, call_text, NULL, NULL);
		JANUS_LOG(LOG_VERB, "  >> %d (%s)\n", ret, janus_get_api_error(ret));
		g_free(call_text);
	}
	session->peer = NULL;
	/* Reset controls */
	session->has_audio = FALSE;
	session->has_video = FALSE;
	session->audio_active = TRUE;
	session->video_active = TRUE;
	session->bitrate = 0;
}
Ejemplo n.º 12
0
    // Method for sending message from CPP to the targeted platform
    void sendMessageWithParams(std::string methodName, Value methodParams) {
        if (0 == strcmp(methodName.c_str(), "")) {
            return;
        }

        json_t *toBeSentJson = json_object();
        json_object_set_new(toBeSentJson, __CALLED_METHOD__, json_string(methodName.c_str()));

        if (!methodParams.isNull()) {
            json_t *paramsJson = NDKHelper::getJsonFromValue(methodParams);

            json_object_set_new(toBeSentJson, __CALLED_METHOD_PARAMS__, paramsJson);
        }

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
        JniMethodInfo t;

        if (JniHelper::getStaticMethodInfo(t,
                                           CLASS_NAME,
                                           "ReceiveCppMessage",
                                           "(Ljava/lang/String;)V")) {
            char *jsonStrLocal = json_dumps(toBeSentJson, JSON_COMPACT | JSON_ENSURE_ASCII);
            std::string jsonStr(jsonStrLocal);
            free(jsonStrLocal);

            jstring stringArg1 = t.env->NewStringUTF(jsonStr.c_str());
            t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg1);
            t.env->DeleteLocalRef(stringArg1);
            t.env->DeleteLocalRef(t.classID);
        }
#endif

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
        json_t *jsonMessageName = json_string(methodName.c_str());

        if (!methodParams.isNull()) {
            json_t *jsonParams = NDKHelper::getJsonFromValue(methodParams);

            IOSNDKHelperImpl::receiveCPPMessage(jsonMessageName, jsonParams);

            json_decref(jsonParams);
        } else {
            IOSNDKHelperImpl::receiveCPPMessage(jsonMessageName, NULL);
        }

        json_decref(jsonMessageName);
#endif

        json_decref(toBeSentJson);
    }
Ejemplo n.º 13
0
static int
watchman_send(struct watchman_connection *conn,
              json_t *query, struct watchman_error *error)
{
    int json_result = json_dumpf(query, conn->fp, JSON_COMPACT);
    if (json_result) {
        char *dump = json_dumps(query, 0);
        watchman_err(error, "Failed to send watchman query %s", dump);
        free(dump);
        return 1;
    }
    fputc('\n', conn->fp);
    return 0;
}
Ejemplo n.º 14
0
void
workspace_callback (i3ipcConnection *conn, i3ipcWorkspaceEvent *event, gpointer user_data) {
	struct widget *widget = (struct widget*)user_data;
	json_t *json_data_object = format_workspaces(conn);
	char *json_str = strdup(json_dumps(json_data_object, 0));
	struct js_callback_arg arg = widget_data_arg_string(json_str);
	struct js_callback_data data = { .widget = widget, .args = &arg, 1 };
	web_view_callback(&data);
	free(json_str);
}

void*
widget_main (struct widget *widget) {
	i3ipcConnection *conn = i3ipc_connection_new(NULL, NULL);

	json_t *json_data_object = format_workspaces(conn);
	char *json_str = strdup(json_dumps(json_data_object, 0));
	widget_data_callback(widget, widget_data_arg_string(json_str));
	free(json_str);

	void (*callback)(i3ipcConnection*, i3ipcWorkspaceEvent*, gpointer);
	callback = workspace_callback;

	GClosure *closure = g_cclosure_new(G_CALLBACK(callback), widget, NULL);
	i3ipc_connection_on(conn, (const gchar*)"workspace", closure, NULL);

	widget_epoll_init(widget);
	while (true) {
		widget_epoll_wait_goto(widget, 1000, cleanup);
	}

cleanup:
	g_object_unref(conn);

	widget_epoll_cleanup(widget);
	widget_clean_exit(widget);
}
Ejemplo n.º 15
0
static void encode_other_than_array_or_object()
{
    /* Encoding anything other than array or object should only
     * succeed if the JSON_ENCODE_ANY flag is used */

    json_t *json;
    FILE *fp = NULL;
    char *result;

    json = json_string("foo");
    if(json_dumps(json, 0) != NULL)
        fail("json_dumps encoded a string!");
    if(json_dumpf(json, fp, 0) == 0)
        fail("json_dumpf encoded a string!");

    result = json_dumps(json, JSON_ENCODE_ANY);
    if(!result || strcmp(result, "\"foo\"") != 0)
        fail("json_dumps failed to encode a string with JSON_ENCODE_ANY");

    free(result);
    json_decref(json);

    json = json_integer(42);
    if(json_dumps(json, 0) != NULL)
        fail("json_dumps encoded an integer!");
    if(json_dumpf(json, fp, 0) == 0)
        fail("json_dumpf encoded an integer!");

    result = json_dumps(json, JSON_ENCODE_ANY);
    if(!result || strcmp(result, "42") != 0)
        fail("json_dumps failed to encode an integer with JSON_ENCODE_ANY");

    free(result);
    json_decref(json);


}
Ejemplo n.º 16
0
void pss_response_delNode(req_t * req, json_t * response, int32_t requestId,
			  void *sweb, req_store_t * req_store)
{
	const char *ack = json_string_value(json_object_get(response,
							    "ack"));

	if (strcmp(ack, "ok") == 0) {

		json_t *web_resp = json_object();
		json_object_set_new(web_resp, "type", json_string("newData"));
		//TODO at the moment only the original node gets the update, which is good enough for me
		json_t *sessionIds = json_array();
		json_array_append(sessionIds,
				  json_object_get(req->request, "sessionId"));
		json_object_set_new(web_resp, "sessionIds", sessionIds);

		json_t *newData = json_object();
		json_t *deletedNodes = json_array();
		json_array_append(deletedNodes,
				  json_object_get
				  (json_object_get
				   (json_object_get
				    (req->request,
				     "clientRequest"), "request"), "id"));
		json_object_set_new(newData, "deletedNodes", deletedNodes);

		json_object_set_new(web_resp, "newData", newData);

		zmsg_t *res = zmsg_new();
		char *web_res_str = json_dumps(web_resp,
					       JSON_COMPACT);

		printf("\nbroker:sweb sent: %s\n", web_res_str);
		zmsg_addstr(res, web_res_str);
		free(web_res_str);
		zmsg_wrap(res, req->address);
		zmsg_send(&res, sweb);
		json_decref(web_resp);

	} else {

		if (strcmp(ack, "fail") == 0) {
			//TODO ??
		}
	}
	request_store_delete(req_store, requestId);
	json_decref(response);

}
Ejemplo n.º 17
0
static int
handle_request(void *cls, struct MHD_Connection *connection,
               const char *url, const char *method,
               const char *version, const char *upload_data,
               size_t *upload_data_size, void **con_cls)
{
    int ret;
    struct MHD_Response *response = NULL;
    struct brubeck_server *brubeck = cls;

    if (!strcmp(method, "GET")) {
        if (!strcmp(url, "/ping")) {
            char *jsonr;
            json_t *pong = json_pack("{s:s, s:i, s:s}",
                                     "version", "brubeck " GIT_SHA,
                                     "pid", (int)getpid(),
                                     "status", "OK");

            jsonr = json_dumps(pong, JSON_PRESERVE_ORDER);
            response = MHD_create_response_from_data(strlen(jsonr), jsonr, 1, 0);
            json_decref(pong);
        }

        else if (!strcmp(url, "/stats"))
            response = send_stats(brubeck);

        else if (starts_with(url, "/metric/"))
            response = send_metric(brubeck, url);
    }
    else if (!strcmp(method, "POST")) {
        if (starts_with(url, "/expire/"))
            response = expire_metric(brubeck, url);
    }

    if (!response) {
        static const char *NOT_FOUND = "404 not found";
        response = MHD_create_response_from_data(
                       strlen(NOT_FOUND), (void *)NOT_FOUND, 0, 0);
        MHD_add_response_header(response, "Connection", "close");
        ret = MHD_queue_response(connection, 404, response);
    } else {
        MHD_add_response_header(response, "Connection", "close");
        MHD_add_response_header(response, "Content-Type", "application/json");
        ret = MHD_queue_response(connection, 200, response);
    }

    MHD_destroy_response(response);
    return ret;
}
Ejemplo n.º 18
0
static void on_result(struct state_data *state, struct sign_request *request, json_t *result)
{
    if (state->ses->id != state->ses_id)
        return;
    if (result == NULL)
        goto error;

    json_t *code = json_object_get(result, "code");
    if (code == NULL)
        goto error;
    int error_code = json_integer_value(code);
    if (error_code != 0) {
        const char *message = json_string_value(json_object_get(result, "message"));
        if (message == NULL)
            goto error;
        log_error("sign fail, access_id: %s, authorisation: %s, token: %"PRIu64" code: %d, message: %s",
                request->access_id, request->authorisation, request->tonce, error_code, message);
        send_error(state->ses, state->request_id, 11, message);
        return;
    }

    json_t *data = json_object_get(result, "data");
    if (data == NULL)
        goto error;
    struct clt_info *info = state->info;
    uint32_t user_id = json_integer_value(json_object_get(data, "user_id"));
    if (user_id == 0)
        goto error;

    if (info->auth && info->user_id != user_id) {
        asset_unsubscribe(info->user_id, state->ses);
        order_unsubscribe(info->user_id, state->ses);
    }

    info->auth = true;
    info->user_id = user_id;
    log_error("sign success, access_id: %s, user_id: %u", request->access_id, user_id);
    send_success(state->ses, state->request_id);

    return;

error:
    if (result) {
        char *reply = json_dumps(result, 0);
        log_fatal("invalid reply: %s", reply);
        free(reply);
    }
    send_error_internal_error(state->ses, state->request_id);
}
Ejemplo n.º 19
0
void AssemblyWriter::writeToString(utString& out)
{
    json_t *json = json_object();

    json_object_set(json, "type", json_string("ASSEMBLY"));
    json_object_set(json, "name", json_string(name.c_str()));
    json_object_set(json, "version", json_string(version.c_str()));
    json_object_set(json, "uid", json_string(uid.c_str()));
    json_object_set(json, "loomconfig", json_string(loomConfig.c_str()));

#ifdef LOOM_ENABLE_JIT
    json_object_set(json, "jit", json_true());
#else
    json_object_set(json, "jit", json_false());
#endif

    json_object_set(json, "debugbuild", LSCompiler::isDebugBuild() ? json_true() : json_false());

    // references

    json_t *refArray = json_array();

    json_object_set(json, "references", refArray);

    for (UTsize i = 0; i < references.size(); i++)
    {
        utString assemblyName = references.at(i);

        json_t *ro = json_object();

        json_object_set(ro, "name", json_string(assemblyName.c_str()));

        json_array_append(refArray, ro);
    }

    // modules

    json_t *moduleArray = json_array();

    json_object_set(json, "modules", moduleArray);

    for (UTsize i = 0; i < modules.size(); i++)
    {
        json_t *mjson = modules[i]->write();
        json_array_append(moduleArray, mjson);
    }

    out = json_dumps(json, JSON_INDENT(3) | JSON_SORT_KEYS | JSON_PRESERVE_ORDER | JSON_COMPACT);
}
Ejemplo n.º 20
0
void BE_get_request()
{
 
  char request[1024];

  int n = ME_sock_recv(the_context.driverfd, request);
 
  if (n <= 0 || !(*request))
    return 1;
  
  //Parse out JSON
  json_t *root, *params;
  json_error_t error;
  root = json_loads(request, 0, &error);
  params = json_object_get(root,"params");
  char * RLI_expr = json_string_value(json_array_get(params,0));
  json_t *id_copy = json_copy(json_object_get(root,"id"));
  
  ME_RLI_IR_value value_result = BE_rhandler_dispatch(RLI_expr);

  json_decref(root);

  //Send response
  root = json_object();
  json_object_set_new(root, "jsonrpc", json_string("2.0"));

  if (value_result.type == ME_RLI_IR_VALUE_MEASUREMENT) {
    json_object_set_new(root, "result", ME_measurement_toJSON(value_result.vdata.ms));
  }
  else {
    json_object_set_new(root, "result", json_null());
  }


  json_object_set_new(root, "id", id_copy);

  char * response;
  response = json_dumps( root, 0 );
  
  ME_sock_send(the_context.driverfd, response);
  
  json_decref(root);

  if (quitting) {
    close(the_context.driverfd);
    exit(-1);
  }

}
Ejemplo n.º 21
0
json_t *Result::getJson()
{
    json_t *json = json_object();

//    if(success)
//    {

//    }else
//    {
        json_object_set(json, "success", json_pack("b", success));
        json_object_set(json, "failReason", json_pack("s", Util::cStr(failReason)));
//    }

//    json = json_pack("{"
//                     "s:i," // productNo
//                     "s:b," // success
//                     "s:b," // loaded
//                     "s:b," // generated
//                     "s:i," // screenWidth
//                     "s:i," // screenHeight
//                     "s:i," // imageGeneratedCount
//                     "s:i," // imageCount
//                     "s:i," // loadElapsed
//                     "s:i," // totalElapsed
//                     "s:s"  // failReason
//                     "}",
//                     "productNo", request->getProductNo(),
//                     "success", success,
//                     "loaded", loaded,
//                     "generated", generated,
//                     "screenWidth", (qint64)screenWidth,
//                     "screenHeight", (qint64)screenHeight,
//                     "imageGeneratedCount", (qint64)screenHeight,
//                     "imageGeneratedCount", (qint64)imageGeneratedCount,
//                     "imageCount", (qint64)imageCount,
//                     "loadElapsed", (qint64)loadElapsed,
//                     "totalElapsed", (qint64)totalElapsed,
//                     "failReason", Util::cStr(failReason)
//                     );

    char *json_str = json_dumps(json, JSON_ENCODE_ANY);
    if(json_str != NULL)
    {
        LOG(DEBUG) << "JSON String " << json_str;
        free(json_str);
    }

    return json;
}
Ejemplo n.º 22
0
void Net::pomeloMsgCallBack(pc_client_t *client, const char *event, void *data)
{
	char nullStr[] = "";
	void *msg = data ? data : (void*)nullStr;
	if(data)
	{
		msg = json_dumps((const json_t*)data, 0);
	}
	
	Net::getInstance()->pushMsg(std::string(event), std::string((const char*)msg));
	if(data)
	{
		free(msg);
	}
}
Ejemplo n.º 23
0
int PomeloSocket::sendMsg(const char* route, json_t* json)
{
    if(state != CONNECTED_OK){
        log("socket has disconnected......");
        return -1;
    }
    Loading::getInstance()->show();
    
    pc_request_t *request = pc_request_new();
    void (*request_cb)(pc_request_t *req, int status, json_t *resp )= &PomeloSocket::requstCallback;

    int ret=pc_request(client, request, route, json, request_cb);
    log("发送数据:route:%s,msg:%s",route,json_dumps(json,0));
    return ret;
}
std::string TDvbJanssonParser::GetProfiles()
{
  std::string res;
  json_error_t error;
  json_t* json = json_load_file(DvbConfigProfileFile.c_str(), 0, &error);
  if (json) {
    res = std::string(json_dumps(json, JSON_INDENT(2)|JSON_ENSURE_ASCII|JSON_PRESERVE_ORDER));
    json_decref(json);
  }
  else {
    OS_LOG(DVB_ERROR,   "%s:%d: json_load_file(%s) failed, error = %s\n",
      __FUNCTION__, __LINE__, DvbConfigProfileFile.c_str(), error.text);
  }
  return res;
}
Ejemplo n.º 25
0
std::string Json::stringify()
{
	char *buf = json_dumps( data, JSON_COMPACT | JSON_PRESERVE_ORDER | JSON_ENCODE_ANY );
	if ( buf != NULL )
	{
		std::string res( buf );
		sized_free( buf );
		return res;
	}
	else
	{
		LLOG
		return "";
	}
}
Ejemplo n.º 26
0
static int __jsondump(json_t *json)
{
	char *dump;
	int indent = g_oneline ? 0 : 4;

	dump = json_dumps(json, JSON_INDENT(indent) | JSON_ENSURE_ASCII |
				JSON_SORT_KEYS);
	if (!dump) {
		pr_err("Failed to get JSON dump.\n");
		return -ENOMEM;
	}
	pr_out("%s\n", dump);
	free(dump);
	return 0;
}
Ejemplo n.º 27
0
static
void handle_conn(Broker *broker, HttpRequest *req, Socket *sock) {
    json_error_t err;

    json_t *body;
    {
        const char *start = strchr(req->body, '{');
        const char *end = strrchr(req->body, '}');
        if (!(start && end)) {
            goto exit;
        }
        body = json_loadb(start, end - start + 1, 0, &err);
        if (!body) {
            broker_send_internal_error(sock);
            goto exit;
        }
    }

    const char *dsId = broker_http_param_get(&req->uri, "dsId");
    if (!dsId) {
        goto exit;
    }
    log_info("%s connecting \n", dsId);
    const char *token = broker_http_param_get(&req->uri, "token");
    json_t *resp = broker_handshake_handle_conn(broker, dsId, token, body);
    json_decref(body);
    if (!resp) {
        broker_send_internal_error(sock);
        goto exit;
    }

    char *data = json_dumps(resp, JSON_INDENT(2));
    json_decref(resp);
    if (!data) {
        broker_send_internal_error(sock);
        goto exit;
    }

    char buf[1024];
    int len = snprintf(buf, sizeof(buf) - 1,
                       CONN_RESP, (int) strlen(data), data);
    buf[len] = '\0';
    dslink_free(data);
    dslink_socket_write(sock, buf, (size_t) len);

exit:
    return;
}
Ejemplo n.º 28
0
void janus_echotest_slow_link(janus_plugin_session *handle, int uplink, int video) {
	/* The core is informing us that our peer got or sent too many NACKs, are we pushing media too hard? */
	if(handle == NULL || handle->stopped || g_atomic_int_get(&stopping) || !g_atomic_int_get(&initialized))
		return;
	janus_echotest_session *session = (janus_echotest_session *)handle->plugin_handle;	
	if(!session) {
		JANUS_LOG(LOG_ERR, "No session associated with this handle...\n");
		return;
	}
	if(session->destroyed)
		return;
	session->slowlink_count++;
	if(uplink && !video && !session->audio_active) {
		/* We're not relaying audio and the peer is expecting it, so NACKs are normal */
		JANUS_LOG(LOG_VERB, "Getting a lot of NACKs (slow uplink) for audio, but that's expected, a configure disabled the audio forwarding\n");
	} else if(uplink && video && !session->video_active) {
		/* We're not relaying video and the peer is expecting it, so NACKs are normal */
		JANUS_LOG(LOG_VERB, "Getting a lot of NACKs (slow uplink) for video, but that's expected, a configure disabled the video forwarding\n");
	} else {
		/* Slow uplink or downlink, maybe we set the bitrate cap too high? */
		if(video) {
			/* Halve the bitrate, but don't go too low... */
			session->bitrate = session->bitrate > 0 ? session->bitrate : 512*1024;
			session->bitrate = session->bitrate/2;
			if(session->bitrate < 64*1024)
				session->bitrate = 64*1024;
			JANUS_LOG(LOG_WARN, "Getting a lot of NACKs (slow %s) for %s, forcing a lower REMB: %"SCNu64"\n",
				uplink ? "uplink" : "downlink", video ? "video" : "audio", session->bitrate);
			/* ... and send a new REMB back */
			char rtcpbuf[24];
			janus_rtcp_remb((char *)(&rtcpbuf), 24, session->bitrate);
			gateway->relay_rtcp(handle, 1, rtcpbuf, 24);
			/* As a last thing, notify the user about this */
			json_t *event = json_object();
			json_object_set_new(event, "echotest", json_string("event"));
			json_t *result = json_object();
			json_object_set_new(result, "status", json_string("slow_link"));
			json_object_set_new(result, "bitrate", json_integer(session->bitrate));
			json_object_set_new(event, "result", result);
			char *event_text = json_dumps(event, JSON_INDENT(3) | JSON_PRESERVE_ORDER);
			json_decref(event);
			json_decref(result);
			event = NULL;
			gateway->push_event(session->handle, &janus_echotest_plugin, NULL, event_text, NULL, NULL);
			g_free(event_text);
		}
	}
}
Ejemplo n.º 29
0
//----------------------------------------------------------------//
int MOAIHarness::_sendMessage(lua_State* L)
{
	// Read the message off of the top of the stack
	json_t* message = MOAIHarness::ConvertStackIndexToJSON(L, lua_gettop(L));

	// Send the message back to the IDE.
	json_t* msg = json_object();
	json_object_set_new(msg, "ID", json_string("message"));
	json_object_set_new(msg, "Value", message);
	char* data = json_dumps(msg, 0);
	MOAIHarness::SendData(std::string(data));
	free(data);

	// Done!
	return 0;
}
Ejemplo n.º 30
0
double getAvail(Parameters& params, std::string currency) {
  json_t* root = authRequest(params, "https://www.bitstamp.net/api/balance/", "");
  while (json_object_get(root, "message") != NULL) {
    sleep(1.0);
    *params.logFile << "<Bitstamp> Error with JSON: " << json_dumps(root, 0) << ". Retrying..." << std::endl;
    root = authRequest(params, "https://www.bitstamp.net/api/balance/", "");
  }
  double availability = 0.0;
  if (currency.compare("btc") == 0) {
    availability = atof(json_string_value(json_object_get(root, "btc_balance")));
  } else if (currency.compare("usd") == 0) {
    availability = atof(json_string_value(json_object_get(root, "usd_balance")));
  }
  json_decref(root);
  return availability;
}