int inputTransform(JsonParser *parser, Graph *graph) { JsonNode *root; JsonReader *reader; int num_nodes, num_edges; int i; root = json_parser_get_root(parser); reader = json_reader_new(root); // Is the graph directed ? json_reader_read_member(reader, "oriented") if(json_reader_get_boolean_value(reader)) { graph->directed = DIRECTED; } else { graph->directed = NOT_DIRECTED; } json_reader_end_member(reader); // Get the nodes json_reader_read_member(reader, "nodes"); if(json_reader_is_array(reader)) { // Allocate the memory for the nodes, and for the edges num_nodes = json_reader_count_elements(reader); graph->nodes = malloc(num_nodes * sizeof(Node)); graph->edges = malloc(num_nodes * sizeof(Edge *)); for(i=0; i < num_nodes; i++) { graph->edges[i] = malloc(num_nodes * sizeof(Edge)); } for(i=0; i < num_nodes; i++) { json_reader_read_element(reader, i); readNode(json_reader_get_value(reader), graph); json_reader_end_element(reader); } } json_reader_end_member(reader); // Get the edges json_reader_read_member(reader, "edges"); if(json_reader_is_array(reader)) { for(i=0; i < num_edges; i++) { json_reader_read_element(reader, i); reader(json_reader_get_value(reader), graph); json_reader_end_element(reader); } } json_reader_end_member(reader); return EXIT_SUCCESS; }
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; }
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 GDataFreebaseTopicValueArray * reader_create_value_array (JsonReader *reader, const gchar *property, GError **error) { GDataFreebaseTopicValueArray *array; GDataFreebaseTopicValue *value; TopicValueType type; guint64 count, i; count = reader_get_item_count (reader); if (count <= 0) return NULL; type = reader_get_value_type (reader, property, error); if (type == TYPE_NONE || type == TYPE_URI || type == TYPE_KEY) return NULL; array = value_array_new (type, count); json_reader_read_member (reader, "values"); count = json_reader_count_elements (reader); for (i = 0; i < count; i++) { json_reader_read_element (reader, i); value = reader_create_value (reader, property, type, error); json_reader_end_element (reader); if (value != NULL) value_array_add (array, value); } json_reader_end_member (reader); return array; }
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; }
/* 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); } }
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); }
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; }
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; }
/* 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); }
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 }
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); }
void getClips (JsonReader * reader, GESLayer * layer, GESTrackType type, gboolean absolute_paths) { int i; json_reader_read_member (reader, "clips"); g_print ("= clips =\n"); for (i = 0; i < json_reader_count_elements (reader); i++) { json_reader_read_element (reader, i); const char *src = getString (reader, "src"); int start = getInt (reader, "start"); int in = getInt (reader, "in"); int dur = getInt (reader, "dur"); g_print ("Clip: %s (start: %d, in: %d, dur: %d)\n", src, start, in, dur); GESClip *clip; if (is_in_members (reader, "multi") && getBool (reader, "multi")) { g_print ("multi on.\n"); clip = ges_multi_clip_from_path (src, layer, start, in, dur, absolute_paths); } else { const char *path; if (absolute_paths == TRUE) { path = src; } else { path = ges_renderer_get_absolute_path (src); } clip = ges_clip_from_path (path, layer, start, in, dur, type); } GESTimeline *tl = ges_layer_get_timeline (layer); GList *tracks = ges_timeline_get_tracks (tl); GESTrack *trackv = g_list_first (tracks)->data; GESTrack *tracka = g_list_last (tracks)->data; if (is_in_members (reader, "volume")) { double volume = getDouble (reader, "volume"); GESTrackElement *audioElement = ges_clip_find_track_element (clip, tracka, G_TYPE_NONE); if (audioElement != NULL) { ges_track_element_set_child_properties (audioElement, "volume", volume, NULL); } } GESTrackElement *videoElement = ges_clip_find_track_element (clip, trackv, G_TYPE_NONE); if (videoElement != NULL) { if (is_in_members (reader, "x")) { int x = getInt (reader, "x"); ges_track_element_set_child_properties (videoElement, "posx", x, NULL); } if (is_in_members (reader, "y")) { int y = getInt (reader, "y"); ges_track_element_set_child_properties (videoElement, "posy", y, NULL); } if (is_in_members (reader, "alpha")) { gdouble alpha = getDouble (reader, "alpha"); ges_track_element_set_child_properties (videoElement, "alpha", alpha, NULL); } if (is_in_members (reader, "size")) { gdouble size = getDouble (reader, "size"); GESUriClipAsset *asset = GES_URI_CLIP_ASSET (ges_extractable_get_asset (GES_EXTRACTABLE (clip))); guint width = ges_asset_get_width (asset); guint height = ges_asset_get_height (asset); if (width != 0 && height != 0) { double dw = width * size; double dh = height * size; g_print ("%dx%d => * %f => %dx%d\n", width, height, size, (int) dw, (int) dh); ges_track_element_set_child_properties (videoElement, "width", (int) dw, "height", (int) dh, NULL); } } if (is_in_members (reader, "effect")) { const char *effect_str = getString (reader, "effect"); if (strcmp (effect_str, "") != 0) { g_print ("Using effect %s", effect_str); GESEffect *effect = ges_effect_new (effect_str); ges_container_add (GES_CONTAINER (clip), GES_TIMELINE_ELEMENT (effect)); } } } json_reader_end_element (reader); } json_reader_end_member (reader); }
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); }