summaryrefslogtreecommitdiffstats
path: root/non-qt-api/glib-example/jsonclient.cpp
blob: b3a87d787e9df7ef0be09ae7d19919ae2c9b5ebf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtAddOn.JsonStream module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "jsonclient.h"

#include <network.h>
#include <stdio.h>
#include <json-glib/json-glib.h>

#ifndef G_VALUE_INIT
#define G_VALUE_INIT  { 0, { { 0 } } }
#endif

static std::string toJson(GHashTable *dict);
static GHashTable* toHashTable(std::string);
static GValue *getValue(JsonNode *node);

inline bool isSignalConnected(const sigc::signal_base & sig)
{
    return sig.size() > 0;
}

/*!
    \class JsonClient
    \brief The JsonClient class is used to send jsons to the JsonServer.

    Note: The JsonClient is not thread safe.
*/

/*!
  Construct a new JsonClient instance with \a registration token.
  The token will be passed in \c{{"token": registration}}.  This constructor
  is designed to work with JsonTokenAuthority.
 */
JsonClient::JsonClient(const std::string& registration)
    : mSocket(0)
{
    mRegistrationMessage = "{\"token\": \"" + registration + "\" }";
}

/*!
  Construct a new JsonClient instance.
 */
JsonClient::JsonClient()
    : mSocket(0)
{
}

/*!
  Destroy the JsonClient and shut down any active stream.
 */
JsonClient::~JsonClient()
{
    setDevice(0);
    if (mSocket)
        delete mSocket;
}

/*!
  Connect to the JsonServer over a TCP socket at \a hostname and \a port. Send the initial registration message.
  Return true if the connection is successful.
*/

bool JsonClient::connectTCP(const std::string & hostname, int port)
{
    TcpSocket *socket = new TcpSocket();
    if (socket->connectToHost(hostname, port))
    {
        if (socket->waitForConnected())
        {
            setDevice(socket);
            g_print("Sending local socket registration message %s\n", mRegistrationMessage.c_str());
            send(!mRegistrationMessage.empty() ? mRegistrationMessage : "{ }");
            return true;
        }
    }
    delete socket;
    return false;
}

/*!
  Connect to the JsonServer over a Unix local socket to \a socketname and send the initial registration message.
  Return true if the connection is successful.
 */
bool JsonClient::connectLocal(const std::string & socketname)
{
    LocalSocket *socket = new LocalSocket();
    if (socket->connectToServer(socketname))
    {
        if (socket->waitForConnected())
        {
            setDevice(socket);
            g_print("Sending local socket registration message %s\n", mRegistrationMessage.c_str());
            send(!mRegistrationMessage.empty() ? mRegistrationMessage : "{ }");
            return true;
        }
    }
    delete socket;
    return false;
}

/*!
  Send a \a message over the socket.
*/
void JsonClient::send(const std::string & _message)
{
    if (mSocket->isOpen())
    {
        std::string message(_message + "\n");
        int nBytes = mSocket->write( message.c_str(), message.size() );
        g_print("wrote %d bytes into socket\n", nBytes);
    } else {
        g_print("stream socket is not available\n");
    }
}

/*!
  Send a \a message over the socket.
*/
void JsonClient::send(GHashTable *map)
{
    send(toJson(map));
}

/*!
  \internal
*/

/*!
    Set the \a device used by the JsonStream.
    Setting the device to 0 disconnects the stream but does not close
    the device nor flush it.

    The stream does not take ownership of the device.
*/
void JsonClient::setDevice( AbstractSocket *device )
{
    if (mSocket)
    {
        if (isSignalConnected(device->readyRead))
            mSocket->readyRead.slots().begin()->disconnect();
        if (isSignalConnected(device->aboutToClose))
            mSocket->aboutToClose.slots().begin()->disconnect();
        delete mSocket;
    }

    mSocket = device;
    if (device) {
        device->readyRead.connect( sigc::mem_fun(this, &JsonClient::dataReadyOnSocket) );
        device->aboutToClose.connect( sigc::mem_fun(this, &JsonClient::socketAboutToClose) );
    }
}

void JsonClient::dataReadyOnSocket()
{
    std::string str(mSocket->readAll());
    if (isSignalConnected(messageReceived))
        messageReceived.emit(str);
    if (isSignalConnected(messageReceivedMap))
        messageReceivedMap.emit(toHashTable(str));
}

void JsonClient::socketAboutToClose()
{
    aboutToClose.emit();
}

/*!
    \fn void JsonClient::aboutToClose()
    This signal is emitted when server closes a connection.
*/

/*!
    \fn void JsonClient::messageReceived(const std::string &message)
    This signal is emitted when a \a message is received from the server.
*/

/*!
    \fn void JsonClient::messageReceivedMap(GHashTable *message)
    This signal is emitted when a \a message is received from the server.
*/

