Exemplo n.º 1
1
// Parse a json object, a json object stripped of {} or an json array
// stripped of [] into a JsonNode.
JsonNode *glib_jsonrpc_json_string_to_json_node(const gchar *str)
{
  JsonParser *parser = json_parser_new();
  GError *error;

  // First try to parse the string
  if (!json_parser_load_from_data(parser, str, -1, &error))
    {
      // Wrap it in a { } pair and try again.
      g_error_free(error); error = NULL;
      GString *j_str = g_string_new("");
      g_string_append_printf(j_str, "{%s}", str);

      // Try parsing it as an object
      if (!json_parser_load_from_data(parser, j_str->str, -1, &error))
        {
          // Still fail, try to parse it as an array
          g_string_free(j_str, TRUE);
          g_string_append_printf(j_str, "[%s]", str);
          if (!json_parser_load_from_data(parser, j_str->str, -1, &error))
            {
              // That's it, we give up.
              g_object_unref(parser);
              return NULL;
            }
        }
    }

  JsonNode *node = json_node_copy(json_parser_get_root(parser));
  g_object_unref(parser);
  return node;
}
Exemplo n.º 2
0
// Creates a response. Transfers ownership of reply.
static JsonNode* create_response(JsonNode *reply, int id)
{
  JsonBuilder *builder = json_builder_new ();

  // {"jsonrpc": "2.0", "result": 19, "id": 1}
  json_builder_begin_object (builder);
  json_builder_set_member_name (builder, "jsonrpc");
  json_builder_add_string_value (builder, "2.0");
  
  json_builder_set_member_name (builder, "id");
  json_builder_add_int_value (builder, id);

  json_builder_set_member_name (builder, "result");

  if (reply)
    json_builder_add_value (builder, json_node_copy(reply));
  else
    // default "ok" message
    json_builder_add_string_value (builder, "ok");

  json_builder_end_object (builder);
  
  JsonNode *node = json_node_copy(json_builder_get_root (builder));

  g_object_unref(builder);
  return node;
}
Exemplo n.º 3
0
static JsonNode* create_fault_value_response(int error_num, JsonNode *msg_node, int id)
{
  JsonBuilder *builder = json_builder_new ();

  json_builder_begin_object (builder);
  json_builder_set_member_name (builder, "jsonrpc");
  json_builder_add_string_value (builder, "2.0");
  json_builder_set_member_name (builder, "error");
  json_builder_begin_object(builder);
  json_builder_set_member_name (builder, "code");
  json_builder_add_int_value(builder, error_num);
  json_builder_set_member_name (builder, "message");
  json_builder_add_value (builder, json_node_copy(msg_node));
  json_builder_end_object (builder);
  json_builder_set_member_name(builder, "id");
  if (id < 0)
    json_builder_add_null_value(builder);
  else
    json_builder_add_int_value(builder, id);
  json_builder_end_object (builder);
  JsonNode *node = json_node_copy(json_builder_get_root (builder));
  
  g_object_unref(builder);
  return node;
}
Exemplo n.º 4
0
/**
 * json_reader_set_root:
 * @reader: a #JsonReader
 * @root: (allow-none): a #JsonNode
 *
 * Sets the root #JsonNode to be read by @reader. The @reader will take
 * a copy of @root
 *
 * If another #JsonNode is currently set as root, it will be replaced.
 *
 * Since: 0.12
 */
