File: changelogmerger.cpp

package info (click to toggle)
kde-runtime 4%3A4.8.4-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 24,712 kB
  • sloc: cpp: 130,244; ansic: 2,447; xml: 1,691; perl: 1,570; sh: 504; python: 455; makefile: 13
file content (332 lines) | stat: -rw-r--r-- 10,332 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
/*
   This file is part of the Nepomuk KDE project.
   Copyright (C) 2010  Vishesh Handa <handa.vish@gmail.com>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) version 3, or any
   later version accepted by the membership of KDE e.V. (or its
   successor approved by the membership of KDE e.V.), which shall
   act as a proxy defined in Section 6 of version 3 of the license.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*/



#include "changelogmerger.h"
#include "nrio.h"

#include <algorithm>

#include <QtCore/QMultiHash>
#include <QtCore/QHashIterator>
#include <QtCore/QThread>

#include <Soprano/Vocabulary/NAO>
#include <Soprano/Vocabulary/NRL>
#include <Soprano/Vocabulary/RDF>
#include <Nepomuk/Vocabulary/NIE>
#include <Nepomuk/Vocabulary/NFO>

#include <Soprano/Node>
#include <Soprano/Statement>
#include <Soprano/Model>
#include <Soprano/QueryResultIterator>
#include <Soprano/StatementIterator>
#include <Soprano/NodeIterator>

#include <Nepomuk/Resource>
#include <Nepomuk/Variant>
#include <Nepomuk/Types/Property>
#include <Nepomuk/ResourceManager>

#include <KDebug>

int Nepomuk::ChangeLogMerger::NextId = 0;

Nepomuk::ChangeLogMerger::ChangeLogMerger(Nepomuk::ChangeLog log)
    : ResourceMerger(),
      m_logFile( log )
{
    m_id = NextId++;
}

int Nepomuk::ChangeLogMerger::id()
{
    return m_id;
}

void Nepomuk::ChangeLogMerger::load()
{
    kDebug() << "Loading the ChangeLog..." << m_logFile.size();
    m_hash = ResourceLogMap::fromChangeLog( m_logFile );

    // The records are stored according to dateTime
    Q_ASSERT( m_logFile.toList().isEmpty() == false );
    m_minDateTime = m_logFile.toList().first().dateTime();
}

namespace {

    //
    // Cache the results. This could have very bad consequences if someone updates the ontology
    // when the service is running
    //
    bool isMergeable( const KUrl & prop, Soprano::Model * model ) {
        //
        // trueg: hardcoding the non-mergeable properties here since there are only 2 defined
        //
        return prop != Soprano::Vocabulary::RDF::type() && prop != Nepomuk::Vocabulary::NIE::url();
    }

    QList<Nepomuk::ChangeLogRecord> getRecords( const Nepomuk::ResourceLogMap & hash, const KUrl resUri, const KUrl & propUri ) {

        Nepomuk::ResourceLogMap::const_iterator it = hash.constFind( resUri );
        if( it == hash.constEnd() ) {
            return QList<Nepomuk::ChangeLogRecord>();
        }

        return it->prop.values( propUri );
    }
}

//TODO: Add completed signal
void Nepomuk::ChangeLogMerger::mergeChangeLog()
{
    m_theGraph = createGraph();

    kDebug();

    //
    // Get own changeLog
    //
    kDebug() << "minDateTime : " << m_minDateTime;
    ChangeLog ownLog;// = LogStorage::instance()->getChangeLog( m_minDateTime );
    kDebug() << "own Log : " << ownLog.size();

    // Get our and their hash
    // ownHash = current local hash from system's ChangeLog
    // theirHash = derived from external ChangeLog
    ResourceLogMap ownHash = ResourceLogMap::fromChangeLog( ownLog );
    ResourceLogMap & theirHash = m_hash;

    kDebug() << "own Hash : " << ownHash.size();
    kDebug() << "their hash : " << theirHash.size();

    QHashIterator<KUrl, ResourceLog> it( theirHash );
    while( it.hasNext() ) {
        it.next();

        // Check for resource deletions
        if( handleResourceDeletion( it.key() ) )
            continue;

        const KUrl & resUri = it.key();
        const ResourceLog & resLog = it.value();

        kDebug() << "Resolving " << resUri;

        const QList<KUrl> & properties = resLog.prop.uniqueKeys();
        foreach( const KUrl & propUri, properties ) {
            kDebug() << propUri;

            if( !isMergeable( propUri, model() ) ) {
                kDebug() << propUri << " is non Mergeable - IGNORING";
                continue;
            }

            Nepomuk::Types::Property prop( propUri );
            int cardinality = prop.maxCardinality();

            QList<ChangeLogRecord> theirRecords = resLog.prop.values( propUri );
            QList<ChangeLogRecord> ownRecords = getRecords( ownHash, resUri, propUri );
            //kDebug() << "own Records : " << ownRecords.size();

            // This case shouldn't ever happen, but just to be sure
            if( theirRecords.empty() )
                continue;

            if( cardinality == 1 ) {
                resolveSingleCardinality( theirRecords, ownRecords );
            }
            else {
                resolveMultipleCardinality( theirRecords, ownRecords );
            }
        }

        //if( !rs.propHash.isEmpty() )
        //    m_jobs.append( rs );
    }
    //theirHash.clear();
    //kDebug() << "Done with merge resolution : " << m_jobs.size();

    //processJobs();
}


