Debian Codegraph @

src/serviceframework/databasemanager.cpp

raw symbols SCIP
1 /****************************************************************************
2 **
3 ** Copyright (C) 2018 The Qt Company Ltd and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the QtSystems module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 3 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL3 included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 3 requirements
23 ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24 **
25 ** GNU General Public License Usage
26 ** Alternatively, this file may be used under the terms of the GNU
27 ** General Public License version 2.0 or (at your option) the GNU General
28 ** Public license version 3 or any later version approved by the KDE Free
29 ** Qt Foundation. The licenses are as published by the Free Software
30 ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31 ** included in the packaging of this file. Please review the following
32 ** information to ensure the GNU General Public License requirements will
33 ** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34 ** https://www.gnu.org/licenses/gpl-3.0.html.
35 **
36 ** $QT_END_LICENSE$
37 **
38 ****************************************************************************/
39
40 #include "databasemanager_p.h"
41 #include "qserviceinterfacedescriptor_p.h"
42 #include <QFileSystemWatcher>
43 #include <QHash>
44
45 QT_BEGIN_NAMESPACE
46
47 DatabaseFileWatcher::DatabaseFileWatcher(DatabaseManager *parent)
48 : QObject(parent),
49 m_manager(parent),
50 m_watcher(0)
51 {
52 }
53
54 QString DatabaseFileWatcher::closestExistingParent(const QString &path)
55 {
56 if (QFile::exists(path))
57 return path;
58
59 int lastSep = path.lastIndexOf(QDir::separator());
60 if (lastSep < 0)
61 return QString();
62 return closestExistingParent(path.mid(0, lastSep));
63 }
64
65 void DatabaseFileWatcher::restartDirMonitoring(const QString &dbPath, const QString &previousDirPath)
66 {
67 if (m_watcher->files().contains(dbPath))
68 return;
69
70 QString existing = closestExistingParent(dbPath);
71 if (existing.isEmpty()) {
72 qWarning() << "QServiceManager: can't find existing directory for path to database" << dbPath
73 << "serviceAdded() and serviceRemoved() will not be emitted";
74 return;
75 }
76 if (existing == dbPath) {
77 ServiceDatabase *db = 0;
78 DatabaseManager::DbScope scope;
79 if (m_manager->m_userDb && dbPath == m_manager->m_userDb->databasePath()) {
80 db = m_manager->m_userDb;
81 scope = DatabaseManager::UserOnlyScope;
82 } else if (dbPath == m_manager->m_systemDb->databasePath()) {
83 db = m_manager->m_systemDb;
84 scope = DatabaseManager::SystemScope;
85 }
86
87 if (db) {
88 if (!previousDirPath.isEmpty())
89 m_watcher->removePath(previousDirPath);
90 QMutableListIterator<QString> i(m_monitoredDbPaths);
91 while (i.hasNext()) {
92 if (i.next() == dbPath)
93 i.remove();
94 }
95
96 QStringList newServices = m_manager->getServiceNames(QString(), scope);
97 for (int i=0; i<newServices.count(); i++)
98 emit m_manager->serviceAdded(newServices[i], scope);
99 setEnabled(db, true);
100 }
101 } else {
102 if (previousDirPath != existing) {
103 if (!previousDirPath.isEmpty())
104 m_watcher->removePath(previousDirPath);
105 if (!m_watcher->directories().contains(existing))
106 m_watcher->addPath(existing);
107 if (!m_monitoredDbPaths.contains(dbPath))
108 m_monitoredDbPaths << dbPath;
109 }
110 }
111 }
112
113 void DatabaseFileWatcher::setEnabled(ServiceDatabase *database, bool enabled)
114 {
115 if (!m_watcher) {
116 m_watcher = new QFileSystemWatcher(this);
117 connect(m_watcher, SIGNAL(fileChanged(QString)),
118 SLOT(databaseChanged(QString)));
119 connect(m_watcher, SIGNAL(directoryChanged(QString)),
120 SLOT(databaseDirectoryChanged(QString)));
121 }
122
123 QString path = database->databasePath();
124 if (enabled) {
125 if (QFile::exists(path)) {
126 if (!database->isOpen())
127 database->open();
128 m_knownServices[path] = database->getServiceNames(QString());
129 m_watcher->addPath(path);
130 } else {
131 restartDirMonitoring(path, QString());
132 }
133 } else {
134 m_watcher->removePath(path);
135 m_knownServices.remove(path);
136 }
137 }
138
139 void DatabaseFileWatcher::databaseDirectoryChanged(const QString &path)
140 {
141 for (int i=0; i<m_monitoredDbPaths.count(); i++) {
142 if (m_monitoredDbPaths[i].contains(path))
143 restartDirMonitoring(m_monitoredDbPaths[i], path);
144 }
145 }
146
147 void DatabaseFileWatcher::databaseChanged(const QString &path)
148 {
149 if (m_manager->m_userDb && path == m_manager->m_userDb->databasePath())
150 notifyChanges(m_manager->m_userDb, DatabaseManager::UserScope);
151 else if (path == m_manager->m_systemDb->databasePath())
152 notifyChanges(m_manager->m_systemDb, DatabaseManager::SystemScope);
153
154 // if database was deleted, the path may have been dropped
155 if (!m_watcher->files().contains(path) && QFile::exists(path))
156 m_watcher->addPath(path);
157 }
158
159 void DatabaseFileWatcher::notifyChanges(ServiceDatabase *database, DatabaseManager::DbScope scope)
160 {
161 QString dbPath = database->databasePath();
162 if (!QFile::exists(dbPath)) {
163 m_knownServices.remove(dbPath);
164 restartDirMonitoring(dbPath, QString());
165 return;
166 }
167
168 QStringList currentServices = database->getServiceNames(QString());
169 if (database->lastError().code() !=DBError::NoError) {
170 qWarning("QServiceManager: failed to get current service names for serviceAdded() and serviceRemoved() signals");
171 return;
172 }
173
174 const QStringList &knownServicesRef = m_knownServices[dbPath];
175
176 QSet<QString> currentServicesSet = currentServices.toSet();
177 QSet<QString> knownServicesSet = knownServicesRef.toSet();
178 if (currentServicesSet == knownServicesSet)
179 return;
180
181 QStringList newServices;
182 for (int i=0; i<currentServices.count(); i++) {
183 if (!knownServicesSet.contains(currentServices[i]))
184 newServices << currentServices[i];
185 }
186
187 QStringList removedServices;
188 for (int i=0; i<knownServicesRef.count(); i++) {
189 if (!currentServicesSet.contains(knownServicesRef[i]))
190 removedServices << knownServicesRef[i];
191 }
192
193 m_knownServices[dbPath] = currentServices;
194 for (int i=0; i<newServices.count(); i++)
195 emit m_manager->serviceAdded(newServices[i], scope);
196 for (int i=0; i<removedServices.count(); i++)
197 emit m_manager->serviceRemoved(removedServices[i], scope);
198 }
199
200 bool lessThan(const QServiceInterfaceDescriptor &d1,
201 const QServiceInterfaceDescriptor &d2)
202 {
203 return (d1.majorVersion() < d2.majorVersion())
204 || ( d1.majorVersion() == d2.majorVersion()
205 && d1.minorVersion() < d2.minorVersion());
206 }
207
208 /*
209 \class DatabaseManager
210 The database manager is responsible for receiving queries about
211 services and managing user and system scope databases in order to
212 respond to those queries.
213
214 It provides operations for
215 - registering and unregistering services
216 - querying for services and interfaces
217 - setting and getting default interface implementations
218
219 and provides notifications by emitting signals for added
220 or removed services.
221
222 Implementation note:
223 When one of the above operations is first invoked a connection with the
224 appropriate database(s) is opened. This connection remains
225 open until the DatabaseManager is destroyed.
226
227 If the system scope database cannot be opened when performing
228 user scope operations. The operations are carried out as per normal
229 but only acting on the user scope database. Each operation invokation
230 will try to open a connection with the system scope database.
231
232 Terminology note:
233 When referring to user scope regarding operations, it generally
234 means access to both the user and system databases with the
235 data from both combined into a single dataset.
236 When referring to a user scope database it means the
237 user database only.
238
239 */
240
241 /*
242 Constructor
243 */
244 DatabaseManager::DatabaseManager()
245 : m_userDb(NULL),
246 m_systemDb(new ServiceDatabase),
247 m_fileWatcher(0),
248 m_hasAccessedUserDb(false),
249 m_alreadyWarnedOpenError(false)
250 {
251 m_userDb = new ServiceDatabase;
252 initDbPath(UserScope);
253 initDbPath(SystemScope);
254 }
255
256 /*
257 Destructor
258 */
259 DatabaseManager::~DatabaseManager()
260 {
261 delete m_fileWatcher;
262 m_fileWatcher = 0;
263
264 //Aside: databases are implicitly closed
265 //during deletion
266 if (m_userDb) {
267 m_userDb->close();
268 delete m_userDb;
269 }
270 m_userDb = 0;
271
272 if (m_systemDb) {
273 m_systemDb->close();
274 delete m_systemDb;
275 }
276 m_systemDb = 0;
277 }
278
279
280 /*
281 Initialises database path of m_userDb
282 or m_systemDb, but does not open any
283 database connections
284 */
285 void DatabaseManager::initDbPath(DbScope scope)
286 {
287 QSettings::Scope settingsScope;
288 QString dbIdentifier;
289 ServiceDatabase *db;
290 if (scope == SystemScope) {
291 settingsScope = QSettings::SystemScope;
292 dbIdentifier = QLatin1String("_system");
293 db = m_systemDb;
294 } else {
295 settingsScope = QSettings::UserScope;
296 dbIdentifier = QLatin1String("_user");
297 db = m_userDb;
298 }
299
300 #ifdef QT_SIMULATOR
301 dbIdentifier.append(QLatin1String("_simulator"));
302 #endif
303
304 QSettings settings(QSettings::IniFormat, settingsScope,
305 QLatin1String("Nokia"), QLatin1String("QtServiceFramework"));
306 QFileInfo fi(settings.fileName());
307 QDir dir = fi.dir();
308 QString qtVersion = QLatin1String(qVersion());
309 qtVersion = qtVersion.left(qtVersion.size() -2); //strip off patch version
310 QString dbName = QString(QLatin1String("QtServiceFramework_")) + qtVersion + dbIdentifier + QLatin1String(".db");
311 db->setDatabasePath(dir.path() + QDir::separator() + dbName);
312 }
313
314 /*
315 Adds the details \a service into the service database corresponding to
316 \a scope.
317
318 Returns true if the operation succeeded and false otherwise.
319 The last error is set when this function is called.
320 */
321 bool DatabaseManager::registerService(ServiceMetaDataResults &service, DbScope scope)
322 {
323 if (scope == DatabaseManager::SystemScope) {
324 if (!openDb(DatabaseManager::SystemScope)) {
325 return false;
326 } else {
327 if (!m_systemDb->registerService(service)) {
328 m_lastError = m_systemDb->lastError();
329 return false;
330 } else { //must be successful registration
331 m_lastError.setError(DBError::NoError);
332 return true;
333 }
334 }
335 } else { //must be registering service at user scope
336 if (!openDb(DatabaseManager::UserScope)) {
337 return false;
338 } else {
339 if (!m_userDb->registerService(service)) {
340 m_lastError = m_userDb->lastError();
341 return false;
342 } else { //must be successful registration
343 m_lastError.setError(DBError::NoError);
344 return true;
345 }
346 }
347 }
348 }
349
350 /*
351 Removes the details of \serviceName from the database corresponding to \a
352 scope.
353
354 Returns true if the operation succeeded, false otherwise.
355 The last error is set when this function is called.
356 */
357 bool DatabaseManager::unregisterService(const QString &serviceName, DbScope scope)
358 {
359 if (scope == DatabaseManager::SystemScope) {
360 if (!openDb(DatabaseManager::SystemScope))
361 return false;
362 else {
363 if (!m_systemDb->unregisterService(serviceName)) {
364 m_lastError = m_systemDb->lastError();
365 return false;
366 } else { //must be successful unregistration
367 m_lastError.setError(DBError::NoError);
368 return true;
369 }
370 }
371 } else {
372 if (!openDb(DatabaseManager::UserScope)) {
373 return false;
374 } else {
375 if (!m_userDb->unregisterService(serviceName)){
376 m_lastError = m_userDb->lastError();
377 return false;
378 } else { //must be successful unregistration
379 m_lastError.setError(DBError::NoError);
380 return true;
381 }
382 }
383 }
384 }
385
386 /*
387 Removes the initialization specific information of \serviceName from the database
388 corresponding to a \scope.
389
390 Returns true if teh operation succeeded, false otherwise.
391 The last error is set when this function is called.
392 */
393 bool DatabaseManager::serviceInitialized(const QString &serviceName, DbScope scope)
394 {
395 ServiceDatabase *db = (scope == DatabaseManager::SystemScope) ? m_systemDb : m_userDb;
396
397 if (!openDb(scope)) {
398 return false;
399 } else {
400 if (!db->serviceInitialized(serviceName)) {
401 m_lastError = db->lastError();
402 return false;
403 } else {
404 m_lastError.setError(DBError::NoError);
405 return true;
406 }
407 }
408 }
409
410 /*
411 Retrieves a list of interface descriptors that fulfill the constraints specified
412 by \a filter at a given \a scope.
413
414 The last error is set when this function is called.
415 */
416 QList<QServiceInterfaceDescriptor> DatabaseManager::getInterfaces(const QServiceFilter &filter, DbScope scope)
417 {
418 QList<QServiceInterfaceDescriptor> descriptors;
419
420 int userDescriptorCount = 0;
421 if (scope == UserScope) {
422 if (!openDb(UserScope))
423 return descriptors;
424
425 descriptors = m_userDb->getInterfaces(filter);
426 if (m_userDb->lastError().code() != DBError::NoError ) {
427 descriptors.clear();
428 m_lastError = m_userDb->lastError();
429 return descriptors;
430 }
431
432 userDescriptorCount = descriptors.count();
433 for (int i=0; i < userDescriptorCount; ++i) {
434 descriptors[i].d->scope = QService::UserScope;
435 }
436 }
437
438 if (openDb(SystemScope)) {
439 descriptors.append(m_systemDb->getInterfaces(filter));
440 if (m_systemDb->lastError().code() != DBError::NoError) {
441 descriptors.clear();
442 m_lastError = m_systemDb->lastError();
443 return descriptors;
444 }
445
446 for (int i = userDescriptorCount; i < descriptors.count(); ++i)
447 descriptors[i].d->scope = QService::SystemScope;
448 } else {
449 if ( scope == SystemScope) {
450 //openDb() should already have handled lastError
451 descriptors.clear();
452 return descriptors;
453 }
454 }
455
456 m_lastError.setError(DBError::NoError);
457 return descriptors;
458 }
459
460
461 /*
462 Retrieves a list of the names of services that provide the interface
463 specified by \a interfaceName.
464
465 The last error is set when this function is called.
466 */
467 QStringList DatabaseManager::getServiceNames(const QString &interfaceName, DatabaseManager::DbScope scope)
468 {
469 QStringList serviceNames;
470 if (scope == UserScope || scope == UserOnlyScope) {
471 if (!openDb(DatabaseManager::UserScope))
472 return serviceNames;
473 serviceNames = m_userDb->getServiceNames(interfaceName);
474 if (m_userDb->lastError().code() != DBError::NoError) {
475 serviceNames.clear();
476 m_lastError = m_userDb->lastError();
477 return serviceNames;
478 }
479 if (scope == UserOnlyScope) {
480 m_lastError.setError(DBError::NoError);
481 return serviceNames;
482 }
483 }
484
485 if (openDb(DatabaseManager::SystemScope)) {
486 QStringList systemServiceNames;
487 systemServiceNames = m_systemDb->getServiceNames(interfaceName);
488 if (m_systemDb->lastError().code() != DBError::NoError) {
489 serviceNames.clear();
490 m_lastError = m_systemDb->lastError();
491 return serviceNames;
492 }
493 foreach (const QString &systemServiceName, systemServiceNames) {
494 if (!serviceNames.contains(systemServiceName, Qt::CaseInsensitive))
495 serviceNames.append(systemServiceName);
496 }
497
498 } else {
499 if ( scope == SystemScope) {
500 //openDb() should have already handled lastError
501 serviceNames.clear();
502 return serviceNames;
503 }
504 }
505
506 m_lastError.setError(DBError::NoError);
507 return serviceNames;
508 }
509
510 /*
511 Returns the default interface implementation descriptor for a given
512 \a interfaceName and \a scope.
513
514 The last error is set when this function is called.
515 */
516 QServiceInterfaceDescriptor DatabaseManager::interfaceDefault(const QString &interfaceName, DbScope scope)
517 {
518 QServiceInterfaceDescriptor descriptor;
519 if (scope == UserScope) {
520 if (!openDb(UserScope))
521 return QServiceInterfaceDescriptor();
522 QString interfaceID;
523 descriptor = m_userDb->interfaceDefault(interfaceName, &interfaceID);
524
525 if (m_userDb->lastError().code() == DBError::NoError) {
526 descriptor.d->scope = QService::UserScope;
527 return descriptor;
528 } else if (m_userDb->lastError().code() == DBError::ExternalIfaceIDFound) {
529 //default hasn't been found in user db, but we have found an ID
530 //that may refer to an interface implementation in the system db
531 if (!openDb(SystemScope)) {
532 QString errorText(QLatin1String("No default service found for interface: \"%1\""));
533 m_lastError.setError(DBError::NotFound, errorText.arg(interfaceName));
534 return QServiceInterfaceDescriptor();
535 }
536
537 descriptor = m_systemDb->getInterface(interfaceID);
538 //found the service from the system database
539 if (m_systemDb->lastError().code() == DBError::NoError) {
540 m_lastError.setError(DBError::NoError);
541 descriptor.d->scope = QService::SystemScope;
542 return descriptor;
543 } else if (m_systemDb->lastError().code() == DBError::NotFound) {
544 //service implementing interface doesn't exist in the system db
545 //so the user db must contain a stale entry so remove it
546 m_userDb->removeExternalDefaultServiceInterface(interfaceID);
547
548 QList<QServiceInterfaceDescriptor> descriptors;
549 descriptors = getInterfaces(QServiceFilter(interfaceName), UserScope);
550
551 //make the latest interface implementation the new
552 //default if there is one
553 if (descriptors.count() > 0 ) {
554 descriptor = latestDescriptor(descriptors);
555 setInterfaceDefault(descriptor, UserScope);
556 m_lastError.setError(DBError::NoError);
557 return descriptor;
558 } else {
559 QString errorText(QLatin1String("No default service found for interface: \"%1\""));
560 m_lastError.setError(DBError::NotFound, errorText.arg(interfaceName));
561 return QServiceInterfaceDescriptor();
562 }
563 } else {
564 m_lastError.setError(DBError::NoError);
565 return QServiceInterfaceDescriptor();
566 }
567 } else if (m_userDb->lastError().code() == DBError::NotFound) {
568 //do nothing, the search for a default in the system db continues
569 //further down
570 } else { //error occurred at user db level, so return
571 m_lastError = m_userDb->lastError();
572 return QServiceInterfaceDescriptor();
573 }
574 }
575
576 //search at system scope because we haven't found a default at user scope
577 //or because we're specifically only querying at system scope
578 if (!openDb(SystemScope)) {
579 if (scope == SystemScope) {
580 m_lastError = m_systemDb->lastError();
581 return QServiceInterfaceDescriptor();
582 } else if (scope == UserScope && m_userDb && m_userDb->lastError().code() == DBError::NotFound) {
583 m_lastError = m_userDb->lastError();
584 return QServiceInterfaceDescriptor();
585 }
586 } else {
587 descriptor = m_systemDb->interfaceDefault(interfaceName);
588 if (m_systemDb->lastError().code() == DBError::NoError) {
589 descriptor.d->scope = QService::SystemScope;
590 return descriptor;
591 } else if (m_systemDb->lastError().code() == DBError::NotFound) {
592 m_lastError = m_systemDb->lastError();
593 return QServiceInterfaceDescriptor();
594 } else {
595 m_lastError = m_systemDb->lastError();
596 return QServiceInterfaceDescriptor();
597 }
598 }
599
600 //should not be possible to reach here
601 m_lastError.setError(DBError::UnknownError);
602 return QServiceInterfaceDescriptor();
603 }
604
605 /*
606 Sets the default interface implemenation for \a interfaceName to the matching
607 interface implementation provided by \a service.
608
609 If \a service provides more than one interface implementation, the newest
610 version of the interface is set as the default.
611
612 Returns true if the operation was succeeded, false otherwise
613 The last error is set when this function is called.
614 */
615 bool DatabaseManager::setInterfaceDefault(const QString &serviceName, const
616 QString &interfaceName, DbScope scope)
617 {
618 QList<QServiceInterfaceDescriptor> descriptors;
619 QServiceFilter filter;
620 filter.setServiceName(serviceName);
621 filter.setInterface(interfaceName);
622
623 descriptors = getInterfaces(filter, scope);
624 if (m_lastError.code() != DBError::NoError)
625 return false;
626
627 if (descriptors.count() == 0) {
628 QString errorText(QLatin1String("No implementation for interface \"%1\" "
629 "found for service \"%2\""));
630 m_lastError.setError(DBError::NotFound,
631 errorText.arg(interfaceName)
632 .arg(serviceName));
633 return false;
634 }
635
636 //find the descriptor with the latest version
637 int latestIndex = 0;
638 for (int i = 1; i < descriptors.count(); ++i) {
639 if (lessThan(descriptors[latestIndex], descriptors[i]))
640 latestIndex = i;
641 }
642
643 return setInterfaceDefault(descriptors[latestIndex], scope);
644 }
645
646 /*
647 Sets the interface implementation specified by \a descriptor to be the default
648 implementation for the particular interface specified in the descriptor.
649
650 Returns true if the operation succeeded, false otherwise.
651 The last error is set when this function is called.
652 */
653 bool DatabaseManager::setInterfaceDefault(const QServiceInterfaceDescriptor &descriptor, DbScope scope)
654 {
655 if (scope == UserScope) {
656 if (!openDb(UserScope))
657 return false;
658 if (descriptor.scope() == QService::UserScope) { //if a user scope descriptor, just set it in the user db
659 if (m_userDb->setInterfaceDefault(descriptor)) {
660 m_lastError.setError(DBError::NoError);
661 return true;
662 } else {
663 m_lastError = m_userDb->lastError();
664 return false;
665 }
666 } else { //otherwise we need to get the interfaceID from the system db and set this
667 //as an external default interface ID in the user db
668 if (!openDb(SystemScope))
669 return false;
670
671 QString interfaceDescriptorID = m_systemDb->getInterfaceID(descriptor);
672 if (m_systemDb->lastError().code() == DBError::NoError) {
673 if (m_userDb->setInterfaceDefault(descriptor, interfaceDescriptorID)) {
674 m_lastError.setError(DBError::NoError);
675 return true;
676 } else {
677 m_lastError = m_userDb->lastError();
678 return false;
679 }
680 } else {
681 m_lastError = m_systemDb->lastError();
682 return false;
683 }
684 }
685 } else { //scope == SystemScope
686 if (descriptor.scope() == QService::UserScope) {
687 QString errorText(QLatin1String("Cannot set default service at system scope with a user scope "
688 "interface descriptor"));
689 m_lastError.setError(DBError::InvalidDescriptorScope, errorText);
690 return false;
691 } else {
692 if (!openDb(SystemScope)) {
693 return false;
694 } else {
695 if (m_systemDb->setInterfaceDefault(descriptor)) {
696 m_lastError.setError(DBError::NoError);
697 return true;
698 } else {
699 m_lastError = m_systemDb->lastError();
700 return false;
701 }
702 }
703 }
704 }
705 }
706
707 /*
708 Opens a database connection with the database at a specific \a scope.
709
710 The last error is set when this function is called.
711 */
712 bool DatabaseManager::openDb(DbScope scope)
713 {
714 if (scope == SystemScope && m_systemDb->isOpen() && !QFile::exists(m_systemDb->databasePath())) {
715 delete m_systemDb;
716 m_systemDb = new ServiceDatabase;
717 initDbPath(SystemScope);
718 m_alreadyWarnedOpenError = false;
719 } else if (scope != SystemScope && m_userDb->isOpen() && !QFile::exists(m_userDb->databasePath())) {
720 delete m_userDb;
721 m_userDb = new ServiceDatabase;
722 initDbPath(UserScope);
723 m_alreadyWarnedOpenError = false;
724 }
725
726 ServiceDatabase *db;
727 if (scope == SystemScope) {
728 db = m_systemDb;
729 }
730 else {
731 db = m_userDb;
732 m_hasAccessedUserDb = true;
733 }
734
735 if (db->isOpen())
736 return true;
737
738 bool isOpen = db->open();
739 if (!isOpen) {
740 #ifdef QT_SFW_SERVICEDATABASE_DEBUG
741 qWarning() << "DatabaseManger::openDb():-"
742 << "Problem:" << qPrintable(m_lastError.text());
743 #endif
744 if (scope == SystemScope && m_hasAccessedUserDb == true) {
745 if (QFile::exists(m_systemDb->databasePath()) && !m_alreadyWarnedOpenError)
746 qWarning() << "Service Framework:- Unable to access system database for a user scope "
747 "operation; resorting to using only the user database. Future operations "
748 "will attempt to access the system database but no further warnings will be issued";
749 }
750
751 QString warning;
752 if (db->lastError().code() == DBError::InvalidDatabaseFile) {
753 warning = QString(QLatin1String("Service Framework:- Database file is corrupt or invalid: ")) + db->databasePath();
754 m_lastError = db->lastError();
755 } else {
756 warning = QString(QLatin1String("Service Framework:- Unable to open or create database at: ")) + db->databasePath();
757 QString errorText(QLatin1String("Unable to open service framework database: %1"));
758 m_lastError.setError(DBError::CannotOpenServiceDb,
759 errorText.arg(db->databasePath()));
760 }
761
762 if (m_alreadyWarnedOpenError
763 || (scope == SystemScope && m_hasAccessedUserDb && !QFile::exists(m_systemDb->databasePath()))) {
764 //do nothing, don't output warning if already warned or we're accessing the system database
765 //from user scope and the system database doesn't exist
766 } else {
767 qWarning() << qPrintable(warning);
768 m_alreadyWarnedOpenError = true;
769 }
770
771 return false;
772 }
773
774 //if we are opening the system database while the user database is open,
775 //cleanup and reset any old external defaults
776 //from the user scope database
777 if (scope == SystemScope && m_userDb && m_userDb->isOpen()) {
778 QList<QPair<QString,QString> > externalDefaultsInfo;
779 externalDefaultsInfo = m_userDb->externalDefaultsInfo();
780 QServiceInterfaceDescriptor descriptor;
781 QPair<QString,QString> defaultInfo;
782
783 for (int i = 0; i < externalDefaultsInfo.count(); ++i) {
784 defaultInfo = externalDefaultsInfo[i];
785 descriptor = m_userDb->getInterface(defaultInfo.second);
786 if (m_userDb->lastError().code() == DBError::NotFound) {
787 m_userDb->removeExternalDefaultServiceInterface(defaultInfo.second);
788 QList<QServiceInterfaceDescriptor> descriptors;
789 descriptors = getInterfaces(QServiceFilter(defaultInfo.first), UserScope);
790
791 if (descriptors.count() > 0 ) {
792 descriptor = latestDescriptor(descriptors);
793 setInterfaceDefault(descriptor, UserScope);
794 }
795 }
796 }
797 }
798
799 m_lastError.setError(DBError::NoError);
800 return true;
801 }
802
803 /*
804 Returns the interface descriptor with the highest version from the
805 list of interface \a descriptors
806 */
807 QServiceInterfaceDescriptor DatabaseManager::latestDescriptor(
808 const QList<QServiceInterfaceDescriptor> &descriptors)
809 {
810 if (descriptors.count() == 0)
811 return QServiceInterfaceDescriptor();
812
813 int latestIndex = 0;
814 for (int i = 1; i < descriptors.count(); ++i) {
815 if (lessThan(descriptors[latestIndex], descriptors[i]))
816 latestIndex = i;
817 }
818
819 return descriptors[latestIndex];
820 }
821
822 /*
823 Sets whether change notifications for added and removed services are
824 \a enabled or not at a given \a scope.
825 */
826 void DatabaseManager::setChangeNotificationsEnabled(DbScope scope, bool enabled)
827 {
828 if (!m_fileWatcher) m_fileWatcher = new
829 DatabaseFileWatcher(this); m_fileWatcher->setEnabled(scope == SystemScope ?
830 m_systemDb : m_userDb, enabled);
831 }
832
833 #include "moc_databasemanager_p.cpp"
834
835 QT_END_NAMESPACE