예제 #1
0
파일: json.c 프로젝트: worldwise001/ircbot
gsweb_t json_parse_gsweb() {
    JsonParser *parser;
    JsonNode *root;
    JsonReader *reader;
    GError *error;
    int array_size = 0;
    const char * tmp;
    gsweb_t ret;
    memset(&ret, 0, sizeof(ret));

    g_type_init();

    parser = json_parser_new();
    error = NULL;
    json_parser_load_from_file(parser, GTMPFILE, &error);
    if (error)
    {
        g_error_free(error);
        g_object_unref(parser);
        ret.success = 2;
        return ret;
    }
    root = json_parser_get_root(parser);
    reader = json_reader_new(root);

    json_reader_read_member (reader, "responseData");
    json_reader_read_member (reader, "results");
    array_size = json_reader_count_elements(reader);
    if (array_size > 0) {
        json_reader_read_element (reader, 0);

        json_reader_read_member (reader, "unescapedUrl");
        tmp = json_reader_get_string_value (reader);
        strncpy(ret.url, tmp, (strlen(tmp) < BUFF_SIZE)?strlen(tmp):BUFF_SIZE);
        json_reader_end_member (reader);

        json_reader_read_member (reader, "titleNoFormatting");
        tmp = json_reader_get_string_value (reader);
        strncpy(ret.title, tmp, (strlen(tmp) < BUFF_SIZE)?strlen(tmp):BUFF_SIZE);
        json_reader_end_member (reader);

        json_reader_read_member (reader, "content");
        tmp = json_reader_get_string_value (reader);
        strncpy(ret.content, tmp, (strlen(tmp) < BUFF_SIZE)?strlen(tmp):BUFF_SIZE);
        json_reader_end_member (reader);

        json_reader_end_element (reader);
        ret.success = 0;
    }
    else
        ret.success = 1;
    json_reader_end_member (reader);
    json_reader_end_member (reader);

    g_object_unref(parser);
    g_object_unref(reader);
    return ret;
}
static gboolean
parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error)
{
	gboolean success;

	if (g_strcmp0 (json_reader_get_member_name (reader), "role") == 0) {
		gchar *role = NULL;  /* owned */

		g_assert (gdata_parser_string_from_json_member (reader, "role",
		                                                P_REQUIRED |
		                                                P_NON_EMPTY,
		                                                &role, &success,
		                                                error));

		if (!success) {
			return FALSE;
		}

		gdata_access_rule_set_role (GDATA_ACCESS_RULE (parsable),
		                            role_v3_to_v2 (role));
		g_free (role);

		return TRUE;
	} else if (g_strcmp0 (json_reader_get_member_name (reader),
	                                                   "scope") == 0) {
		const gchar *scope_type;
		const gchar *scope_value;

		/* Check this is an object. */
		if (!json_reader_is_object (reader)) {
			return gdata_parser_error_required_json_content_missing (reader,
			                                                         error);
		}

		json_reader_read_member (reader, "type");
		scope_type = json_reader_get_string_value (reader);
		json_reader_end_member (reader);

		json_reader_read_member (reader, "value");
		scope_value = json_reader_get_string_value (reader);
		json_reader_end_member (reader);

		/* Scope type is required. */
		if (scope_type == NULL) {
			return gdata_parser_error_required_json_content_missing (reader,
			                                                         error);
		}

		gdata_access_rule_set_scope (GDATA_ACCESS_RULE (parsable),
		                             scope_type_v3_to_v2 (scope_type),
		                             scope_value);

		return TRUE;
	}

	return GDATA_PARSABLE_CLASS (gdata_calendar_access_rule_parent_class)->parse_json (parsable, reader, user_data, error);
}
static gint64
reader_parse_timestamp (JsonReader *reader, const gchar *member, GError **error)
{
	const GError *reader_error;
	const gchar *date_str;
	gint64 timestamp = -1;

	if (error != NULL && *error != NULL)
		return -1;

	json_reader_read_member (reader, member);
	date_str = json_reader_get_string_value (reader);
	reader_error = json_reader_get_error (reader);

	if (reader_error != NULL) {
		if (error != NULL)
			*error = g_error_copy (reader_error);
	} else if (date_str) {
		if (!gdata_parser_int64_from_iso8601 (date_str, &timestamp))
			timestamp = -1;
	}

	json_reader_end_member (reader);

	return timestamp;
}
/* Parsing functions to create GDataFreebaseTopicValues, and arrays of those */
static gchar *
reader_dup_member_string (JsonReader *reader, const gchar *member, GError **error)
{
	const GError *reader_error;
	gchar *str;

	if (error != NULL && *error != NULL)
		return NULL;

	json_reader_read_member (reader, member);
	str = g_strdup (json_reader_get_string_value (reader));
	reader_error = json_reader_get_error (reader);

	if (reader_error != NULL) {
		g_free (str);
		str = NULL;

		if (error != NULL)
			*error = g_error_copy (reader_error);
	}

	json_reader_end_member (reader);

	return str;
}
static gboolean
parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error)
{
	GDataFreebaseTopicResultPrivate *priv = GDATA_FREEBASE_TOPIC_RESULT (parsable)->priv;
	const gchar *member_name;

	GDATA_PARSABLE_CLASS (gdata_freebase_topic_result_parent_class)->parse_json (parsable, reader, user_data, error);

	member_name = json_reader_get_member_name (reader);

	if (member_name == NULL)
		return FALSE;

	if (strcmp (member_name, "id") == 0) {
		/* We only expect one member containing information */
		g_assert (priv->object == NULL);
		priv->object = object_new (json_reader_get_string_value (reader));
	} else if (strcmp (member_name, "property") == 0) {
		reader_get_properties (reader, priv->object, error);
	} else {
		return FALSE;
	}

	return TRUE;
}
예제 #6
0
/*
 * gdata_parser_string_from_json_member:
 * @reader: #JsonReader cursor object to read JSON node from
 * @member_name: the name of the member to parse
 * @options: a bitwise combination of parsing options from #GDataParserOptions, or %P_NONE
 * @output: the return location for the parsed string content
 * @success: the return location for a value which is %TRUE if the string was parsed successfully, %FALSE if an error was encountered,
 * and undefined if @element didn't match @element_name
 * @error: a #GError, or %NULL
 *
 * Gets the string content of @element if its name is @element_name, subject to various checks specified by @options.
 *
 * If @element doesn't match @element_name, %FALSE will be returned, @error will be unset and @success will be unset.
 *
 * If @element matches @element_name but one of the checks specified by @options fails, %TRUE will be returned, @error will be set to a
 * %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error and @success will be set to %FALSE.
 *
 * If @element matches @element_name and all of the checks specified by @options pass, %TRUE will be returned, @error will be unset and
 * @success will be set to %TRUE.
 *
 * The reason for returning the success of the parsing in @success is so that calls to gdata_parser_string_from_element() can be chained
 * together in a large "or" statement based on their return values, for the purposes of determining whether any of the calls matched
 * a given @element. If any of the calls to gdata_parser_string_from_element() return %TRUE, the value of @success can be examined.
 *
 * Return value: %TRUE if @element matched @element_name, %FALSE otherwise
 *
 * Since: 0.15.0
 */