namespace {

    Nepomuk::ChangeLogRecord maxRecord( const QList<Nepomuk::ChangeLogRecord> & records ) {
        QList<Nepomuk::ChangeLogRecord>::const_iterator it = std::max_element( records.begin(), records.end() );
        if( it != records.constEnd() )
            return *it;
        return Nepomuk::ChangeLogRecord();
    }
}


void Nepomuk::ChangeLogMerger::resolveSingleCardinality(const QList< Nepomuk::ChangeLogRecord >& theirRecords, const QList< Nepomuk::ChangeLogRecord >& ownRecords)
{
    kDebug() << "O: " << ownRecords.size() << " " << "T:" << theirRecords.size();

    //Find max on the basis of time stamp
    ChangeLogRecord theirMax = maxRecord( theirRecords );
    ChangeLogRecord ownMax = maxRecord( ownRecords );
    kDebug() << "TheirMax : "<< theirMax.toString();
    kDebug() << "OwnMax " << ownMax.toString();

    if( theirMax > ownMax ) {
        Soprano::Statement statement( theirMax.st().subject(), theirMax.st().predicate(),
                                      Soprano::Node(), Soprano::Node() );

        if( theirMax.added() ) {
            Soprano::Node object = theirMax.st().object();
            kDebug() << "Resolved - Adding " << object;

            if( !model()->containsAnyStatement( statement ) ) {
                statement.setObject( object );
                statement.setContext( m_theGraph );
                model()->addStatement( statement );
            }
        }
        else {
            kDebug() << "Resolved - Removing";
            model()->removeAllStatements( statement );
        }
    }
}

namespace {

    struct MergeData {
        bool added;
        QDateTime dateTime;

        MergeData( bool add, const QDateTime & dt )
            : added( add ),
              dateTime( dt )
        {}
    };


}

void Nepomuk::ChangeLogMerger::resolveMultipleCardinality( const QList<Nepomuk::ChangeLogRecord>& theirRecords, const QList<Nepomuk::ChangeLogRecord>& ownRecords)
{
    kDebug() << "MULTIPLE";
    kDebug() << "O: " << ownRecords.size() << " " << "T:" << theirRecords.size();

    const Soprano::Statement& reference = theirRecords.first().st();
    Soprano::Statement baseStatement( reference.subject(), reference.predicate(), Soprano::Node(), Soprano::Node() );

    //
    // Merge both record lists
    //
    //TODO: Optimize merging - use merge sort or something equivilant
    QList<ChangeLogRecord> records = ownRecords;
    records << theirRecords;
    qSort( records );

    QHash<Soprano::Node, MergeData> hash;
    foreach( const ChangeLogRecord rec, records ) {
        Soprano::Node object = rec.st().object();
        QHash<Soprano::Node, MergeData>::const_iterator it = hash.constFind( object );
        if( it == hash.constEnd() ) {
            hash.insert( object, MergeData( rec.added(), rec.dateTime() ) );
        }
        else {
            // +ve after -ve
            if( rec.added() == true && it.value().added == false ) {
                hash.remove( object );
                hash.insert( object, MergeData( rec.added(), rec.dateTime() ) );
            }
            // -ve after +ve
            else if( rec.added() == false && it.value().added == true ) {
                hash.remove( object );
            }
            // +ve after +ve
            // -ve after -ve
            //    Do nothing
        }
    }

    //
    // Do the actual merging
    //
    QHashIterator<Soprano::Node, MergeData> it( hash );
    while( it.hasNext() ) {
        it.next();

        Soprano::Statement st( baseStatement );
        st.setObject( it.key() );

        MergeData data = it.value();
        if( data.added == true ) {
            if( !model()->containsAnyStatement( st ) ) {
                st.setContext( m_theGraph );
                model()->addStatement( st );
                kDebug() << "adding - " << st;
            }
        }
        else {
            kDebug() << "removing " << st;
            model()->removeAllStatements( st );
        }
    }

    m_multipleMergers.append( Soprano::Statement( baseStatement.subject(),
                                                  baseStatement.predicate(),
                                                  Soprano::Node() ) );
}

QList< Soprano::Statement > Nepomuk::ChangeLogMerger::multipleMergers() const
{
    return m_multipleMergers;
}

bool Nepomuk::ChangeLogMerger::handleResourceDeletion(const KUrl& resUri)
{
    ResourceLog & log = m_hash[ resUri ];
    const KUrl& rdfTypeProp = Soprano::Vocabulary::RDF::type();

    QList<ChangeLogRecord> records = log.prop.values( rdfTypeProp );
    if( records.empty() )
        return false;

    //
    // Check if rdf:type is being removed
    //
    bool removed = false;
    foreach( const ChangeLogRecord & r, records ) {
        if( !r.added() ) {
            removed = true;
            break;
        }
    }
    if( !removed )
        return false;

    // If removed, remove all records and delete the resource
    m_hash.remove( resUri );
    Resource res( resUri );
    res.remove();
    return true;
}