void
json_reader_set_root (JsonReader *reader,
                      JsonNode   *root)
{
  JsonReaderPrivate *priv;

  g_return_if_fail (JSON_IS_READER (reader));

  priv = reader->priv;

  if (priv->root == root)
    return;

  if (priv->root != NULL)
    {
      json_node_free (priv->root);
      priv->root = NULL;
      priv->current_node = NULL;
      priv->previous_node = NULL;
    }

  if (root != NULL)
    {
      priv->root = json_node_copy (root);
      priv->current_node = priv->root;
      priv->previous_node = NULL;
    }

  g_object_notify_by_pspec (G_OBJECT (reader), reader_properties[PROP_ROOT]);
}
Exemplo n.º 5
0
JsonNode*
cometd_new_publish_message(const cometd* h,
                           const char* channel,
                           JsonNode* data)
{
  gint64 seed = ++(h->conn->msg_id_seed);

  JsonNode*   root = json_node_new(JSON_NODE_OBJECT);
  JsonObject* obj  = json_object_new();

  json_object_set_int_member(obj, COMETD_MSG_ID_FIELD, seed);

  json_object_set_string_member(obj,
                                COMETD_MSG_CHANNEL_FIELD,
                                channel);

  json_object_set_string_member(obj,
                                COMETD_MSG_CLIENT_ID_FIELD,
                                cometd_conn_client_id(h->conn));

  json_object_set_member(obj,
                         COMETD_MSG_DATA_FIELD,
                         json_node_copy(data));

  json_node_take_object(root, obj);

  return root;
}
Exemplo n.º 6
0
Arquivo: json.c Projeto: GNOME/gegl
static GType
json_op_register_type_for_file (GTypeModule *type_module, const gchar *filepath)
{
    GType ret = 0;
    GError *error = NULL;
    JsonParser *parser = json_parser_new();
    const gboolean success = json_parser_load_from_file(parser, filepath, &error);

    if (success) {
        JsonNode *root_node = json_node_copy (json_parser_get_root (parser));
        JsonObject *root = json_node_get_object (root_node);
        const gchar *name;
        gchar *type_name;

        g_assert(root_node);

        name = metadata_get_property(root, "name");
        type_name = (name) ? component2gtypename(name) : component2gtypename(filepath);
        ret = json_op_register_type(type_module, type_name, root);
        g_free(type_name);
    }

//    g_object_unref(parser);
    return ret;
}
Exemplo n.º 7
0
static JsonNode *
postal_http_parse_body (SoupMessage  *message,
                        GError      **error)
{
   JsonParser *p;
   JsonNode *ret;

   g_assert(SOUP_IS_MESSAGE(message));

   p = json_parser_new();

   if (!json_parser_load_from_data(p,
                                   message->request_body->data,
                                   message->request_body->length,
                                   error)) {
      g_object_unref(p);
      return NULL;
   }

   if ((ret = json_parser_get_root(p))) {
      ret = json_node_copy(ret);
   }

   g_object_unref(p);

   if (!ret) {
      g_set_error(error,
                  postal_json_error_quark(),
                  0,
                  "Missing JSON payload.");
   }

   return ret;
}
Exemplo n.º 8
0
static void
router_rule_compile (RouterRule *rule,
                     JsonObject *object)
{
  RouterMatch *match;
  GList *names, *l;
  JsonNode *node;
  gint i;

  g_assert (rule->matches == NULL);

  names = json_object_get_members (object);
  rule->matches = g_new0 (RouterMatch, g_list_length (names) + 1);
  for (l = names, i = 0; l != NULL; l = g_list_next (l), i++)
    {
      match = &rule->matches[i];
      match->name = g_strdup (l->data);
      node = json_object_get_member (object, l->data);

      /* A glob style string pattern */
      if (JSON_NODE_HOLDS_VALUE (node) && json_node_get_value_type (node) == G_TYPE_STRING)
        match->glob = g_pattern_spec_new (json_node_get_string (node));

      /* A null matches anything */
      if (!JSON_NODE_HOLDS_NULL (node))
        match->node = json_node_copy (node);
    }

  /* The last match has a null name */
  g_list_free (names);
}
Exemplo n.º 9
0
void
JSONBuilder::add_JsonNode_member(const gchar *member_name,
                                 Node JsonNode_value) {
  std::unique_lock<std::mutex> lock(thread_safe_);
  json_builder_set_member_name(builder_, member_name);
  JsonNode *copy = json_node_copy(JsonNode_value->get());
  json_builder_add_value(builder_, copy);
}
Exemplo n.º 10
0
void
cometd_inbox_push_msg(cometd_inbox* inbox, JsonNode* node)
{
  g_mutex_lock(inbox->m);
  g_queue_push_tail(inbox->queue, json_node_copy(node));
  g_cond_signal(inbox->c);
  g_mutex_unlock(inbox->m);
}
Exemplo n.º 11
0
void trg_prefs_load(TrgPrefs * p)
{
    TrgPrefsPrivate *priv = p->priv;
    JsonParser *parser = json_parser_new();
    JsonNode *root;
    guint n_profiles;
    JsonArray *profiles;

    gboolean parsed = json_parser_load_from_file(parser, priv->file, NULL);

    if (!parsed) {
        trg_prefs_empty_init(p);
        g_object_unref(parser);
        return;
    }

    root = json_parser_get_root(parser);
    if (root) {
        priv->user = json_node_copy(root);
        priv->userObj = json_node_get_object(priv->user);
    }

    g_object_unref(parser);

    if (!root) {
        trg_prefs_empty_init(p);
        return;
    }

    if (!json_object_has_member(priv->userObj, TRG_PREFS_KEY_PROFILES)) {
        profiles = json_array_new();
        json_object_set_array_member(priv->userObj, TRG_PREFS_KEY_PROFILES,
                                     profiles);
    } else {
        profiles = json_object_get_array_member(priv->userObj,
                                                TRG_PREFS_KEY_PROFILES);
    }

    n_profiles = json_array_get_length(profiles);

    if (n_profiles < 1) {
        priv->profile = trg_prefs_new_profile_object();
        json_array_add_object_element(profiles, priv->profile);
        trg_prefs_set_int(p, TRG_PREFS_KEY_PROFILE_ID, 0,
                          TRG_PREFS_GLOBAL);
    } else {
        gint profile_id = trg_prefs_get_int(p, TRG_PREFS_KEY_PROFILE_ID,
                                            TRG_PREFS_GLOBAL);
        if (profile_id >= n_profiles)
            trg_prefs_set_int(p, TRG_PREFS_KEY_PROFILE_ID, profile_id = 0,
                              TRG_PREFS_GLOBAL);

        priv->profile =
            json_array_get_object_element(profiles, profile_id);
    }
}
Exemplo n.º 12
0
/**
 * json_builder_get_root:
 * @builder: a #JsonBuilder
 *
 * Returns the root of the current constructed tree, if the build is complete
 * (ie: all opened objects, object members and arrays are being closed).
 *
 * Return value: (transfer full): the #JsonNode, or %NULL if the build is not complete.
 *   Free the returned value with json_node_free().
 */
