File: Node.cpp

package info (click to toggle)
dataquay 0.9-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 912 kB
  • ctags: 1,348
  • sloc: cpp: 8,795; sh: 26; ansic: 12; makefile: 9
file content (478 lines) | stat: -rw-r--r-- 14,859 bytes parent folder | download
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*-  vi:set ts=8 sts=4 sw=4: */

/*
    Dataquay

    A C++/Qt library for simple RDF datastore management.
    Copyright 2009-2012 Chris Cannam.
  
    Permission is hereby granted, free of charge, to any person
    obtaining a copy of this software and associated documentation
    files (the "Software"), to deal in the Software without
    restriction, including without limitation the rights to use, copy,
    modify, merge, publish, distribute, sublicense, and/or sell copies
    of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
    ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
    CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
    WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

    Except as contained in this notice, the name of Chris Cannam
    shall not be used in advertising or otherwise to promote the sale,
    use or other dealings in this Software without prior written
    authorization.
*/

#include "Node.h"

#include "Debug.h"

#include <QDataStream>
#include <QTextStream>
#include <QTime>
#include <QByteArray>
#include <QMetaType>
#include <QMutex>
#include <QHash>

namespace Dataquay
{

static const Uri encodedVariantTypeURI
("http://breakfastquay.com/dataquay/datatype/encodedvariant");

static const Uri xsdPrefix
("http://www.w3.org/2001/XMLSchema#");


struct StandardVariantEncoder : public Node::VariantEncoder {
    QString fromVariant(const QVariant &v) {
        return v.toString();
    }
};

struct LongVariantEncoder : public StandardVariantEncoder {
    QVariant toVariant(const QString &s) {
        return QVariant::fromValue<long>(s.toLong());
    }
};

struct ULongVariantEncoder : public StandardVariantEncoder {
    QVariant toVariant(const QString &s) {
        return QVariant::fromValue<unsigned long>(s.toULong());
    }
};

struct DoubleVariantEncoder : public StandardVariantEncoder {
    QVariant toVariant(const QString &s) {
        return QVariant::fromValue<double>(s.toDouble());
    }
};

struct StringVariantEncoder : public StandardVariantEncoder {
    QVariant toVariant(const QString &s) {
        return QVariant::fromValue<QString>(s);
    }
};

struct BoolVariantEncoder : public Node::VariantEncoder {
    QVariant toVariant(const QString &s) {
        return QVariant::fromValue<bool>((s == "true") ||
                                         (s == "1"));
    }
    QString fromVariant(const QVariant &v) {
        return (v.toBool() ? "true" : "false");
    }
};

struct UriVariantEncoder : public Node::VariantEncoder {
    QVariant toVariant(const QString &s) {
        return QVariant::fromValue<Uri>(Uri(s));
    }
    QString fromVariant(const QVariant &v) {
        return v.value<Uri>().toString();
    }
};

struct QUrlVariantEncoder : public Node::VariantEncoder {
    QVariant toVariant(const QString &s) {
        return QVariant::fromValue<QUrl>(QUrl(s));
    }
    QString fromVariant(const QVariant &v) {
        return v.value<QUrl>().toString();
    }
};

// Type maps to be used when converting from Node to Variant and
// Variant to Node, respectively.  These are not symmetrical -- for
// example, we convert xsd:string to QString, but convert QString to
// an untyped literal ("literal" and "literal"^^xsd:string compare
// differently and most people just use "literal", so we're more
// likely to achieve interoperable results if we don't type plain
// strings).  Similarly we convert both double and float to
// xsd:decimal, but always convert xsd:decimal to double.  However, we
// do currently impose symmetry for user-provided types (that is, our
// registerDatatype method adds the datatype to both maps).

class DatatypeMetatypeAssociation
{
public:
    static DatatypeMetatypeAssociation *instance() {
        static DatatypeMetatypeAssociation *inst = 0;
        static QMutex mutex;
        mutex.lock();
        if (inst == 0) inst = new DatatypeMetatypeAssociation();
        mutex.unlock();
        return inst;
    }
    
    int getMetatypeId(Uri dt) {
        DatatypeMetatypeMap::const_iterator i = datatypeMetatypeMap.find(dt);
        if (i != datatypeMetatypeMap.end()) return i->first;
        return 0;
    }

    bool getDatatype(int mt, Uri &dt) {
        MetatypeDatatypeMap::const_iterator i = metatypeDatatypeMap.find(mt);
        if (i != metatypeDatatypeMap.end()) {
            dt = i->first;
            return true;
        }
        return false;
    }

    Node::VariantEncoder *getEncoder(Uri dt) {
        DatatypeMetatypeMap::const_iterator i = datatypeMetatypeMap.find(dt);
        if (i != datatypeMetatypeMap.end()) return i->second;
        return 0;
    }

    Node::VariantEncoder *getEncoder(int id) {
        MetatypeDatatypeMap::const_iterator i = metatypeDatatypeMap.find(id);
        if (i != metatypeDatatypeMap.end()) return i->second;
        return 0;
    }

