Esempio n. 1
0
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;
}
Esempio n. 2
0
/*!
 * Check a QMP "execute" response message.
 *
 * \param result Response from server.
 * \param bytes Size of \p result.
 * \param expect_empty \c true if the result is expected to be an
 *   empty json message, else \c false.
 *
 * \warning FIXME: no validation performed on non-empty QMP messages yet.
 *
 * \return \c true on success, else \c false.
 */
static gboolean
clr_oci_qmp_check_result (const char *result, gsize bytes,
		gboolean expect_empty)
{
	gboolean      ret;
	JsonParser   *parser = NULL;
	JsonReader   *reader = NULL;
	GError       *error = NULL;
	gint          count = 0;

	g_assert (result);

	parser = json_parser_new ();
	reader = json_reader_new (NULL);

	ret = json_parser_load_from_data (parser, result,
			(gssize)bytes, &error);
	if (! ret) {
		g_critical ("failed to check qmp response: %s",
				error->message);
		g_error_free (error);

		goto out;
	}

	json_reader_set_root (reader, json_parser_get_root (parser));

	ret = json_reader_read_member (reader, "return");
	if (! ret) {
		goto out;
	}

	ret = json_reader_is_object (reader);
	if (! ret) {
		goto out;
	}

	count = json_reader_count_members (reader);
	if (count && expect_empty) {
		g_critical ("expected empty object denoting success, "
				"but found %d members", count);
		goto out;
	}

	ret = true;

out:
	if (reader) {
		json_reader_end_member (reader);
		g_object_unref (reader);
	}

	if (parser) {
		g_object_unref (parser);
	}

	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);
}
Esempio n. 4
0
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;
}
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; 
}
Esempio n. 6
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);
  }
}
Esempio n. 7
0
static gboolean
parse_json (GDataParsable *parsable, JsonReader *reader, gpointer user_data, GError **error)
{
	gboolean success = TRUE;
	gchar *next_uri = NULL;

	/* JSON format: https://developers.google.com/drive/v2/reference/files/list */

	if (gdata_parser_string_from_json_member (reader, "nextLink", P_DEFAULT, &next_uri, &success, error) == TRUE) {
		if (success && next_uri != NULL && next_uri[0] != '\0') {
			GDataLink *_link;

			_link = gdata_link_new (next_uri, "http://www.iana.org/assignments/relation/next");
			_gdata_feed_add_link (GDATA_FEED (parsable), _link);
			g_object_unref (_link);
		}

		g_free (next_uri);
		return success;
	} else if (g_strcmp0 (json_reader_get_member_name (reader), "items") == 0) {
		guint i, elements;

		if (json_reader_is_array (reader) == FALSE) {
			g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR,
			             /* Translators: the parameter is an error message */
			             _("Error parsing JSON: %s"),
			             "JSON node ‘items’ is not an array.");
			return FALSE;
		}

		/* Loop through the elements array. */
		for (i = 0, elements = (guint) json_reader_count_elements (reader); success && i < elements; i++) {
			GDataEntry *entry = NULL;
			GError *child_error = NULL;
			GType entry_type = G_TYPE_INVALID;
			gchar *kind = NULL;
			gchar *mime_type = NULL;

			json_reader_read_element (reader, i);

			if (json_reader_is_object (reader) == FALSE) {
				g_set_error (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR,
				             /* Translators: the parameter is an error message */
				             _("Error parsing JSON: %s"),
				             "JSON node inside ‘items’ is not an object");
				success = FALSE;
				goto continuation;
			}

			get_kind_and_mime_type (reader, &kind, &mime_type, &child_error);
			if (child_error != NULL) {
				g_propagate_error (error, child_error);
				success = FALSE;
				goto continuation;
			}

			if (g_strcmp0 (kind, "drive#file") == 0) {
				entry_type = gdata_documents_utils_get_type_from_content_type (mime_type);
			} else {
				g_warning ("%s files are not handled yet", kind);
			}

			if (entry_type == G_TYPE_INVALID)
				goto continuation;

			entry = GDATA_ENTRY (_gdata_parsable_new_from_json_node (entry_type, reader, NULL, error));
			/* Call the progress callback in the main thread */
			_gdata_feed_call_progress_callback (GDATA_FEED (parsable), user_data, entry);
			_gdata_feed_add_entry (GDATA_FEED (parsable), entry);

		continuation:
			g_clear_object (&entry);
			g_free (kind);
			g_free (mime_type);
			json_reader_end_element (reader);
		}

		return success;
	}

	return GDATA_PARSABLE_CLASS (gdata_documents_feed_parent_class)->parse_json (parsable, reader, user_data, error);
}
Esempio n. 8
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);
}
Esempio n. 9
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
}