gboolean
gdata_parser_string_from_json_member (JsonReader *reader, const gchar *member_name, GDataParserOptions options,
                                      gchar **output, gboolean *success, GError **error)
{
	const gchar *text;
	const GError *child_error = NULL;

	/* Check if there's such element */
	if (g_strcmp0 (json_reader_get_member_name (reader), member_name) != 0) {
		return FALSE;
	}

	/* Check if the output string has already been set. The JSON parser guarantees this can't happen. */
	g_assert (!(options & P_NO_DUPES) || *output == NULL);

	/* Get the string and check it for NULLness or emptiness. Check for parser errors first. */
	text = json_reader_get_string_value (reader);
	child_error = json_reader_get_error (reader);
	if (child_error != NULL) {
		*success = parser_error_from_json_error (reader, child_error, error);
		return TRUE;
	} else if ((options & P_REQUIRED && text == NULL) || (options & P_NON_EMPTY && text != NULL && *text == '\0')) {
		*success = gdata_parser_error_required_json_content_missing (reader, error);
		return TRUE;
	} else if (options & P_DEFAULT && (text == NULL || *text == '\0')) {
		text = "";
	}

	/* Success! */
	g_free (*output);
	*output = g_strdup (text);
	*success = TRUE;

	return TRUE;
}
예제 #7
0
파일: test.c 프로젝트: initlove/fuse-ocs
gchar *
get_value (gchar *data, gchar *key)
{
    JsonParser *parser = json_parser_new ();
    JsonReader *reader = json_reader_new (NULL);
    GError *error = NULL;
    gchar *val = NULL;

    json_parser_load_from_data (parser, data, -1, &error);
    if (error) {
        g_error_free (error);
        goto out;
    }

    json_reader_set_root (reader, json_parser_get_root (parser));
    if (!json_reader_is_object (reader)) {
        goto out;
    }

    json_reader_read_member (reader, key);
    val = g_strdup (json_reader_get_string_value (reader));
    json_reader_end_member (reader);
out:
    g_object_unref (parser);
    g_object_unref (reader);

    return val;
}
예제 #8
0
파일: test.c 프로젝트: initlove/fuse-ocs
GList *
get_file_list (gchar *data)
{
    JsonParser *parser = json_parser_new ();
    JsonReader *reader = json_reader_new (NULL);
    GError *error = NULL;
    GList *val = NULL;
    gint count, i;
    simple_file *sf;

    json_parser_load_from_data (parser, data, -1, &error);
    if (error) {
        g_error_free (error);
        goto out;
    }

    json_reader_set_root (reader, json_parser_get_root (parser));
    if (!json_reader_is_object (reader)) {
        goto out;
    }

    json_reader_read_member (reader, "files");
    count = json_reader_count_elements (reader);
    for (i = 0; i < count; i++) {
        json_reader_read_element (reader, i);
        sf = malloc(sizeof (simple_file));

        json_reader_read_member (reader, "name");
        sf->name = g_strdup (json_reader_get_string_value (reader));
        json_reader_end_member (reader);

        json_reader_read_member (reader, "type");
        sf->type = g_strdup (json_reader_get_string_value (reader));
        json_reader_end_member (reader);
        val = g_list_prepend (val, sf);

        json_reader_end_member (reader);
    }

    json_reader_end_member (reader);    //files
out:
    g_object_unref (parser);
    g_object_unref (reader);

    return val;
}
예제 #9
0
const gchar *
getString (JsonReader * reader, const gchar * member_name)
{
  json_reader_read_member (reader, member_name);
  const char *value = json_reader_get_string_value (reader);
  json_reader_end_member (reader);
  return value;
}
static gboolean
reader_fill_simple_gvalue (JsonReader *reader, TopicValueType type, GValue *value)
{
	gboolean retval = TRUE;
	gint64 datetime;

	json_reader_read_member (reader, "value");

	if (json_reader_get_error (reader) != NULL) {
		json_reader_end_member (reader);
		return FALSE;
	}

	switch (type) {
	case TYPE_BOOL:
	case TYPE_INT:
	case TYPE_DOUBLE:
	case TYPE_STRING:
		json_node_get_value (json_reader_get_value (reader), value);
		break;
	case TYPE_DATETIME:
		if (gdata_parser_int64_from_iso8601 (json_reader_get_string_value (reader), &datetime) ||
		    gdata_parser_int64_from_date (json_reader_get_string_value (reader), &datetime)) {
			g_value_init (value, G_TYPE_INT64);
			g_value_set_int64 (value, datetime);
		} else {
			retval = FALSE;
		}

		break;
	case TYPE_NONE:
	case TYPE_COMPOUND:
	case TYPE_OBJECT:
	case TYPE_KEY:
	case TYPE_URI:
	default:
		retval = FALSE;
	}

	json_reader_end_member (reader);
	return retval;
}
예제 #11
0
파일: weibo_oauth.c 프로젝트: wucan/unim
int weibo_oauth_access(struct unim_login_info *login_info)
{
	char *req_param, *reply;
	int rc = -1;
	int argc = 0;
	char **argv = NULL;
	char *postargs = NULL;
	int i;

	argc = oauth_split_url_parameters(login_info->access_token_uri, &argv);
	if (login_info->request_added_argc) {
		for (i = 0; i < login_info->request_added_argc; i++) {
			oauth_add_param_to_array(&argc, &argv,
					login_info->request_added_argv[i]);
		}
	}
	req_param = oauth_serialize_url_parameters(argc, argv);
	printf("req_param: %s\n", req_param);
	reply = oauth_http_post(login_info->access_token_uri, req_param);
	if (reply) {
		JsonParser *jparser;
		GError *err;
		gboolean rb;

		printf("HTTP-reply:\n\t%s\n", reply);
		jparser = json_parser_new();
		rb = json_parser_load_from_data(jparser, reply, strlen(reply), &err);
		if (!rb) {
			printf("json parse failed! err: %s\n", err->message);
			g_object_unref(jparser);
			goto error_out;
		}
		JsonReader *jreader = json_reader_new(json_parser_get_root(jparser));
		rb = json_reader_read_member(jreader, "access_token");
		if (rb) {
			login_info->access_token_key =
				strdup(json_reader_get_string_value(jreader));
			rc = 0;
		}
		g_object_unref(jreader);
	}

error_out:
	if (req_param)
		free(req_param);
	if (reply)
		free(reply);
	if (postargs)
		free(postargs);

	return rc;
}
static GDataFreebaseTopicObject *
reader_create_object (JsonReader *reader, TopicValueType type)
{
	GDataFreebaseTopicObject *object;

	if (type != TYPE_OBJECT && type != TYPE_COMPOUND)
		return NULL;

	json_reader_read_member (reader, "id");

	if (json_reader_get_error (reader) != NULL) {
		json_reader_end_member (reader);
		return NULL;
	}

	object = object_new (json_reader_get_string_value (reader));
	json_reader_end_member (reader);

	return object;
}
static guint
reader_get_value_type (JsonReader *reader, const gchar *property, GError **error)
{
	TopicValueType type = TYPE_NONE;
	const GError *reader_error;
	const gchar *valuestr;

	json_reader_read_member (reader, "valuetype");
	valuestr = json_reader_get_string_value (reader);

	reader_error = json_reader_get_error (reader);

	if (reader_error != NULL) {
		if (error != NULL && *error == NULL)
			*error = g_error_copy (reader_error);
	} else {
		if (strcmp (valuestr, "key") == 0)
			type = TYPE_KEY;
		else if (strcmp (valuestr, "uri") == 0)
			type = TYPE_URI;
		else if (strcmp (valuestr, "compound") == 0)
			type = TYPE_COMPOUND;
		else if (strcmp (valuestr, "object") == 0)
			type = TYPE_OBJECT;
		else if (strcmp (valuestr, "float") == 0)
			type = TYPE_DOUBLE;
		else if (strcmp (valuestr, "string") == 0)
			type = TYPE_STRING;
		else if (strcmp (valuestr, "int") == 0)
			type = TYPE_INT;
		else if (strcmp (valuestr, "bool") == 0)
			type = TYPE_BOOL;
		else if (strcmp (valuestr, "datetime") == 0)
			type = TYPE_DATETIME;
		else
			gdata_parser_error_required_json_content_missing (reader, error);
	}

	json_reader_end_member (reader);
	return type;
}
예제 #14
0
/*
 * gdata_parser_int64_time_from_json_member:
 * @reader: #JsonReader cursor object to read JSON node from
 * @element_name: the name of the element to parse
 * @options: a bitwise combination of parsing options from #GDataParserOptions, or %P_NONE
 * @output: (out caller-allocates): the return location for the parsed time value
 * @success: the return location for a value which is %TRUE if the time val was parsed successfully, %FALSE if an error was encountered,
 * and undefined if @element didn't match @element_name
 * @error: a #GError, or %NULL
 *
 * Gets the time value of @element if its name is @element_name, subject to various checks specified by @options. It expects the text content
 * of @element to be a date or time value in ISO 8601 format. The returned time value will be a UNIX timestamp (seconds since the epoch).
 *
 * If @element doesn't match @element_name, %FALSE will be returned, @error will be unset and @success will be unset.
 *
 * If @element matches @element_name but one of the checks specified by @options fails, %TRUE will be returned, @error will be set to a
 * %GDATA_SERVICE_ERROR_PROTOCOL_ERROR error and @success will be set to %FALSE.
 *
 * If @element matches @element_name and all of the checks specified by @options pass, %TRUE will be returned, @error will be unset and
 * @success will be set to %TRUE.
 *
 * The reason for returning the success of the parsing in @success is so that calls to gdata_parser_int64_time_from_element() can be chained
 * together in a large "or" statement based on their return values, for the purposes of determining whether any of the calls matched
 * a given @element. If any of the calls to gdata_parser_int64_time_from_element() return %TRUE, the value of @success can be examined.
 *
 * Return value: %TRUE if @element matched @element_name, %FALSE otherwise
 *
 * Since: 0.15.0
 */