    void registerDatatype(Uri dt, int id, Node::VariantEncoder *enc) {
        datatypeMetatypeMap[dt] = QPair<int, Node::VariantEncoder *>(id, enc);
    }

    void registerDatatype(int id, Uri dt, Node::VariantEncoder *enc) {
        metatypeDatatypeMap[id] = QPair<Uri, Node::VariantEncoder *>(dt, enc);
    }

    void registerXsd(QString name, int id, Node::VariantEncoder *enc) {
        registerDatatype(Uri(xsdPrefix.toString() + name), id, enc);
    }

    void registerXsd(int id, QString name, Node::VariantEncoder *enc) {
        registerDatatype(id, Uri(xsdPrefix.toString() + name), enc);
    }

private:
    DatatypeMetatypeAssociation() {
        registerXsd("string", QMetaType::QString, new StringVariantEncoder());
        registerXsd("boolean", QMetaType::Bool, new BoolVariantEncoder());
        registerXsd("int", QMetaType::Int, new LongVariantEncoder());
        registerXsd("long", QMetaType::Long, new LongVariantEncoder());
        registerXsd("integer", QMetaType::Long, new LongVariantEncoder());
        registerXsd("unsignedInt", QMetaType::UInt, new ULongVariantEncoder());
        registerXsd("nonNegativeInteger", QMetaType::ULong, new ULongVariantEncoder());
        registerXsd("float", QMetaType::Float, new DoubleVariantEncoder());
        registerXsd("double", QMetaType::Double, new DoubleVariantEncoder());
        registerXsd("decimal", QMetaType::Double, new DoubleVariantEncoder());

        registerXsd(QMetaType::Bool, "boolean", new BoolVariantEncoder());
        registerXsd(QMetaType::Int, "integer", new LongVariantEncoder());
        registerXsd(QMetaType::Long, "integer", new LongVariantEncoder());
        registerXsd(QMetaType::UInt, "integer", new ULongVariantEncoder());
        registerXsd(QMetaType::ULong, "integer", new ULongVariantEncoder());
        registerXsd(QMetaType::Float, "decimal", new DoubleVariantEncoder());
        registerXsd(QMetaType::Double, "decimal", new DoubleVariantEncoder());

        // Not necessary in normal use, because URIs are stored in URI
        // nodes and handled separately rather than being stored in
        // literal nodes... but necessary if an untyped literal is
        // presented for conversion via toVariant(Uri::metaTypeId())
        registerDatatype(Uri::metaTypeId(), Uri(), new UriVariantEncoder());

        // Similarly, although no datatype is associated with QUrl, it
        // could be presented when trying to convert a URI Node using
        // an explicit variant type target (e.g. to assign RDF URIs to
        // QUrl properties rather than Uri ones)
        registerDatatype(QMetaType::QUrl, Uri(), new QUrlVariantEncoder());

        // QString is a known variant type, but has no datatype when
        // writing (we write strings as untyped literals because
        // that's what seems most useful).  We already registered it
        // with xsd:string for reading.
        registerDatatype(QMetaType::QString, Uri(), new StringVariantEncoder());
    }

    typedef QHash<Uri, QPair<int, Node::VariantEncoder *> > DatatypeMetatypeMap;
    DatatypeMetatypeMap datatypeMetatypeMap;