JsonNode *
json_builder_get_root (JsonBuilder *builder)
{
  JsonNode *root = NULL;

  g_return_val_if_fail (JSON_IS_BUILDER (builder), NULL);

  if (builder->priv->root)
    root = json_node_copy (builder->priv->root);

  return root;
}
Exemplo n.º 13
0
JsonNode *
json_node_from_call (RestProxyCall *call)
{
	JsonParser *parser;
	JsonNode *root = NULL;
	JsonObject *obj = NULL;
	GError *error;
	gboolean ret = FALSE;
	const char *status;

	parser = json_parser_new ();

	if (call == NULL)
		goto out;

	if (!SOUP_STATUS_IS_SUCCESSFUL (rest_proxy_call_get_status_code (call))) {
		g_message ("Error from Google Map: %s (%d)",
			   rest_proxy_call_get_status_message (call),
			   rest_proxy_call_get_status_code (call));
		goto out;
	}

	ret = json_parser_load_from_data (parser,
					  rest_proxy_call_get_payload (call),
					  rest_proxy_call_get_payload_length (call),
					  &error);
	if (!ret)
		goto out;
	root = json_parser_get_root (parser);

	if (root == NULL) {
		g_message ("Error from Google Map: %s",
		rest_proxy_call_get_payload (call));
		goto out;
	}

	/* check status */
	obj = json_node_get_object (root);
	status = json_object_get_string_member (obj, "status");
	if (g_strcmp0 (status, "OK") != 0) {
		g_message ("Error from Google Map: %s", status);
		root = NULL;
		goto out;
	}

	root = json_node_copy (root);
out:
	g_object_unref (parser);

	return root;
}
Exemplo n.º 14
0
/**
 * json_array_dup_element:
 * @array: a #JsonArray
 * @index_: the index of the element to retrieve
 *
 * Retrieves a copy of the #JsonNode containing the value of the
 * element at @index_ inside a #JsonArray
 *
 * Return value: (transfer full): a copy of the #JsonNode at the requested
 *   index. Use json_node_free() when done.
 *
 * Since: 0.6
 */