gboolean
gdata_parser_int64_time_from_json_member (JsonReader *reader, const gchar *member_name, GDataParserOptions options,
                                          gint64 *output, gboolean *success, GError **error)
{
	const gchar *text;
	GTimeVal time_val;
	const GError *child_error = NULL;

	/* Check if there's such element */
	if (g_strcmp0 (json_reader_get_member_name (reader), member_name) != 0) {
		return FALSE;
	}

	/* Check if the output time val has already been set. The JSON parser guarantees this can't happen. */
	g_assert (!(options & P_NO_DUPES) || *output == -1);

	/* Get the string and check it for NULLness. Check for errors first. */
	text = json_reader_get_string_value (reader);
	child_error = json_reader_get_error (reader);
	if (child_error != NULL) {
		*success = parser_error_from_json_error (reader, child_error, error);
		return TRUE;
	} else if (options & P_REQUIRED && (text == NULL || *text == '\0')) {
		*success = gdata_parser_error_required_json_content_missing (reader, error);
		return TRUE;
	}

	/* Attempt to parse the string as a GTimeVal */
	if (g_time_val_from_iso8601 ((gchar*) text, &time_val) == FALSE) {
		*success = gdata_parser_error_not_iso8601_format_json (reader, text, error);
		return TRUE;
	}

	/* Success! */
	*output = time_val.tv_sec;
	*success = TRUE;

	return TRUE;
}
static int websocket_callback(struct libwebsocket_context *context,struct libwebsocket *wsi,enum libwebsocket_callback_reasons reason, void *user,void *in, size_t len)
{
	//printf("Switch: %i\n",reason);


	switch (reason)
	{
		case LWS_CALLBACK_CLIENT_WRITEABLE:
		{
			//Connection has been established.
			//printf("Connection established\n");
			break;
		}
		case LWS_CALLBACK_CLOSED:
		{
			//Connection is closed, we need to remove all related sinks
			sinkManager->disconnectAll(wsi);
			/*g_io_
			GIOChannel *chan = g_io_channel_unix_new((int)(long)user);
			g_io_add_watch(chan,G_IO_IN,(GIOFunc)gioPollingFunc,0);
			g_io_add_watch(chan,G_IO_PRI,(GIOFunc)gioPollingFunc,0);
			pollfds[count_pollfds].fd = (int)(long)user;
			pollfds[count_pollfds].events = (int)len;
// 			pollfds[count_pollfds++].revents = 0;*/
			break;
		}
		case LWS_CALLBACK_CLIENT_RECEIVE:
		{
			//printf("Client writable\n");
			break;
		}
		case LWS_CALLBACK_SERVER_WRITEABLE:
		{
			//printf("Server writable\n");
			break;
		}

		case LWS_CALLBACK_RECEIVE:
		{
			//printf("Data Received: %s\n",(char*)in);
			//The lack of a break; here is intentional.
		}
		case LWS_CALLBACK_HTTP:
		{
			//TODO: Verify that ALL requests get sent via LWS_CALLBACK_HTTP, so we can use that instead of LWS_CALLBACK_RECIEVE
			//TODO: Do we want exceptions, or just to return an invalid json reply? Probably an invalid json reply.
			DebugOut() << __SMALLFILE__ << ":" << __LINE__ << " Requested: " << (char*)in << "\n";
			GError* error = nullptr;


			JsonParser* parser = json_parser_new();
			if (!json_parser_load_from_data(parser,(char*)in,len,&error))
			{
				DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Error loading JSON\n";
				return 0;
			}

			JsonNode* node = json_parser_get_root(parser);
			if(node == nullptr)
			{
				DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Error getting root node of json\n";
				//throw std::runtime_error("Unable to get JSON root object");
				return 0;
			}

			JsonReader* reader = json_reader_new(node);
			if(reader == nullptr)
			{
				DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "json_reader is null!\n";
				//throw std::runtime_error("Unable to create JSON reader");
				return 0;
			}





			string type;
			json_reader_read_member(reader,"type");
			type = json_reader_get_string_value(reader);
			json_reader_end_member(reader);

			string  name;
			json_reader_read_member(reader,"name");
			name = json_reader_get_string_value(reader);
			json_reader_end_member(reader);
			
			string id;
			json_reader_read_member(reader,"transactionid");
			if (strcmp("gchararray",g_type_name(json_node_get_value_type(json_reader_get_value(reader)))) == 0)
			{
				//Type is a string
				id = json_reader_get_string_value(reader);
			}
			else
			{
				//Type is an integer
				stringstream strstr;
				strstr << json_reader_get_int_value(reader);
				id = strstr.str();
			}
			json_reader_end_member(reader);

			
			if (type == "method" && name == "getRanged")
			{
				json_reader_read_member(reader,"data");
				if (json_reader_is_object(reader))
				{
					double timeBegin;
					double timeEnd;
					double sequenceBegin;
					double sequenceEnd;
					string property;
					if (json_reader_read_member(reader,"timeBegin"))
					{
						timeBegin = boost::lexical_cast<double,std::string>(json_reader_get_string_value(reader));
						json_reader_end_member(reader);
					}
					
					if (json_reader_read_member(reader,"timeEnd"))
					{
						timeEnd = boost::lexical_cast<double,std::string>(json_reader_get_string_value(reader));
						json_reader_end_member(reader);
					}
					if (json_reader_read_member(reader,"sequenceBegin"))
					{
						sequenceBegin = boost::lexical_cast<double,std::string>(json_reader_get_string_value(reader));
						json_reader_end_member(reader);
					}
					if (json_reader_read_member(reader,"sequenceEnd"))
					{
						sequenceEnd = boost::lexical_cast<double,std::string>(json_reader_get_string_value(reader));
						json_reader_end_member(reader);
					}
					if (json_reader_read_member(reader,"property"))
					{
						property = json_reader_get_string_value(reader);
						json_reader_end_member(reader);
					}
					if ((timeBegin < 0 && timeEnd > 0) || (timeBegin > 0 && timeEnd < 0))
					{
						//Invalid time begin/end pair
					}
					if ((sequenceBegin < 0 && sequenceEnd > 0) || (sequenceBegin > 0 && sequenceEnd < 0))
					{
						//Invalid sequence begin/end pair
					}
					sinkManager->addSingleShotRangedSink(wsi,property,timeBegin,timeEnd,sequenceBegin,sequenceEnd,id);
				}
				json_reader_end_member(reader);
			}
			else
			{

				vector<string> data;
				list<string> key;
				list<string> value;
				json_reader_read_member(reader,"data");
				if (json_reader_is_array(reader))
				{
					for(int i=0; i < json_reader_count_elements(reader); i++)
					{
						json_reader_read_element(reader,i);
						if (json_reader_is_value(reader))
						{
							//Raw string value
							string path = json_reader_get_string_value(reader);
							data.push_back(path);

						}
						else
						{
							//Not a raw string value, then it's "property/value" kvp, for "set" requests
							json_reader_read_member(reader,"property");
							string keystr = json_reader_get_string_value(reader);
							key.push_back(keystr);
							json_reader_end_member(reader);
							json_reader_read_member(reader,"value");
							string valuestr = json_reader_get_string_value(reader);
							value.push_back(valuestr);
							json_reader_end_member(reader);
						}
						json_reader_end_element(reader);
					}
				}
				else
				{
					string path = json_reader_get_string_value(reader);
					if (path != "")
					{
						data.push_back(path);
					}
				}
				json_reader_end_member(reader);
				if (type == "method")
				{
					if (name == "get")
					{
						if (data.size() > 0)
						{
							//GetProperty is going to be a singleshot sink.
							//string arg = arguments.front();
							sinkManager->addSingleShotSink(wsi,data.front(),id);
						}
						else
						{
							DebugOut() << __SMALLFILE__ << ":" << __LINE__ << " \"get\" method called with no data! Transaction ID:" << id << "\n";
						}
					}
					else if (name == "set")
					{
						if (data.size() > 0)
						{
						  //Should not happen
						}
						else if (value.size() > 0)
						{
							if (key.size() != value.size())
							{
								DebugOut() << __SMALLFILE__ << ":" << __LINE__ << "\"set\" method called with an invalid key value pair count\n";
							}
							else
							{
								list<string>::iterator d = value.begin();
								for (list<string>::iterator i=key.begin();i!=key.end();i++)
								{
									DebugOut() << __SMALLFILE__ << ":" << __LINE__ << "websocketsinkmanager setting" << (*i) << "to" << (*d) << "\n";
									//(*i);
									sinkManager->setValue((*i),(*d));
									//(*d);
									d++;
								}

							}
						}
					}
					else if (name == "subscribe")
					{
						//Websocket wants to subscribe to an event, data.front();
						for (auto i=data.begin();i!=data.end();i++)
						{
							sinkManager->addSink(wsi,(*i),id);
						}
					}
					else if (name == "unsubscribe")
					{
						//Websocket wants to unsubscribe to an event, data.front();
						for (auto i=data.begin();i!=data.end();i++)
						{
							sinkManager->removeSink(wsi,(*i),id);
						}
					}
					else if (name == "getSupportedEventTypes")
					{
						//If data.front() dosen't contain a property name, return a list of properties supported.
						//if it does, then return the event types that particular property supports.
						string typessupported = "";
						if (data.size() == 0)
						{
							//Send what properties we support
							typessupported = "\"running_status_speedometer\",\"running_status_engine_speed\",\"running_status_steering_wheel_angle\",\"running_status_transmission_gear_status\"";
							
							PropertyList foo = sinkManager->getSupportedProperties();
							PropertyList::const_iterator i=foo.cbegin();
							while (i != foo.cend())
							{
								typessupported.append(",\"").append((*i)).append("\"");
								i++;
							}
						}
						else
						{
							//Send what events a particular property supports
							if (data.front()== "running_status_speedometer")
							{
								typessupported = "\"get\",\"subscribe\",\"unsubscribe\",\"getSupportedEventTypes\"";
							}
							else if (data.front()== "running_status_engine_speed")
							{
								typessupported = "\"get\",\"subscribe\",\"unsubscribe\",\"getSupportedEventTypes\"";
							}
							else if (data.front() == "running_status_steering_wheel_angle")
							{
								typessupported = "\"get\",\"subscribe\",\"unsubscribe\",\"getSupportedEventTypes\"";
							}
							else if (data.front() == "running_status_transmission_gear_status")
							{
								typessupported = "\"get\",\"subscribe\",\"unsubscribe\",\"getSupportedEventTypes\"";
							}
							else
							{
								PropertyList foo = sinkManager->getSupportedProperties();
								if (ListPlusPlus<VehicleProperty::Property>(&foo).contains(data.front()))
								{
									//sinkManager->addSingleShotSink(wsi,data.front(),id);
									typessupported = "\"get\",\"subscribe\",\"unsubscribe\",\"getSupportedEventTypes\"";
								}
							}
						}
						stringstream s;
						string s2;
						s << "{\"type\":\"methodReply\",\"name\":\"getSupportedEventTypes\",\"data\":[" << typessupported << "],\"transactionid\":\"" << id << "\"}";
						string replystr = s.str();
						DebugOut() << __SMALLFILE__ << ":" << __LINE__ << " JSON Reply: " << replystr << "\n";
						//printf("Reply: %s\n",replystr.c_str());
						char *new_response = new char[LWS_SEND_BUFFER_PRE_PADDING + strlen(replystr.c_str()) + LWS_SEND_BUFFER_POST_PADDING];
						new_response+=LWS_SEND_BUFFER_PRE_PADDING;
						strcpy(new_response,replystr.c_str());
						libwebsocket_write(wsi, (unsigned char*)new_response, strlen(new_response), LWS_WRITE_TEXT);
						delete (char*)(new_response-LWS_SEND_BUFFER_PRE_PADDING);
					}
					else
					{
						DebugOut(0)<<"Unknown method called."<<endl;
					}
				}
			}

			
			///TODO: this will probably explode:
			//mlc: I agree with Kevron here, it does explode.
			//if(error) g_error_free(error);

			g_object_unref(reader);
			g_object_unref(parser);


			
			break;
		}
		case LWS_CALLBACK_ADD_POLL_FD:
		{
			//printf("Adding poll %i\n",sinkManager);
			//DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Adding poll" << (int)sinkManager << "\n";
			if (sinkManager != 0)
			{
				sinkManager->addPoll((int)(long)user);
			}
			break;
		}
		case LWS_CALLBACK_DEL_POLL_FD:
		{
			sinkManager->removePoll((int)(long)user);
			break;
		}
		case LWS_CALLBACK_SET_MODE_POLL_FD:
		{
			//Set the poll mode
			break;
		}
		case LWS_CALLBACK_CLEAR_MODE_POLL_FD:
		{
			//Don't handle this yet.
			break;
		}
		default:
		{
			//printf("Unhandled callback: %i\n",reason);
			DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Unhandled callback:" << reason << "\n";
			break;
		}
	}
	return 0; 
}
예제 #16
0
/* Save key/values on the table in the stack if the value is an
 * object or an array, it calls recursively the function again.
 *
 * @param L, pointer to the L with nil on top of it;
 * @param reader, pointed to the first element of main object;
 *
 * returns: the table in the stack with all json values
 */