    typedef QHash<int, QPair<Uri, Node::VariantEncoder *> > MetatypeDatatypeMap;
    MetatypeDatatypeMap metatypeDatatypeMap;
};

void
Node::registerDatatype(Uri dt, QString typeName, VariantEncoder *enc)
{
    QByteArray ba = typeName.toLocal8Bit();
    int id = QMetaType::type(ba.data());
    if (id <= 0) {
        std::cerr << "WARNING: Node::registerDatatype: Type name \""
                  << typeName.toStdString() << "\" is unknown to QMetaType, "
                  << "cannot register it here" << std::endl;
        return;
    }
    DatatypeMetatypeAssociation::instance()->registerDatatype(dt, id, enc);
    DatatypeMetatypeAssociation::instance()->registerDatatype(id, dt, enc);
}
    
Uri
Node::getDatatype(QString typeName)
{
    QByteArray ba = typeName.toLocal8Bit();
    int id = QMetaType::type(ba.data());
    if (id <= 0) return Uri();
    Uri dt;
    if (DatatypeMetatypeAssociation::instance()->getDatatype(id, dt)) return dt;
    return Uri();
}

QString
Node::getVariantTypeName(Uri datatype)
{
    int id = DatatypeMetatypeAssociation::instance()->getMetatypeId(datatype);
    if (id > 0) return QMetaType::typeName(id);
    else return QString();
}

Node
Node::fromVariant(const QVariant &v)
{
    DEBUG << "Node::fromVariant: QVariant type is " << v.userType()
          << " (" << int(v.userType()) << "), variant is " << v << endl;

    if (Uri::hasUriType(v)) {
        return Node(v.value<Uri>());
    }
    if (v.type() == QVariant::Url) {
        QString s = v.toUrl().toString();
        if (Uri::isCompleteUri(s)) {
            return Node(Uri(s));
        }
    }

    int id = v.userType();
    
    DatatypeMetatypeAssociation *a = DatatypeMetatypeAssociation::instance();
    Uri datatype;
    if (a->getDatatype(id, datatype)) {
        
        Node n;
        n.type = Literal;
        n.datatype = datatype;

        VariantEncoder *encoder = a->getEncoder(id);

        if (encoder) {
            n.value = encoder->fromVariant(v);
        } else {
            n.value = v.toString();
        }

        return n;

    } else {

        // unknown type: use opaque encoding
        QByteArray b;
        QDataStream ds(&b, QIODevice::WriteOnly);
        ds << v;
        
        Node n;
        n.type = Literal;
        n.datatype = encodedVariantTypeURI;
        n.value = QString::fromLatin1(qCompress(b).toBase64());        
        return n;
    }
}

QVariant
Node::toVariant() const
{
    if (type == URI) {
        return QVariant::fromValue(Uri(value));
    }

    if (type == Nothing || type == Blank) {
        return QVariant();
    }

    if (datatype == Uri()) {
        return QVariant::fromValue<QString>(value);
    }
    
    if (datatype == encodedVariantTypeURI) {
        // Opaque encoding used for "unknown" types.  If this is
        // encoding is in use, we must decode from it even if the type
        // is actually known
        QByteArray benc = value.toLatin1();
        QByteArray b = qUncompress(QByteArray::fromBase64(benc));
        QDataStream ds(&b, QIODevice::ReadOnly);
        QVariant v;
        ds >> v;
        return v;
    }

    DatatypeMetatypeAssociation *a = DatatypeMetatypeAssociation::instance();
    int id = a->getMetatypeId(datatype);
        
    if (id > 0) {
        
        VariantEncoder *encoder = a->getEncoder(datatype);

        if (encoder) {
            return encoder->toVariant(value);
        } else {
            // datatype present, but no encoder: can do nothing
            // interesting with this, convert as string
            return QVariant::fromValue<QString>(value);
        }
        
    } else {
        
        // unknown datatype, but not "unknown type" encoding;
        // convert as a string
        return QVariant::fromValue<QString>(value);
    }
}

QVariant
Node::toVariant(int metatype) const
{
    VariantEncoder *encoder =
        DatatypeMetatypeAssociation::instance()->getEncoder(metatype);

    if (!encoder) {
        std::cerr << "WARNING: Node::toVariant: Unsupported metatype id "
                  << metatype << " (\"" << QMetaType::typeName(metatype)
                  << "\"), register it with registerDatatype please"
                  << std::endl;
        return QVariant();
    }

    return encoder->toVariant(value);
}

bool
operator==(const Node &a, const Node &b)
{
    if (a.type == Node::Nothing &&
        b.type == Node::Nothing) return true;
    if (a.type == b.type &&
        a.value == b.value &&
        a.datatype == b.datatype) return true;
    return false;
}

bool
operator!=(const Node &a, const Node &b)
{
    return !operator==(a, b);
}

QDataStream &
operator<<(QDataStream &out, const Node &n)
{
    return out << (int)n.type << n.value << n.datatype;
}

QDataStream &
operator>>(QDataStream &in, Node &n)
{
    int t;
    in >> t >> n.value >> n.datatype;
    n.type = (Node::Type)t;
    return in;
}

std::ostream &
operator<<(std::ostream &out, const Node &n)
{
    switch (n.type) {
    case Node::Nothing:
        out << "[]";
        break;
    case Node::URI:
        if (n.value == "") {
            out << "[empty-uri]";
        } else {
            out << "<" << n.value.toStdString() << ">";
        }
        break;
    case Node::Literal:
        out << "\"" << n.value.toStdString() << "\"";
        if (n.datatype != Uri()) out << "^^" << n.datatype;
        break;
    case Node::Blank:
        out << "[blank " << n.value.toStdString() << "]";
        break;
    }
    return out;
}

QTextStream &
operator<<(QTextStream &out, const Node &n)
{
    switch (n.type) {
    case Node::Nothing:
        out << "[]";
        break;
    case Node::URI:
        if (n.value == "") {
            out << "[empty-uri]";
        } else {
            out << "<" << n.value << ">";
        }
        break;
    case Node::Literal:
        out << "\"" << n.value << "\"";
        if (n.datatype != Uri()) out << "^^" << n.datatype;
        break;
    case Node::Blank:
        out << "[blank " << n.value << "]";
        break;
    }
    return out;
}

}

unsigned int
qHash(const Dataquay::Node &n)
{
    switch (n.type) {
    case Dataquay::Node::URI:
        return qHash(n.value);
    case Dataquay::Node::Literal:
        return qHash(n.value + n.datatype.toString());
    case Dataquay::Node::Blank:
        return qHash(n.value);
    default:
        return qHash("");
    }
}