JsonNode *
json_array_dup_element (JsonArray *array,
                        guint      index_)
{
  JsonNode *retval;

  g_return_val_if_fail (array != NULL, NULL);
  g_return_val_if_fail (index_ < array->elements->len, NULL);

  retval = json_array_get_element (array, index_);
  if (!retval)
    return NULL;

  return json_node_copy (retval);
}
Exemplo n.º 15
0
/**
 * json_object_dup_member:
 * @object: a #JsonObject
 * @member_name: the name of the JSON object member to access
 *
 * Retrieves a copy of the #JsonNode containing the value of @member_name
 * inside a #JsonObject
 *
 * Return value: a copy of the node for the requested object member
 *   or %NULL. Use json_node_free() when done.
 *
 * Since: 0.6
 */
JsonNode *
json_object_dup_member (JsonObject  *object,
                        const gchar *member_name)
{
  JsonNode *retval;

  g_return_val_if_fail (object != NULL, NULL);
  g_return_val_if_fail (member_name != NULL, NULL);

  retval = json_object_get_member (object, member_name);
  if (!retval)
    return NULL;

  return json_node_copy (retval);
}
Exemplo n.º 16
0
static gboolean
picasa_web_utils_parse_json_response (SoupMessage  *msg,
				      JsonNode    **node,
				      GError      **error)
{
	JsonParser *parser;
	SoupBuffer *body;

	g_return_val_if_fail (msg != NULL, FALSE);
	g_return_val_if_fail (node != NULL, FALSE);

	*node = NULL;

	if ((msg->status_code != 200) && (msg->status_code != 400)) {
		*error = g_error_new (SOUP_HTTP_ERROR,
				      msg->status_code,
				      "%s",
				      soup_status_get_phrase (msg->status_code));
		return FALSE;
	}

	body = soup_message_body_flatten (msg->response_body);
	parser = json_parser_new ();
	if (json_parser_load_from_data (parser, body->data, body->length, error)) {
		JsonObject *obj;

		*node = json_node_copy (json_parser_get_root (parser));

		obj = json_node_get_object (*node);
		if (json_object_has_member (obj, "error")) {
			JsonObject *error_obj;

			error_obj = json_object_get_object_member (obj, "error");
			*error = g_error_new (WEB_SERVICE_ERROR,
					      json_object_get_int_member (error_obj, "code"),
					      "%s",
					      json_object_get_string_member (error_obj, "message"));

			json_node_free (*node);
			*node = NULL;
		}
	}

	g_object_unref (parser);
	soup_buffer_free (body);

	return *node != NULL;
}
Exemplo n.º 17
0
static JsonNode *query_network_address(IpcamIAjax *iajax)
{
	const gchar *token = ipcam_base_app_get_config(IPCAM_BASE_APP(iajax), "token");
	IpcamRequestMessage *req_msg;
	IpcamMessage *resp_msg;
    JsonBuilder *builder;
	JsonNode *addr_node = NULL;
	gboolean ret;

	builder = json_builder_new();
	json_builder_begin_object(builder);
	json_builder_set_member_name(builder, "items");
	json_builder_begin_array(builder);
	json_builder_add_string_value(builder, "address");
	json_builder_end_array(builder);
	json_builder_end_object(builder);

	req_msg = g_object_new(IPCAM_REQUEST_MESSAGE_TYPE,
	                       "action", "get_network",
	                       "body", json_builder_get_root(builder),
	                       NULL);
	ipcam_base_app_send_message(IPCAM_BASE_APP(iajax), IPCAM_MESSAGE(req_msg),
	                            "iconfig", token, NULL, 5);
	ret = ipcam_base_app_wait_response(IPCAM_BASE_APP(iajax),
	                                   ipcam_request_message_get_id(req_msg),
	                                   5000, &resp_msg);
	if (ret)
	{
		JsonNode *resp_body;
		JsonObject *items_obj;

		g_object_get(G_OBJECT(resp_msg), "body", &resp_body, NULL);

		items_obj = json_object_get_object_member(json_node_get_object(resp_body), "items");
		addr_node = json_node_copy(json_object_get_member(items_obj, "address"));

		g_object_unref(resp_msg);
	}

	g_object_unref(req_msg);
	g_object_unref(builder);

	return addr_node;
}
Exemplo n.º 18
0
static gboolean
onvif_invocate_action(IpcamIOnvifDiscovery *ionvif_discovery, const char *action,
                               JsonNode *request, JsonNode **response)
{
	const gchar *token;
	IpcamRequestMessage *req_msg;
	IpcamMessage *resp_msg;
	gboolean ret = FALSE;

	token = ipcam_base_app_get_config(IPCAM_BASE_APP(ionvif_discovery), "token");

	req_msg = g_object_new(IPCAM_REQUEST_MESSAGE_TYPE,
	                       "action", action,
	                       "body", request,
	                       NULL);

	ipcam_base_app_send_message(IPCAM_BASE_APP(ionvif_discovery),
	                            IPCAM_MESSAGE(req_msg),
	                            "iconfig", token, NULL, 10);

	ret = ipcam_base_app_wait_response(IPCAM_BASE_APP(ionvif_discovery),
	                                   ipcam_request_message_get_id(req_msg),
	                                   5000, &resp_msg);
	if (ret)
	{
		JsonNode *resp_body;

        if (response) {
            g_object_get(G_OBJECT(resp_msg), "body", &resp_body, NULL);
            *response = json_node_copy(resp_body);
        }

		g_object_unref(resp_msg);
	}

	g_object_unref(req_msg);

	return ret;
}
Exemplo n.º 19
0
// FIXME: check for memory leaks
JSONcontext* Network::readJSON(const char* file){
   JsonParser *parser;
   JsonObject *obj;
   JsonArray *jnodes;
   JsonArray *jedges;
   int i,k;
   JSONcontext* ctx=new JSONcontext();
   GError *error;
   g_type_init ();
   parser = json_parser_new ();
   
   error = NULL;
   json_parser_load_from_file (parser, file, &error);
   if (error)
   {
      g_print ("Unable to parse `%s': %s\n", file, error->message);
      g_error_free (error);
      g_object_unref (parser);
      abort();
   }
   addCompartment(0,"unknown"); // add dummy compartment, may be overwritten by compartment from json
   ctx->root = json_node_copy(json_parser_get_root(parser)); // needs to be copied ??
   obj=json_node_get_object (ctx->root);
   jnodes=json_object_get_array_member(obj,"nodes");
   jedges=json_object_get_array_member(obj,"edges");
   g_print ("%i nodes\n",json_array_get_length(jnodes));
   for (i=0;i<json_array_get_length(jnodes);i++){
      JsonObject *n=json_array_get_object_element(jnodes,i);
      JsonObject *data=json_object_get_object_member(n,"data");
      const char* type=json_object_get_string_member(n,"type");
      const char* id=json_object_get_string_member(n,"id");
      if (json_object_has_member(n,"is_abstract") && (json_object_get_boolean_member(n,"is_abstract") || json_object_get_int_member(n,"is_abstract"))){
         continue;
      }
      if (!json_object_has_member(n,"index")){
         g_print ("no index defined for %s %s\n",type,id);
         abort();
      }
      int idx=json_object_get_int_member(n,"index");
      g_print ("node %d %s id %s\n",idx,type,id);
      if(strcmp(type,"Compartment")==0){
         addCompartment(idx,id);
      } else {
         double x=json_object_get_double_member(data,"x");
         double y=json_object_get_double_member(data,"y");
         double w=json_object_get_double_member(data,"width");
         double h=json_object_get_double_member(data,"height");
         double d=json_object_get_double_member(data,"dir");
         int c=json_object_get_int_member(data,"compartmentidx");
         for(k=0;k<7;k++){
            if(strcmp(jnodetypes[k],type)==0)break;
         }
         if (k==7){
            g_print ("unknown node type %s\n",type);
            abort();
         }
         addNode(idx,inodetypes[k],id,w,h,x,y,d,c);
         if (idx>=ctx->nodeidx->size()) ctx->nodeidx->resize(idx+1);
         (*(ctx->nodeidx))[idx]=i;
      }
   }
   g_print ("%i edges\n",json_array_get_length(jedges));
   for (i=0;i<json_array_get_length(jedges);i++){
      JsonObject *e=json_array_get_object_element(jedges,i);
      const char* type=json_object_get_string_member(e,"type");
      if ((!json_object_has_member(e,"sourceidx")) || (!json_object_has_member(e,"targetidx"))){
         g_print ("no source/targetindex defined for edge %s %i",type,i);
         abort;
      }
      for(k=0;k<7;k++){
         if(strcmp(edgetypes[k],type)==0)break;
      }
      int from=json_object_get_int_member(e,"sourceidx");
      int to=json_object_get_int_member(e,"targetidx");
      addEdge(from,to,(Edgetype)k);
      g_print ("edge %s %i -> %i\n",edgetypes[k],from,to);
   }
   g_object_unref(parser);
   return ctx;
}
static gboolean
process_includes (RpmOstreeTreeComposeContext  *self,
                  GFile             *treefile_path,
                  guint              depth,
                  JsonObject        *root,
                  GCancellable      *cancellable,
                  GError           **error)
{
  gboolean ret = FALSE;
  const char *include_path;
  const guint maxdepth = 50;

  if (depth > maxdepth)
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                   "Exceeded maximum include depth of %u", maxdepth);
      goto out;
    }

  {
    g_autoptr(GFile) parent = g_file_get_parent (treefile_path);
    gboolean existed = FALSE;
    if (self->treefile_context_dirs->len > 0)
      {
        GFile *prev = self->treefile_context_dirs->pdata[self->treefile_context_dirs->len-1];
        if (g_file_equal (parent, prev))
          existed = TRUE;
      }
    if (!existed)
      {
        g_ptr_array_add (self->treefile_context_dirs, parent);
        parent = NULL; /* Transfer ownership */
      }
  }

  if (!_rpmostree_jsonutil_object_get_optional_string_member (root, "include", &include_path, error))
    goto out;
                                          
  if (include_path)
    {
      g_autoptr(GFile) treefile_dirpath = g_file_get_parent (treefile_path);
      g_autoptr(GFile) parent_path = g_file_resolve_relative_path (treefile_dirpath, include_path);
      glnx_unref_object JsonParser *parent_parser = json_parser_new ();
      JsonNode *parent_rootval;
      JsonObject *parent_root;
      GList *members;
      GList *iter;

      if (!json_parser_load_from_file (parent_parser,
                                       gs_file_get_path_cached (parent_path),
                                       error))
        goto out;

      parent_rootval = json_parser_get_root (parent_parser);
      if (!JSON_NODE_HOLDS_OBJECT (parent_rootval))
        {
          g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                       "Treefile root is not an object");
          goto out;
        }
      parent_root = json_node_get_object (parent_rootval);
      
      if (!process_includes (self, parent_path, depth + 1, parent_root,
                             cancellable, error))
        goto out;
                             
      members = json_object_get_members (parent_root);
      for (iter = members; iter; iter = iter->next)
        {
          const char *name = iter->data;
          JsonNode *parent_val = json_object_get_member (parent_root, name);
          JsonNode *val = json_object_get_member (root, name);

          g_assert (parent_val);

          if (!val)
            json_object_set_member (root, name, json_node_copy (parent_val));
          else
            {
              JsonNodeType parent_type =
                json_node_get_node_type (parent_val);
              JsonNodeType child_type =
                json_node_get_node_type (val);
              if (parent_type != child_type)
                {
                  g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                               "Conflicting element type of '%s'",
                               name);
                  goto out;
                }
              if (child_type == JSON_NODE_ARRAY)
                {
                  JsonArray *parent_array = json_node_get_array (parent_val);
                  JsonArray *child_array = json_node_get_array (val);
                  JsonArray *new_child = json_array_new ();
                  guint i, len;

                  len = json_array_get_length (parent_array);
                  for (i = 0; i < len; i++)
                    json_array_add_element (new_child, json_node_copy (json_array_get_element (parent_array, i)));
                  len = json_array_get_length (child_array);
                  for (i = 0; i < len; i++)
                    json_array_add_element (new_child, json_node_copy (json_array_get_element (child_array, i)));
                  
                  json_object_set_array_member (root, name, new_child);
                }
            }
        }

      json_object_remove_member (root, "include");
    }

  ret = TRUE;
 out:
  return ret;
}
Exemplo n.º 21
0
JsonNode *
json_node_from_call (RestProxyCall *call, GError** error)
{
  JsonNode *root;
  JsonObject *object = NULL;
  char *error_message = NULL;
  JsonParser *parser = NULL;

  g_return_val_if_fail (call, NULL);

  if (!SOUP_STATUS_IS_SUCCESSFUL (rest_proxy_call_get_status_code (call))) {
    g_set_error (error, SW_SERVICE_ERROR,
                 SW_SERVICE_ERROR_REMOTE_ERROR,
                 "Error from Facebook: %s (%d)",
                 rest_proxy_call_get_status_message (call),
                 rest_proxy_call_get_status_code (call));
    g_object_unref (parser);
    return NULL;
  }

  parser = json_parser_new ();
  if (!json_parser_load_from_data (parser,
                                   rest_proxy_call_get_payload (call),
                                   rest_proxy_call_get_payload_length (call),
                                   NULL)) {
    g_set_error (error, SW_SERVICE_ERROR,
                 SW_SERVICE_ERROR_REMOTE_ERROR,
                 "Malformed JSON from Facebook: %s",
                 rest_proxy_call_get_payload (call));
    g_object_unref (parser);
    return NULL;
  }

  root = json_parser_get_root (parser);

  if (root)
    root = json_node_copy (root);

  g_object_unref (parser);

  if (root == NULL) {
    g_set_error (error, SW_SERVICE_ERROR,
                 SW_SERVICE_ERROR_REMOTE_ERROR,
                 "Error from Facebook: %s",
                 rest_proxy_call_get_payload (call));
    return NULL;
  }

  /*
   * Is it an error?  If so, it'll be a hash containing
   * the key "error", which maps to a hash containing
   * a key "message".
   */

  if (json_node_get_node_type (root) == JSON_NODE_OBJECT) {
    object = json_node_get_object (root);
  }

  if (object && json_object_has_member (object, "error")) {
    JsonNode *inner = json_object_get_member (object,
                                              "error");
    JsonObject *inner_object = NULL;

    if (json_node_get_node_type (inner) == JSON_NODE_OBJECT)
      inner_object = json_node_get_object (inner);

    if (inner_object && json_object_has_member (inner_object, "message"))
      error_message = get_child_node_value (inner, "message");
  }

  if (error_message) {
    g_set_error (error, SW_SERVICE_ERROR,
                 SW_SERVICE_ERROR_REMOTE_ERROR,
                 "Error response from Facebook: %s", error_message);
    g_free (error_message);
    json_node_free (root);
    return NULL;
  } else {
    return root;
  }
}
Exemplo n.º 22
0
GHashTable *
cockpit_package_listing (JsonArray **json)
{
  JsonArray *root = NULL;
  GHashTable *listing;
  CockpitPackage *package;
  GHashTable *ids;
  JsonObject *object;
  JsonArray *id;
  GList *names, *l;
  GList *packages;
  const gchar *name;
  JsonNode *node;
  JsonArray *array;
  guint i, length;

  listing = g_hash_table_new_full (g_str_hash, g_str_equal,
                                   NULL, cockpit_package_unref);

  build_package_listing (listing);

  /* Add aliases to the listing */
  packages = g_hash_table_get_values (listing);
  packages = g_list_sort (packages, compar_packages);
  g_list_foreach (packages, (GFunc)cockpit_package_ref, NULL);
  for (l = packages; l != NULL; l = g_list_next (l))
    {
      package = l->data;

      node = json_object_get_member (package->manifest, "alias");
      if (node)
        {
          /*
           * Process and remove "alias" from the manifest, as it results in
           * confusing and duplicated information for the front end.
           */
          package->alias = node = json_node_copy (node);
          json_object_remove_member (package->manifest, "alias");

          if (JSON_NODE_HOLDS_ARRAY (node))
            {
              array = json_node_get_array (node);
              length = json_array_get_length (array);
              for (i = 0; i < length; i++)
                add_alias_to_listing (listing, package, json_array_get_element (array, i));
            }
          else
            {
              add_alias_to_listing (listing, package, node);
            }
        }
    }
  g_list_free_full (packages, (GDestroyNotify)cockpit_package_unref);

  /* Now wrap up the checksums */
  finish_checksums (listing);

  /* Add checksums to the listing */
  packages = g_hash_table_get_values (listing);
  g_list_foreach (packages, (GFunc)cockpit_package_ref, NULL);
  for (l = packages; l != NULL; l = g_list_next (l))
    {
      package = l->data;
      if (package->checksum && !g_hash_table_contains (listing, package->checksum))
        {
          g_hash_table_replace (listing, package->checksum, cockpit_package_ref (package));
          g_debug ("%s: package has checksum: %s", package->name, package->checksum);
        }
    }
  g_list_free_full (packages, (GDestroyNotify)cockpit_package_unref);

  /* Build JSON packages block */
  if (json)
    {
      *json = root = json_array_new ();
      ids = g_hash_table_new (g_direct_hash, g_direct_equal);
      names = g_hash_table_get_keys (listing);
      names = g_list_sort (names, (GCompareFunc)strcmp);

      for (l = names; l != NULL; l = g_list_next (l))
        {
          name = l->data;
          package = g_hash_table_lookup (listing, name);
          id = g_hash_table_lookup (ids, package);
          if (!id)
            {
              object = json_object_new ();
              id = json_array_new();

              /* The actual package name always comes first */
              json_object_set_array_member (object, "id", id);
              json_array_add_string_element (id, package->name);
              g_hash_table_insert (ids, package, id);

              json_object_set_object_member (object, "manifest", json_object_ref (package->manifest));
              json_array_add_object_element (root, object);
            }

          /* Other ways to refer to the package */
          if (!g_str_equal (name, package->name))
              json_array_add_string_element (id, name);
        }

      g_list_free (names);
      g_hash_table_destroy (ids);
    }

  return listing;
}
Exemplo n.º 23
0
JsonNode*
cometd_msg_wrap_copy(JsonNode* msg)
{
    return cometd_msg_wrap(json_node_copy(msg));
}
Exemplo n.º 24
0
static JsonNode *
catch_resource_group_api_parse_response (CatchResourceGroup   *group,
                                         SoupMessage          *message,
                                         GError              **error)
{
   const gchar *content_type;
   const gchar *error_message = NULL;
   const gchar *status = NULL;
   JsonParser *parser;
   JsonObject *obj = NULL;
   JsonNode *result = NULL;
   JsonNode *root;

   ENTRY;

   g_return_val_if_fail(CATCH_IS_RESOURCE_GROUP(group), NULL);
   g_return_val_if_fail(SOUP_IS_MESSAGE(message), NULL);

   /*
    * If the result isn't application/json, something really wrong happened.
    */
   content_type = soup_message_headers_get_one(message->response_headers,
                                               "Content-Type");
   if (!!g_strcmp0("application/json", content_type)) {
      g_set_error(error, CATCH_API_ERROR, CATCH_API_ERROR_BAD_REQUEST,
                  _("The API request failed for unknown reasons; HTTP %d."),
                  message->status_code);
      RETURN(NULL);
   }

   /*
    * Create a JSON parser to extract the result object from the response. Load
    * the content from the response body.
    */
   parser = json_parser_new();
   if (!json_parser_load_from_data(parser, message->response_body->data,
                                   message->response_body->length, error)) {
      g_object_unref(parser);
      RETURN(NULL);
   }

   /*
    * Check to see if the response is improperly formatted or an error.
    */
   root = json_parser_get_root(parser);
   if (!(root = json_parser_get_root(parser)) ||
       !JSON_NODE_HOLDS_OBJECT(root) ||
       !(obj = json_node_get_object(root)) ||
       !json_object_has_member(obj, "status") ||
       !JSON_NODE_HOLDS_VALUE(json_object_get_member(obj, "status")) ||
       !(status = json_object_get_string_member(obj, "status")) ||
       !!g_strcmp0("ok", status)) {
      if (obj &&
          json_object_has_member(obj, "error") &&
          JSON_NODE_HOLDS_OBJECT(json_object_get_member(obj, "error")) &&
          (obj = json_object_get_object_member(obj, "error")) &&
          json_object_has_member(obj, "message") &&
          JSON_NODE_HOLDS_VALUE(json_object_get_member(obj, "message")) &&
          (error_message = json_object_get_string_member(obj, "message"))) {
         g_set_error(error, CATCH_API_ERROR, CATCH_API_ERROR_BAD_REQUEST,
                     _("%s"), error_message);
      } else {
         g_set_error(error, CATCH_API_ERROR, CATCH_API_ERROR_BAD_REQUEST,
                     _("The API request failed for unknown reasons; HTTP %d."),
                     message->status_code);
      }
      g_object_unref(parser);
      RETURN(NULL);
   }

   /*
    * Try to extract the result node from the response.
    */
   if (obj && json_object_has_member(obj, "result")) {
      if ((result = json_object_get_member(obj, "result"))) {
         result = json_node_copy(result);
      }
   }

   g_object_unref(parser);

   RETURN(result);
}
Exemplo n.º 25
0
void JSONBuilder::add_node_value(JsonNode *node_value) {
  std::unique_lock<std::mutex> lock(thread_safe_);
  JsonNode *copy = json_node_copy(node_value);
  json_builder_add_value(builder_, copy);
}