static void insertToJson(gpointer name, gpointer v, gpointer user_data)
{
    JsonBuilder *builder = (JsonBuilder *)user_data;

    if (name != NULL)
        json_builder_set_member_name (builder, (const char *)name);

    switch (G_VALUE_TYPE(v)) {
    case G_TYPE_BOOLEAN:
        json_builder_add_boolean_value (builder, g_value_get_boolean((GValue *)v));
        break;
    case G_TYPE_STRING:
        json_builder_add_string_value (builder, g_value_get_string((GValue *)v));
        break;
    case G_TYPE_INT:
        json_builder_add_int_value (builder, g_value_get_int((GValue *)v));
        break;
    case G_TYPE_INT64:
        json_builder_add_int_value (builder, g_value_get_int64((GValue *)v));
        break;
    case G_TYPE_DOUBLE:
        json_builder_add_double_value (builder, g_value_get_double((GValue *)v));
        break;
    default:
        if (G_VALUE_TYPE(v) == G_TYPE_HASH_TABLE)
        {
            json_builder_begin_object (builder);
            GHashTable *map = (GHashTable *) g_value_get_boxed((GValue *)v);
            g_hash_table_foreach (map, insertToJson, builder);
            json_builder_end_object (builder);
        }
        else if (G_VALUE_TYPE(v) == G_TYPE_VALUE_ARRAY)
        {
            json_builder_begin_array (builder);
            GValueArray *array = (GValueArray *) g_value_get_boxed((GValue *)v);
            for (guint i = 0; i < array->n_values; i++)
            {
               GValue *value = g_value_array_get_nth(array, i);
               insertToJson(0, value, builder);
            }
            json_builder_end_array (builder);
        }
        else
        {
            g_print("unhandled type %s\n", G_VALUE_TYPE_NAME(v));
            json_builder_add_null_value (builder);
        }
        break;
    }
}

static std::string toJson(GHashTable *dict)
{
    fprintf(stderr, "JSONDocument::toJson\n");
    JsonBuilder *builder = json_builder_new ();

    json_builder_begin_object (builder);

    if (dict != NULL)
    {
        g_hash_table_foreach (dict, insertToJson, builder);
    }

    json_builder_end_object (builder);

    JsonGenerator *generator = json_generator_new ();
    json_generator_set_root (generator, json_builder_get_root (builder));
    gchar *str = json_generator_to_data (generator, 0);

    std::string msg(str);

    g_object_unref (generator);
    g_object_unref (builder);

    //g_print("[%s]\n", msg.c_str());

    return msg + "\n";
}

static void parseMembers(JsonObject *,
                         const gchar *member_name,
                         JsonNode    *member_node,
                         gpointer     user_data)
{
    GHashTable *map = static_cast<GHashTable *>(user_data);
    g_hash_table_insert(map, g_strdup(member_name), getValue(member_node));
}

static void parseElements(JsonArray *, guint, JsonNode *element_node, gpointer user_data)
{
    GValueArray *array = static_cast<GValueArray *>(user_data);
    g_value_array_append(array, getValue(element_node));
}

static GValue *getValue(JsonNode *node)
{
    GValue *p = new GValue;
    GValue &ret = *p;

    switch (JSON_NODE_TYPE(node))
    {
    case JSON_NODE_OBJECT:
        {
            JsonObject *node_object;
            node_object = json_node_get_object (node);
            g_assert (node_object != NULL);

            GHashTable *object = g_hash_table_new(g_str_hash, g_str_equal);
            json_object_foreach_member(node_object, parseMembers, object);

            g_value_init(&ret, G_TYPE_HASH_TABLE);
            g_value_set_boxed(&ret, object);
        }
        break;
    case JSON_NODE_ARRAY:
        {
            JsonArray *node_array;
            node_array = json_node_get_array (node);
            g_assert (node_array != NULL);

            GValueArray *array = g_value_array_new(0);
            json_array_foreach_element(node_array, parseElements, array);

            g_value_init(&ret, G_TYPE_VALUE_ARRAY);
            g_value_set_boxed(&ret, array);
        }
        break;
    case JSON_NODE_VALUE:
        {
            switch (json_node_get_value_type(node))
            {
            case G_TYPE_INT64:
                {
                    gint64 val = json_node_get_int(node);
                    g_value_init (&ret, G_TYPE_INT64);
                    g_value_set_int64(&ret, val);
                }
                break;

            case G_TYPE_DOUBLE:
                {
                    double val = json_node_get_double(node);
                    g_value_init (&ret, G_TYPE_INT64);
                    g_value_set_double(&ret, val);
                }
                break;

            case G_TYPE_BOOLEAN:
                {
                    bool val = json_node_get_boolean(node);
                    g_value_init (&ret, G_TYPE_INT64);
                    g_value_set_boolean(&ret, val);
                }
                break;

            case G_TYPE_STRING:
                {
                    const gchar * str = json_node_get_string(node);
                    g_value_init (&ret, G_TYPE_STRING);
                    g_value_set_string(&ret, str);
                }
                break;
            default:
                break;
            }
        }
        break;
    case JSON_NODE_NULL:
        break;
    }
    return &ret;
}

static GHashTable* toHashTable(std::string msg)
{
    g_print("toHashTable\n");
    JsonParser *parser;
    GError *error = NULL;

    parser = json_parser_new ();

    GHashTable *map = g_hash_table_new(g_str_hash, g_str_equal);

    if (json_parser_load_from_data (parser, msg.c_str(), -1, &error))
    {
        JsonNode *root;
        JsonObject *object;

        g_assert (NULL != json_parser_get_root (parser));

        root = json_parser_get_root (parser);
        if (JSON_NODE_TYPE (root) == JSON_NODE_OBJECT)
        {
            object = json_node_get_object (root);
            g_assert (object != NULL);

            json_object_foreach_member(object, parseMembers, map);
        }
    }
    else
    {
        g_error_free (error);
    }
    g_object_unref (parser);

    return map;
}