File: xmldocument.cpp

package info (click to toggle)
kdepimlibs 4:4.14.10-11
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 35,856 kB
  • sloc: cpp: 269,391; xml: 4,188; ansic: 2,946; yacc: 1,904; perl: 381; ruby: 60; sh: 60; makefile: 13
file content (330 lines) | stat: -rw-r--r-- 9,092 bytes parent folder | download | duplicates (4)
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
/*
    Copyright (c) 2009 Volker Krause <vkrause@kde.org>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    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 Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "xmldocument.h"
#include "format_p.h"
#include "xmlreader.h"

#include <KDebug>
#include <KGlobal>
#include <KLocalizedString>
#include <KStandardDirs>

#include <qdom.h>
#include <qfile.h>

#ifdef HAVE_LIBXML2
#include <libxml/parser.h>
#include <libxml/xmlIO.h>
#include <libxml/xmlschemas.h>
#endif

static const KCatalogLoader loader( QLatin1String( "libakonadi-xml") );

using namespace Akonadi;

// helper class for dealing with libxml resource management
template <typename T, void FreeFunc(T)> class XmlPtr
{
  public:
    XmlPtr( const T &t ) : p( t ) {}

    ~XmlPtr()
    {
      FreeFunc( p );
    }

    operator T() const
    {
      return p;
    }

    operator bool() const
    {
      return p != 0;
    }

  private:
    T p;
};

static QDomElement findElementByRidHelper( const QDomElement &elem, const QString &rid, const QString &elemName )
{
  if ( elem.isNull() )
    return QDomElement();
  if ( elem.tagName() == elemName && elem.attribute( Format::Attr::remoteId() ) == rid )
    return elem;
  const QDomNodeList children = elem.childNodes();
  for ( int i = 0; i < children.count(); ++i ) {
    const QDomElement child = children.at( i ).toElement();
    if ( child.isNull() )
      continue;
    const QDomElement rv = findElementByRidHelper( child, rid, elemName );
    if ( !rv.isNull() )
      return rv;
  }
  return QDomElement();
}

namespace Akonadi {

class XmlDocumentPrivate
{
  public:
    XmlDocumentPrivate() :
      valid( false )
    {
      lastError = i18n( "No data loaded." );
    }

    QDomElement findElementByRid( const QString &rid, const QString &elemName ) const
    {
      return findElementByRidHelper( document.documentElement(), rid, elemName );
    }

    QDomDocument document;
    QString lastError;
    bool valid;
};

}

XmlDocument::XmlDocument() :
  d( new XmlDocumentPrivate )
{
  const QDomElement rootElem = d->document.createElement( Format::Tag::root() );
  d->document.appendChild( rootElem );
}

XmlDocument::XmlDocument(const QString& fileName) :
  d( new XmlDocumentPrivate )
{
  loadFile( fileName );
}

XmlDocument::~XmlDocument()
{
  delete d;
}

bool Akonadi::XmlDocument::loadFile(const QString& fileName)
{
  d->valid = false;
  d->document = QDomDocument();

  if ( fileName.isEmpty() ) {
    d->lastError = i18n( "No filename specified" );
    return false;
  }

  QFile file( fileName );
  QByteArray data;
  if ( file.exists() ) {
    if ( !file.open( QIODevice::ReadOnly ) ) {
      d->lastError = i18n( "Unable to open data file '%1'.", fileName );
      return false;
    }
    data = file.readAll();
  } else {
    d->lastError = i18n( "File %1 does not exist.", fileName );
    return false;
  }

#ifdef HAVE_LIBXML2
  // schema validation
  XmlPtr<xmlDocPtr, xmlFreeDoc> sourceDoc( xmlParseMemory( data.constData(), data.length() ) );
  if ( !sourceDoc ) {
    d->lastError = i18n( "Unable to parse data file '%1'.", fileName );
    return false;
  }

  const QString &schemaFileName = KGlobal::dirs()->findResource( "data", QLatin1String("akonadi/akonadi-xml" SOVERSION ".xsd") );
  XmlPtr<xmlDocPtr, xmlFreeDoc> schemaDoc( xmlReadFile( schemaFileName.toLocal8Bit(), 0, XML_PARSE_NONET ) );
  if ( !schemaDoc ) {
    d->lastError = i18n( "Schema definition could not be loaded and parsed." );
    return false;
  }
  XmlPtr<xmlSchemaParserCtxtPtr, xmlSchemaFreeParserCtxt> parserContext( xmlSchemaNewDocParserCtxt( schemaDoc ) );
  if ( !parserContext ) {
    d->lastError = i18n( "Unable to create schema parser context." );
    return false;
  }
  XmlPtr<xmlSchemaPtr, xmlSchemaFree> schema( xmlSchemaParse( parserContext ) );
  if ( !schema ) {
    d->lastError = i18n( "Unable to create schema." );
    return false;
  }
  XmlPtr<xmlSchemaValidCtxtPtr, xmlSchemaFreeValidCtxt> validationContext( xmlSchemaNewValidCtxt( schema ) );
  if ( !validationContext ) {
    d->lastError = i18n( "Unable to create schema validation context." );
    return false;
  }

  if ( xmlSchemaValidateDoc( validationContext, sourceDoc ) != 0 ) {
    d->lastError = i18n( "Invalid file format." );
    return false;
  }
#endif

  // DOM loading
  QString errMsg;
  if ( !d->document.setContent( data, true, &errMsg ) ) {
    d->lastError = i18n( "Unable to parse data file: %1", errMsg );
    return false;
  }

  d->valid = true;
  d->lastError.clear();
  return true;
}

bool XmlDocument::writeToFile(const QString& fileName) const
{
  QFile f( fileName );
  if ( !f.open( QFile::WriteOnly ) ) {
    d->lastError = f.errorString();
    return false;
  }

  f.write( d->document.toByteArray( 2 ) );

  d->lastError.clear();
  return true;
}

bool XmlDocument::isValid() const
{
  return d->valid;
}

QString XmlDocument::lastError() const
{
  return d->lastError;
}

QDomDocument& XmlDocument::document() const
{
  return d->document;
}

QDomElement XmlDocument::collectionElementByRemoteId(const QString& rid) const
{
  return d->findElementByRid( rid, Format::Tag::collection() );
}

QDomElement XmlDocument::collectionElement( const Collection &collection ) const
{
  if ( collection == Collection::root() )
    return d->document.documentElement();
  if ( collection.remoteId().isEmpty() )
    return QDomElement();
  if ( collection.parentCollection().remoteId().isEmpty() && collection.parentCollection() != Collection::root() )
    return d->findElementByRid( collection.remoteId(), Format::Tag::collection() );
  QDomElement parent = collectionElement( collection.parentCollection() );
  if ( parent.isNull() )
    return QDomElement();
  const QDomNodeList children = parent.childNodes();
  for ( int i = 0; i < children.count(); ++i ) {
    const QDomElement child = children.at( i ).toElement();
    if ( child.isNull() )
      continue;
   if ( child.tagName() == Format::Tag::collection() && child.attribute( Format::Attr::remoteId() ) == collection.remoteId() )
    return child;
  }
  return QDomElement();
}

QDomElement XmlDocument::itemElementByRemoteId(const QString& rid) const
{
  return d->findElementByRid( rid, Format::Tag::item() );
}

Collection XmlDocument::collectionByRemoteId(const QString& rid) const
{
  const QDomElement elem = collectionElementByRemoteId( rid );
  return XmlReader::elementToCollection( elem );
}

Item XmlDocument::itemByRemoteId(const QString& rid, bool includePayload) const
{
  return XmlReader::elementToItem( itemElementByRemoteId( rid ), includePayload );
}

Collection::List XmlDocument::collections() const
{
  return XmlReader::readCollections( d->document.documentElement() );
}

Tag::List XmlDocument::tags() const
{
  return XmlReader::readTags( d->document.documentElement() );
}

Collection::List XmlDocument::childCollections(const QString& parentCollectionRid) const
{
  Collection c;
  c.setRemoteId( parentCollectionRid );
  return childCollections( c );
}

Collection::List XmlDocument::childCollections( const Collection &parentCollection ) const
{
  QDomElement parentElem = collectionElement( parentCollection );

  if ( parentElem.isNull() ) {
    d->lastError = QLatin1String( "Parent node not found." );
    return Collection::List();
  }

  Collection::List rv;
  const QDomNodeList children = parentElem.childNodes();
  for ( int i = 0; i < children.count(); ++i ) {
    const QDomElement childElem = children.at( i ).toElement();
    if ( childElem.isNull() || childElem.tagName() != Format::Tag::collection() )
      continue;
    Collection c = XmlReader::elementToCollection( childElem );
    c.setParentCollection( parentCollection );
    rv.append( c );
  }

  return rv;
}


Item::List XmlDocument::items(const Akonadi::Collection& collection, bool includePayload) const
{
  const QDomElement colElem = collectionElement( collection );
  if ( colElem.isNull() ) {
    d->lastError = i18n( "Unable to find collection %1", collection.name() );
    return Item::List();
  } else {
    d->lastError.clear();
  }

  Item::List items;
  const QDomNodeList children = colElem.childNodes();
  for ( int i = 0; i < children.count(); ++i ) {
    const QDomElement itemElem = children.at( i ).toElement();
    if ( itemElem.isNull() || itemElem.tagName() != Format::Tag::item() )
      continue;
    items += XmlReader::elementToItem( itemElem, includePayload );
  }

  return items;
}