static void
build_table_from_json_reader (lua_State *L,
                              JsonReader *reader)
{
  const GError *err = json_reader_get_error (reader);
  if (err != NULL) {
    GRL_WARNING ("Error when building json: %s", err->message);
    return;
  }

  if (lua_isnil (L, -1)) {
    /* In the first execution of this recursive call, the main json object
     * does not have a member name. The nil is in the top of the stack and
     * it shall be converted to the table with json content */
    lua_pop (L, 1);

  } else if (lua_istable (L, -1)) {
    const gchar *member_name = json_reader_get_member_name (reader);
    if (member_name)
      lua_pushstring (L, member_name);

  } else if (!lua_isnumber (L, -1)) {
    GRL_DEBUG ("getting value to either table or array");
    return;
  }

  if (json_reader_is_object (reader)) {
    guint index_member = 0;
    guint num_members = json_reader_count_members (reader);

    lua_createtable (L, num_members, 0);
    for (index_member = 0; index_member < num_members; index_member++) {
      json_reader_read_element (reader, index_member);
      build_table_from_json_reader (L, reader);
      json_reader_end_element (reader);
    }

  } else if (json_reader_is_array (reader)) {
    guint index_element = 0;
    guint num_elements = json_reader_count_elements (reader);

    lua_createtable (L, num_elements, 0);
    for (index_element = 0; index_element < num_elements; index_element++) {
      json_reader_read_element (reader, index_element);
      lua_pushinteger (L, index_element + 1);
      build_table_from_json_reader (L, reader);
      json_reader_end_element (reader);
    }

  } else if (json_reader_is_value (reader)) {
    if (json_reader_get_null_value (reader)) {
      lua_pushnil (L);
    } else {
      /* value of the element */
      JsonNode *value = json_reader_get_value (reader);
      switch (json_node_get_value_type (value)) {
      case G_TYPE_STRING:
        lua_pushstring (L, json_reader_get_string_value (reader));
        break;
      case G_TYPE_INT64:
        lua_pushinteger (L, json_reader_get_int_value (reader));
        break;
      case G_TYPE_DOUBLE:
        lua_pushnumber (L, json_reader_get_double_value (reader));
        break;
      case G_TYPE_BOOLEAN:
        lua_pushnumber (L, json_reader_get_boolean_value (reader));
        break;
      default:
        GRL_DEBUG ("'%d' (json-node-type) is not being handled",
                   (gint) json_node_get_value_type (value));
        lua_pushnil (L);
      }
    }
  }

  if (lua_gettop (L) > 3) {
    /* save this key/value on previous table */
    lua_settable (L, -3);
  }
}
예제 #17
0
static gboolean dt_noiseprofile_verify(JsonParser *parser)
{
  JsonReader *reader = NULL;
  gboolean valid = TRUE;

  dt_print(DT_DEBUG_CONTROL, "[noiseprofile] verifying noiseprofile file\n");

  JsonNode *root = json_parser_get_root(parser);
  if(!root) _ERROR("can't get the root node");

  reader = json_reader_new(root);

  if(!json_reader_read_member(reader, "version")) _ERROR("can't find file version.");

  // check the file version
  const int version = json_reader_get_int_value(reader);
  json_reader_end_member(reader);

  if(version != DT_NOISE_PROFILE_VERSION) _ERROR("file version is not what this code understands");

  if(!json_reader_read_member(reader, "noiseprofiles")) _ERROR("can't find `noiseprofiles' entry.");

  if(!json_reader_is_array(reader)) _ERROR("`noiseprofiles' is supposed to be an array");

  // go through all makers
  const int n_makers = json_reader_count_elements(reader);
  dt_print(DT_DEBUG_CONTROL, "[noiseprofile] found %d makers\n", n_makers);
  for(int i = 0; i < n_makers; i++)
  {
    if(!json_reader_read_element(reader, i)) _ERROR("can't access maker at position %d / %d", i+1, n_makers);

    if(!json_reader_read_member(reader, "maker")) _ERROR("missing `maker`");

    dt_print(DT_DEBUG_CONTROL, "[noiseprofile] found maker `%s'\n", json_reader_get_string_value(reader));
    // go through all models and check those
    json_reader_end_member(reader);

    if(!json_reader_read_member(reader, "models")) _ERROR("missing `models`");

    const int n_models = json_reader_count_elements(reader);
    dt_print(DT_DEBUG_CONTROL, "[noiseprofile] found %d models\n", n_models);
    for(int j = 0; j < n_models; j++)
    {
      if(!json_reader_read_element(reader, j)) _ERROR("can't access model at position %d / %d", j+1, n_models);

      if(!json_reader_read_member(reader, "model")) _ERROR("missing `model`");

      dt_print(DT_DEBUG_CONTROL, "[noiseprofile] found %s\n", json_reader_get_string_value(reader));
      json_reader_end_member(reader);

      if(!json_reader_read_member(reader, "profiles")) _ERROR("missing `profiles`");

      const int n_profiles = json_reader_count_elements(reader);
      dt_print(DT_DEBUG_CONTROL, "[noiseprofile] found %d profiles\n", n_profiles);
      for(int k = 0; k < n_profiles; k++)
      {
        if(!json_reader_read_element(reader, k)) _ERROR("can't access profile at position %d / %d", k+1, n_profiles);

        gchar** member_names = json_reader_list_members(reader);

        // name
        if(!is_member(member_names, "name"))
        {
          g_strfreev(member_names);
          _ERROR("missing `name`");
        }

        // iso
        if(!is_member(member_names, "iso"))
        {
          g_strfreev(member_names);
          _ERROR("missing `iso`");
        }

        // a
        if(!is_member(member_names, "a"))
        {
          g_strfreev(member_names);
          _ERROR("missing `a`");
        }
        json_reader_read_member(reader, "a");
        if(json_reader_count_elements(reader) != 3)
        {
          g_strfreev(member_names);
          _ERROR("`a` with size != 3");
        }
        json_reader_end_member(reader);

        // b
        if(!is_member(member_names, "b"))
        {
          g_strfreev(member_names);
          _ERROR("missing `b`");
        }
        json_reader_read_member(reader, "b");
        if(json_reader_count_elements(reader) != 3)
        {
          g_strfreev(member_names);
          _ERROR("`b` with size != 3");
        }
        json_reader_end_member(reader);

        json_reader_end_element(reader);

        g_strfreev(member_names);
      } // profiles

      json_reader_end_member(reader);
      json_reader_end_element(reader);
    } // models

    json_reader_end_member(reader);
    json_reader_end_element(reader);
  } // makers

  json_reader_end_member(reader);

  dt_print(DT_DEBUG_CONTROL, "[noiseprofile] verifying noiseprofile completed\n");

end:
  if(reader) g_object_unref(reader);
  return valid;
}
예제 #18
0
GList *dt_noiseprofile_get_matching(const dt_image_t *cimg)
{
  JsonParser *parser = darktable.noiseprofile_parser;
  JsonReader *reader = NULL;
  GList *result = NULL;

  if(!parser) goto end;

  dt_print(DT_DEBUG_CONTROL, "[noiseprofile] looking for maker `%s', model `%s'\n", cimg->camera_maker, cimg->camera_model);

  JsonNode *root = json_parser_get_root(parser);

  reader = json_reader_new(root);

  json_reader_read_member(reader, "noiseprofiles");

  // go through all makers
  const int n_makers = json_reader_count_elements(reader);
  dt_print(DT_DEBUG_CONTROL, "[noiseprofile] found %d makers\n", n_makers);
  for(int i = 0; i < n_makers; i++)
  {
    json_reader_read_element(reader, i);

    json_reader_read_member(reader, "maker");

    if(g_strstr_len(cimg->camera_maker, -1, json_reader_get_string_value(reader)))
    {
      dt_print(DT_DEBUG_CONTROL, "[noiseprofile] found `%s' as `%s'\n", cimg->camera_maker, json_reader_get_string_value(reader));
      // go through all models and check those
      json_reader_end_member(reader);

      json_reader_read_member(reader, "models");

      const int n_models = json_reader_count_elements(reader);
      dt_print(DT_DEBUG_CONTROL, "[noiseprofile] found %d models\n", n_models);
      for(int j = 0; j < n_models; j++)
      {
        json_reader_read_element(reader, j);

        json_reader_read_member(reader, "model");

        if(!g_strcmp0(cimg->camera_model, json_reader_get_string_value(reader)))
        {
          dt_print(DT_DEBUG_CONTROL, "[noiseprofile] found %s\n", cimg->camera_model);
          // we got a match, return at most bufsize elements
          json_reader_end_member(reader);

          json_reader_read_member(reader, "profiles");

          const int n_profiles = json_reader_count_elements(reader);
          dt_print(DT_DEBUG_CONTROL, "[noiseprofile] found %d profiles\n", n_profiles);
          for(int k = 0; k < n_profiles; k++)
          {
            dt_noiseprofile_t tmp_profile = { 0 };

            json_reader_read_element(reader, k);

            gchar** member_names = json_reader_list_members(reader);

            // do we want to skip this entry?
            if(is_member(member_names, "skip"))
            {
              json_reader_read_member(reader, "skip");
              gboolean skip = json_reader_get_boolean_value(reader);
              json_reader_end_member(reader);
              if(skip)
              {
                json_reader_end_element(reader);
                g_strfreev(member_names);
                continue;
              }
            }

            // maker
            tmp_profile.maker = g_strdup(cimg->camera_maker);

            // model
            tmp_profile.model = g_strdup(cimg->camera_model);

            // name
            json_reader_read_member(reader, "name");
            tmp_profile.name = g_strdup(json_reader_get_string_value(reader));
            json_reader_end_member(reader);

            // iso
            json_reader_read_member(reader, "iso");
            tmp_profile.iso = json_reader_get_double_value(reader);
            json_reader_end_member(reader);

            // a
            json_reader_read_member(reader, "a");
            for(int a = 0; a < 3; a++)
            {
              json_reader_read_element(reader, a);
              tmp_profile.a[a] = json_reader_get_double_value(reader);
              json_reader_end_element(reader);
            }
            json_reader_end_member(reader);

            // b
            json_reader_read_member(reader, "b");
            for(int b = 0; b < 3; b++)
            {
              json_reader_read_element(reader, b);
              tmp_profile.b[b] = json_reader_get_double_value(reader);
              json_reader_end_element(reader);
            }
            json_reader_end_member(reader);

            json_reader_end_element(reader);

            // everything worked out, add tmp_profile to result
            dt_noiseprofile_t *new_profile = (dt_noiseprofile_t *)malloc(sizeof(dt_noiseprofile_t));
            *new_profile = tmp_profile;
            result = g_list_append(result, new_profile);

            g_strfreev(member_names);
          } // profiles

          goto end;
        }

        json_reader_end_member(reader);
        json_reader_end_element(reader);
      } // models
    }

    json_reader_end_member(reader);
    json_reader_end_element(reader);
  } // makers

  json_reader_end_member(reader);

end:
  if(reader) g_object_unref(reader);
  if(result) result = g_list_sort(result, _sort_by_iso);
  return result;
}
예제 #19
0
static gboolean
handler (GThreadedSocketService *service,
         GSocketConnection      *connection,
         GSocketListener        *listener,
         gpointer                user_data)
{
  GLibJsonRpcServerPrivate *jsonrpc_server = (GLibJsonRpcServerPrivate*)user_data;
  GError *error = NULL;
  
  // Check if it is a local connection. - This doesn't work!
  GSocketAddress *sockaddr
    = g_socket_connection_get_remote_address(connection,
                                             &error);
  GInetAddress *addr = g_inet_socket_address_get_address(G_INET_SOCKET_ADDRESS(sockaddr));

  if (!jsonrpc_server->allow_non_loopback_connections)
    {
#if 0
      // Why doesn't this work?
      if (!g_inet_address_get_is_loopback(addr))
        return TRUE; // just fail
#endif
      
      gchar *addr_string = g_inet_address_to_string(addr);
      gboolean is_local = g_strstr_len(addr_string, -1, "127.0.0.1") != NULL;
      g_free(addr_string);
      if (!is_local) 
        return TRUE; // silently fail
    }

  GOutputStream *out;
  GInputStream *in;
  char buffer[1024];
  gssize size;

  out = g_io_stream_get_output_stream (G_IO_STREAM (connection));
  in = g_io_stream_get_input_stream (G_IO_STREAM (connection));

  // Read the http header
  gboolean skip_header = TRUE;
  JsonParser *parser = json_parser_new();
  GString *json_string = g_string_new("");
  while (0 < (size = g_input_stream_read (in, buffer,
                                          sizeof buffer, NULL, NULL)))
    {
      int header_size = 0;
      
      if (skip_header)
        {
          gchar *head_end = g_strstr_len(buffer, size,
                                         "\r\n\r\n");
          if (head_end > 0)
            header_size = head_end - buffer;
          else
            continue;
        }
      
      g_string_append_len(json_string, buffer+header_size, size-header_size);
      if (json_parser_load_from_data(parser, json_string->str, -1, &error))
        break;
      else
        g_error_free(error);
    }

  // TBD:   raise error if there was a syntax error
  g_string_free(json_string, TRUE);

  // Get params object without the reader 
  JsonNode *root = json_parser_get_root(parser);
  JsonObject *root_object = json_node_get_object(root);
  JsonNode* params = json_object_get_member(root_object, "params");

  // Use reader for method and id
  JsonReader *reader = json_reader_new(json_parser_get_root(parser));
  json_reader_read_member (reader, "method");
  const gchar *method = json_reader_get_string_value (reader);
  json_reader_end_member (reader);
  
  json_reader_read_member (reader, "id");
  gint64 id = json_reader_get_int_value(reader);
  json_reader_end_member (reader);

  // Build the response which is either a response object or an error object
  JsonNode *response = NULL;
  
  /* Call the callback */
  command_hash_value_t *command_val = NULL;
  if (method)
    command_val = g_hash_table_lookup(jsonrpc_server->command_hash,
                                      method);
  if (!command_val)
    response = create_fault_msg_response(-2, "No such method!",id);
  else if (command_val->async_callback)
    {
      if (jsonrpc_server->async_busy)
        response = create_fault_msg_response(-2, "Busy!",id);
      else
        {
          // With the embedding of the mutex in the query we should
          // be able to handle more than one connection, so there
          // is no need to protect against a busy state.
          // jsonrpc_server->async_busy = TRUE;
          GLibJsonRpcAsyncQueryPrivate *query = glib_jsonrpc_server_query_new((GLibJsonRpcServer*)jsonrpc_server);
          
          // Create a secondary main loop
          (*command_val->async_callback)((GLibJsonRpcServer*)jsonrpc_server,
                                         (GLibJsonRpcAsyncQuery*)query,
                                         method,
                                         params,
                                         command_val->user_data);
          
          // Lock on a mutex
          g_mutex_lock(&query->mutex);
          g_cond_wait(&query->cond, &query->mutex);
          g_mutex_unlock(&query->mutex);

          if (query->error_num != 0)
            response = create_fault_value_response(query->error_num,query->reply,id);
          else
            response = create_response(query->reply, id);
          jsonrpc_server->async_busy = FALSE;

          // Erase the query
          glib_jsonrpc_async_query_free(query);
        }
    }
  else
    {
      JsonNode *reply;

      int ret = (*command_val->callback)((GLibJsonRpcServer*)jsonrpc_server,
                                         method,
                                         params,
                                         &reply,
                                         command_val->user_data);

      if (ret == 0)
        response = create_response(reply,id);
      else
        // For faults expect a string response containing the error
        response = create_fault_value_response(ret, reply,id);

      if (reply)
        json_node_free(reply);
    }

  if (response)
    {
      GString *response_string = g_string_new("");
  
      // Serialize response into content_string
      JsonGenerator *gen = json_generator_new ();
      gsize len;
      json_generator_set_root (gen, response);
      json_node_free(response);
      gchar *content_string = json_generator_to_data(gen, &len);
      g_object_unref (gen);

      g_string_append_printf(response_string,
                             "HTTP/1.1 200 OK\r\n"
                             "Connection: close\r\n"
                             "Content-Length: %d\r\n"
                             "Content-Type: text/xml\r\n"
                             "Date: Fri, 1 Jan 2000 00:00:00 GMT\r\n"
                             "Server: GlibJsonRPC server\r\n"
                             "\r\n"
                             "%s",
                             (int)len,
                             content_string
                             );
      g_free(content_string);
  
      g_output_stream_write (out,
                             response_string->str,
                             response_string->len,
                             NULL,NULL);
      g_string_free(response_string, TRUE);
    }

  g_object_unref(parser);

  return TRUE;
}
예제 #20
0
/* The error format used by the Google Tasks API doesn’t seem to be documented
 * anywhere, which is a little frustrating. Here’s an example of it:
 *     {
 *      "error": {
 *       "errors": [
 *        {
 *         "domain": "usageLimits",
 *         "reason": "dailyLimitExceededUnreg",
 *         "message": "Daily Limit for Unauthenticated Use Exceeded.",
 *         "extendedHelp": "https://code.google.com/apis/console"
 *        }
 *       ],
 *       "code": 403,
 *       "message": "Daily Limit for Unauthenticated Use Exceeded."
 *      }
 *     }
 * or:
 *     {
 *      "error": {
 *       "errors": [
 *        {
 *         "domain": "global",
 *         "reason": "authError",
 *         "message": "Invalid Credentials",
 *         "locationType": "header",
 *         "location": "Authorization"
 *        }
 *       ],
 *       "code": 401,
 *       "message": "Invalid Credentials"
 *      }
 *     }
 */
static void
parse_error_response (GDataService *self, GDataOperationType operation_type,
                      guint status, const gchar *reason_phrase,
                      const gchar *response_body, gint length, GError **error)
{
	JsonParser *parser = NULL;  /* owned */
	JsonReader *reader = NULL;  /* owned */
	gint i;
	GError *child_error = NULL;

	if (response_body == NULL) {
		goto parent;
	}

	if (length == -1) {
		length = strlen (response_body);
	}

	parser = json_parser_new ();
	if (!json_parser_load_from_data (parser, response_body, length,
	                                 &child_error)) {
		goto parent;
	}

	reader = json_reader_new (json_parser_get_root (parser));

	/* Check that the outermost node is an object. */
	if (!json_reader_is_object (reader)) {
		goto parent;
	}

	/* Grab the ‘error’ member, then its ‘errors’ member. */
	if (!json_reader_read_member (reader, "error") ||
	    !json_reader_is_object (reader) ||
	    !json_reader_read_member (reader, "errors") ||
	    !json_reader_is_array (reader)) {
		goto parent;
	}

	/* Parse each of the errors. Return the first one, and print out any
	 * others. */
	for (i = 0; i < json_reader_count_elements (reader); i++) {
		const gchar *domain, *reason, *message, *extended_help;
		const gchar *location_type, *location;

		/* Parse the error. */
		if (!json_reader_read_element (reader, i) ||
		    !json_reader_is_object (reader)) {
			goto parent;
		}

		json_reader_read_member (reader, "domain");
		domain = json_reader_get_string_value (reader);
		json_reader_end_member (reader);

		json_reader_read_member (reader, "reason");
		reason = json_reader_get_string_value (reader);
		json_reader_end_member (reader);

		json_reader_read_member (reader, "message");
		message = json_reader_get_string_value (reader);
		json_reader_end_member (reader);

		json_reader_read_member (reader, "extendedHelp");
		extended_help = json_reader_get_string_value (reader);
		json_reader_end_member (reader);

		json_reader_read_member (reader, "locationType");
		location_type = json_reader_get_string_value (reader);
		json_reader_end_member (reader);

		json_reader_read_member (reader, "location");
		location = json_reader_get_string_value (reader);
		json_reader_end_member (reader);

		/* End the error element. */
		json_reader_end_element (reader);

		/* Create an error message, but only for the first error */
		if (error == NULL || *error == NULL) {
			if (g_strcmp0 (domain, "usageLimits") == 0 &&
			    g_strcmp0 (reason,
			               "dailyLimitExceededUnreg") == 0) {
				/* Daily Limit for Unauthenticated Use
				 * Exceeded. */
				g_set_error (error, GDATA_SERVICE_ERROR,
				             GDATA_SERVICE_ERROR_API_QUOTA_EXCEEDED,
				             _("You have made too many API "
				               "calls recently. Please wait a "
				               "few minutes and try again."));
			} else if (g_strcmp0 (domain, "global") == 0 &&
			           (g_strcmp0 (reason, "authError") == 0 ||
			            g_strcmp0 (reason, "required") == 0)) {
				/* Authentication problem */
				g_set_error (error, GDATA_SERVICE_ERROR,
				             GDATA_SERVICE_ERROR_AUTHENTICATION_REQUIRED,
				             _("You must be authenticated to "
				               "do this."));
			} else {
				/* Unknown or validation (protocol) error. Fall
				 * back to working off the HTTP status code. */
				g_warning ("Unknown error code ‘%s’ in domain "
				           "‘%s’ received with location type "
				           "‘%s’, location ‘%s’, extended help "
				           "‘%s’ and message ‘%s’.",
				           reason, domain, location_type,
				           location, extended_help, message);

				goto parent;
			}
		} else {
			/* For all errors after the first, log the error in the
			 * terminal. */
			g_debug ("Error message received in response: domain "
			         "‘%s’, reason ‘%s’, extended help ‘%s’, "
			         "message ‘%s’, location type ‘%s’, location "
			         "‘%s’.",
			         domain, reason, extended_help, message,
			         location_type, location);
		}
	}

	/* End the ‘errors’ and ‘error’ members. */
	json_reader_end_element (reader);
	json_reader_end_element (reader);

	g_clear_object (&reader);
	g_clear_object (&parser);

	/* Ensure we’ve actually set an error message. */
	g_assert (error == NULL || *error != NULL);

	return;

parent:
	g_clear_object (&reader);
	g_clear_object (&parser);

	/* Chain up to the parent class */
	GDATA_SERVICE_CLASS (gdata_tasks_service_parent_class)->parse_error_response (self, operation_type, status, reason_phrase,
	                                                                              response_body, length, error);
}
예제 #21
0
파일: savestate.c 프로젝트: auchter/spop
static void restore_state(session_callback_type type, gpointer data, gpointer user_data) {
    JsonParser* jp = NULL;
    JsonReader* jr = NULL;

    const gchar* sqs;
    saved_state* s = NULL;

    GError* err = NULL;

    /* Is it the callback we're interested in? */
    if (type != SPOP_SESSION_LOGGED_IN)
        return;

    /* First disable the callback so it's not called again */
    session_remove_callback(restore_state, NULL);

    g_debug("savestate: reading saved state...");
    s = g_new0(saved_state, 1);

    /* Read and parse state file */
    jp = json_parser_new();
    if (!json_parser_load_from_file(jp, g_state_file_path, &err)) {
        g_warning("savestate: error while reading state file: %s", err->message);
        goto restorestate_error;
    }

    jr = json_reader_new(json_parser_get_root(jp));

    /* Read basic state */
    if (!json_reader_read_member(jr, "status")) goto restorestate_jr_error;
    sqs = json_reader_get_string_value(jr);
    json_reader_end_member(jr);
    if      (strcmp(sqs, "stopped")) s->qs = STOPPED;
    else if (strcmp(sqs, "playing")) s->qs = PLAYING;
    else if (strcmp(sqs, "paused"))  s->qs = PAUSED;
    else {
        g_warning("savestate: bad value for queue status: %s", sqs);
        goto restorestate_error;
    }

    if (!json_reader_read_member(jr, "repeat")) goto restorestate_jr_error;
    s->repeat = json_reader_get_boolean_value(jr);
    json_reader_end_member(jr);

    if (!json_reader_read_member(jr, "shuffle")) goto restorestate_jr_error;
    s->shuffle = json_reader_get_boolean_value(jr);
    json_reader_end_member(jr);

    if (!json_reader_read_member(jr, "current_track")) goto restorestate_jr_error;
    s->cur_track = json_reader_get_int_value(jr);
    json_reader_end_member(jr);

    /* Now read tracks URIs */
    if (!json_reader_read_member(jr, "tracks")) goto restorestate_jr_error;
    if (!json_reader_is_array(jr)) {
        g_warning("savestate: error while parsing JSON: tracks is not an array");
        goto restorestate_error;
    }
    gint tracks = json_reader_count_elements(jr);
    if (s->cur_track >= tracks) {
        g_warning("savestate: incoherent state file: cur_track >= tracks");
        goto restorestate_error;
    }

    s->tracks = g_array_sized_new(FALSE, FALSE, sizeof(sp_track*), tracks);
    if (!s->tracks)
        g_error("Can't allocate array of %d tracks.", tracks);

    size_t i;
    gboolean can_restore_now = TRUE;
    for (i=0; i < tracks; i++) {
        json_reader_read_element(jr, i);
        const gchar* uri = json_reader_get_string_value(jr);
        json_reader_end_element(jr);

        sp_link* lnk = sp_link_create_from_string(uri);
        sp_linktype lt = sp_link_type(lnk);
        if (lt != SP_LINKTYPE_TRACK) {
            g_warning("savestate: invalid link type for track %zu: %d", i, lt);
            sp_link_release(lnk);
            goto restorestate_error;
        }
        sp_track* tr = sp_link_as_track(lnk);
        sp_track_add_ref(tr);
        sp_link_release(lnk);
        g_array_append_val(s->tracks, tr);
        if (!sp_track_is_loaded(tr))
            can_restore_now = FALSE;
    }

    /* If possible, restore now, else wait for all tracks to be loaded */
    if (can_restore_now)
        really_restore_state(s);
    else {
        g_timeout_add(100, (GSourceFunc) really_restore_state, s);
        g_debug("savestate: waiting for all tracks to be loaded before restoring saved state...");
    }

    /* Add a notification callback */
    if (!interface_notify_add_callback(savestate_notification_callback, NULL))
        g_error("Could not add savestate callback.");

    goto restorestate_clean;

 restorestate_jr_error:
    err = (GError*) json_reader_get_error(jr);
    g_warning("savestate: error while parsing JSON: %s", err->message);

 restorestate_error:
    if (s) {
        if (s->tracks)
            g_array_free(s->tracks, TRUE);
        g_free(s);
    }

 restorestate_clean:
    if (jp)
        g_object_unref(jp);
    if (jr)
        g_object_unref(jr);
}
예제 #22
0
static void get_language_names(GList *languages)
{
#ifdef HAVE_ISO_CODES

  JsonReader *reader = NULL;
  JsonParser *parser = NULL;
  GError *error = NULL;

#if defined(_WIN32) && !defined(MSYS2_INSTALL) // TODO: add osx?
  char datadir[PATH_MAX] = { 0 };
  dt_loc_get_datadir(datadir, sizeof(datadir));
  char *filename = g_build_filename(datadir, "..",  "iso-codes", "json", "iso_639-2.json", NULL);
#else
  char *filename = g_build_filename(ISO_CODES_LOCATION, "iso_639-2.json", NULL);
#endif

  if(!g_file_test(filename, G_FILE_TEST_EXISTS))
  {
    fprintf(stderr, "[l10n] error: can't open iso-codes file `%s'\n"
                    "       there won't be nicely translated language names in the preferences.\n", filename);
    goto end;
  }

#if defined(_WIN32) && !defined(MSYS2_INSTALL) // TODO: add osx?
  // on windows we are shipping the translations of iso-codes along ours
  char *localedir = g_build_filename(datadir, "..", "locale", NULL);
  bindtextdomain("iso_639", localedir);
  g_free(localedir);
#else
  bindtextdomain("iso_639", ISO_CODES_LOCALEDIR);
#endif

  bind_textdomain_codeset("iso_639", "UTF-8");

  parser = json_parser_new();
  if(!json_parser_load_from_file(parser, filename, &error))
  {
    fprintf(stderr, "[l10n] error: parsing json from `%s' failed\n%s\n", filename, error->message);
    goto end;
  }

  // go over the json
  JsonNode *root = json_parser_get_root(parser);
  if(!root)
  {
    fprintf(stderr, "[l10n] error: can't get root node of `%s'\n", filename);
    goto end;
  }

  reader = json_reader_new(root);

  if(!json_reader_read_member(reader, "639-2"))
  {
    fprintf(stderr, "[l10n] error: unexpected layout of `%s'\n", filename);
    goto end;
  }

  if(!json_reader_is_array(reader))
  {
    fprintf(stderr, "[l10n] error: unexpected layout of `%s'\n", filename);
    goto end;
  }

  int n_elements = json_reader_count_elements(reader);
  for(int i = 0; i < n_elements; i++)
  {
    json_reader_read_element(reader, i);
    if(!json_reader_is_object(reader))
    {
      fprintf(stderr, "[l10n] error: unexpected layout of `%s' (element %d)\n", filename, i);
      goto end;
    }

    const char *alpha_2 = NULL, *alpha_3 = NULL, *name = NULL;
    if(json_reader_read_member(reader, "alpha_2"))
      alpha_2 = json_reader_get_string_value(reader);
    json_reader_end_member(reader); // alpha_2

    if(json_reader_read_member(reader, "alpha_3"))
      alpha_3 = json_reader_get_string_value(reader);
    json_reader_end_member(reader); // alpha_3

    if(json_reader_read_member(reader, "name"))
      name = json_reader_get_string_value(reader);
    json_reader_end_member(reader); // name

    if(name && (alpha_2 || alpha_3))
    {
      // check if alpha_2 or alpha_3 is in our translations
      for(GList *iter = languages; iter; iter = g_list_next(iter))
      {
        dt_l10n_language_t *language = (dt_l10n_language_t *)iter->data;
        if(!g_strcmp0(language->base_code, alpha_2) || !g_strcmp0(language->base_code, alpha_3))
        {
          // code taken in parts from GIMP's gimplanguagestore-parser.c
          g_setenv("LANGUAGE", language->code, TRUE);
          setlocale (LC_ALL, language->code);

          char *localized_name = g_strdup(dgettext("iso_639", name));

          /* If original and localized names are the same for other than English,
           * maybe localization failed. Try now in the main dialect. */
          if(g_strcmp0(name, localized_name) == 0 &&
             g_strcmp0(language->code, language->base_code) != 0)
          {
            g_free(localized_name);

            g_setenv("LANGUAGE", language->base_code, TRUE);
            setlocale (LC_ALL, language->base_code);

            localized_name = g_strdup(dgettext("iso_639", name));
          }

          /*  there might be several language names; use the first one  */
          char *semicolon = strchr(localized_name, ';');

          if(semicolon)
          {
            char *tmp = localized_name;
            localized_name = g_strndup(localized_name, semicolon - localized_name);
            g_free(tmp);
          }

          // we initialize the name to the language code to have something on systems lacking iso-codes, so free it!
          g_free(language->name);
          language->name = g_strdup_printf("%s (%s)%s", localized_name, language->code, language->is_default ? " *" : "");
          g_free(localized_name);

          // we can't break out of the loop here. at least pt is in our list twice!
        }
      }
    }
    else
      fprintf(stderr, "[l10n] error: element %d has no name, skipping\n", i);

    json_reader_end_element(reader);
  }

  json_reader_end_member(reader); // 639-2

end:
  // cleanup
  g_free(filename);
  if(error) g_error_free(error);
  if(reader) g_object_unref(reader);
  if(parser) g_object_unref(parser);

#endif // HAVE_ISO_CODES
}
예제 #23
0
void
render_json (const char *filename)
{
  JsonParser *parser;
  JsonNode *root;
  GError *error;
  parser = json_parser_new ();

  error = NULL;
  json_parser_load_from_file (parser, filename, &error);
  if (error) {
    g_print ("Parsing error `%s':\n %s\n", filename, error->message);
    g_error_free (error);
    g_object_unref (parser);
    exit (0);
  }

  root = json_parser_get_root (parser);

  JsonReader *reader = json_reader_new (root);
  GESTimeline *timeline;

  json_reader_read_member (reader, "composition");

  // comp strings
  const char *name = getString (reader, "name");
  //const char *src_dir = getString (reader, "src-dir");
  //g_print ("Source Directory: %s\nName: %s\n", src_dir, name);

  // comp ints
  int width = getInt (reader, "width");
  int height = getInt (reader, "height");
  int fps = getInt (reader, "fps");

  gboolean transparency = TRUE;

  if (is_in_members (reader, "transparency")) {
    transparency = getBool (reader, "transparency");
  }

  gboolean absolute_paths = FALSE;

  if (is_in_members (reader, "absolute_paths")) {
    absolute_paths = getBool (reader, "absolute_paths");
  }

  g_print ("Resolution: %dx%d, FPS: %d\n", width, height, fps);

  timeline = ges_timeline_new_audio_video ();

  int i;
  json_reader_read_member (reader, "layers");

  for (i = 0; i < json_reader_count_elements (reader); i++) {
    json_reader_read_element (reader, i);

    GESLayer *layer = ges_layer_new ();

    g_object_set (layer, "priority", i, NULL);

    if (is_in_members (reader, "autotransition")) {
      gboolean autotransition = getBool (reader, "autotransition");
      if (autotransition)
        g_print ("Auto Transitions on.\n");
      g_object_set (layer, "auto-transition", autotransition, NULL);
    }

    ges_timeline_add_layer (timeline, layer);

    getClips (reader, layer, GES_TRACK_TYPE_UNKNOWN, absolute_paths);

    json_reader_end_element (reader);
  }
  json_reader_end_member (reader);

  ges_timeline_commit (timeline);

  const gchar *xges_path = g_strconcat ("file://", filename, ".xges", NULL);

  ges_timeline_save_xges (timeline, xges_path);

  //free(xges_path);

  // formats
  GESRendererProfile res =
      { width, height, fps, PROFILE_AAC_H264_QUICKTIME, NULL };
  if (!transparency) {
    g_print ("Deactivating transparency\n");
    res.format = "I420";
  }

  json_reader_read_member (reader, "formats");
  for (i = 0; i < json_reader_count_elements (reader); i++) {
    json_reader_read_element (reader, i);
    const char *format = json_reader_get_string_value (reader);
    json_reader_end_element (reader);
    g_print ("format: %s\n", format);
    EncodingProfile prof = PROFILE_AAC_H264_QUICKTIME;
    if (strcmp (format, "webm") == 0) {
      prof = PROFILE_VORBIS_VP8_WEBM;
    } else if (strcmp (format, "mkv") == 0) {
      prof = PROFILE_VORBIS_H264_MATROSKA;
    } else if (strcmp (format, "mp4") == 0) {
      prof = PROFILE_AAC_H264_QUICKTIME;
    } else if (strcmp (format, "ogg") == 0) {
      prof = PROFILE_VORBIS_THEORA_OGG;
    }
    res.profile = prof;
    ges_renderer_render (timeline, name, &res, absolute_paths);
  }
  json_reader_end_member (reader);

  json_reader_end_member (reader);

  g_object_unref (reader);
  g_object_unref (parser);
}