diff options
author | Matt Vogt <matthew.vogt@jollamobile.com> | 2014-06-12 11:30:12 +1000 |
---|---|---|
committer | Matthew Vogt <matthew.vogt@qinetic.com.au> | 2014-06-16 03:30:19 +0200 |
commit | 2c771de92d5c47d6ac58ab5f5b3e709b915492f3 (patch) | |
tree | 1c21bcb78cfd2b8869304deae2552882e680dade | |
parent | dfa4e6b792837c192e7e664c41f567ad986756a5 (diff) |
Remove jsondb backends
The jsondb contact and organizer backends are unsupported.
Change-Id: I6aa76c94b97edad20d43d777f75ec66f0400b65e
Reviewed-by: Christopher Adams <chris.adams@jollamobile.com>
114 files changed, 210 insertions, 19191 deletions
diff --git a/examples/organizer/qmlorganizerlistview/qmlorganizerlistview.qml b/examples/organizer/qmlorganizerlistview/qmlorganizerlistview.qml index 9fddb6fa6..ca367bf35 100644 --- a/examples/organizer/qmlorganizerlistview/qmlorganizerlistview.qml +++ b/examples/organizer/qmlorganizerlistview/qmlorganizerlistview.qml @@ -147,7 +147,6 @@ Rectangle { id: organizer startPeriod: new Date("1970-01-01") endPeriod: new Date("2012-12-31") - //manager:"jsondb" manager: "memory" Component.onCompleted: { diff --git a/src/contacts/contacts.pro b/src/contacts/contacts.pro index 4d237440b..008b04a74 100644 --- a/src/contacts/contacts.pro +++ b/src/contacts/contacts.pro @@ -70,10 +70,6 @@ SOURCES += \ qcontactsortorder.cpp \ qcontactengineid.cpp \ -qtHaveModule(jsondb) { - isEmpty(CONTACTS_DEFAULT_ENGINE): CONTACTS_DEFAULT_ENGINE=jsondb -} - !isEmpty(CONTACTS_DEFAULT_ENGINE): DEFINES += Q_CONTACTS_DEFAULT_ENGINE=$$CONTACTS_DEFAULT_ENGINE HEADERS += $$PUBLIC_HEADERS $$PRIVATE_HEADERS diff --git a/src/imports/contacts/qdeclarativecontactdetail.cpp b/src/imports/contacts/qdeclarativecontactdetail.cpp index 2fefbc666..0a7ccf194 100644 --- a/src/imports/contacts/qdeclarativecontactdetail.cpp +++ b/src/imports/contacts/qdeclarativecontactdetail.cpp @@ -529,14 +529,6 @@ QDeclarativeContactDetail *QDeclarativeContactDetailFactory::createContactDetail \ingroup qml-contacts-details \inqmlmodule QtContacts 5.0 - Note for the jsondb manager backend: it converts extended detail data of type date, - time or javascript Date to a string expressed in local timezone in ISO 8601 format - without timezone specified. Javascript function Date.parse() cannot be used - to parse this string, since it interprets the string without timezone specified - being in UTC. It is recommended to convert dates to strings before storing them - to extended details. For example, javascript functions Date.toISOString() and - Date.parse() can be used for the conversion. - ExtendedDetail element contains the following field types: \list \li ExtendedDetail.Name diff --git a/src/organizer/doc/snippets/qmlorganizerbasiclist/qmlorganizerbasiclist.qml b/src/organizer/doc/snippets/qmlorganizerbasiclist/qmlorganizerbasiclist.qml index d394929fb..8af0bcd19 100644 --- a/src/organizer/doc/snippets/qmlorganizerbasiclist/qmlorganizerbasiclist.qml +++ b/src/organizer/doc/snippets/qmlorganizerbasiclist/qmlorganizerbasiclist.qml @@ -49,7 +49,6 @@ Rectangle { autoUpdate:true //! [Manager Choice] -// manager:"qtorganizer:jsondb:id=qml" manager:"qtorganizer:memory:id=qml" //! [Manager Choice] diff --git a/src/organizer/organizer.pro b/src/organizer/organizer.pro index 967c54e95..b21c628a2 100644 --- a/src/organizer/organizer.pro +++ b/src/organizer/organizer.pro @@ -67,10 +67,6 @@ SOURCES += \ qorganizeritemsortorder.cpp \ qorganizermanager_p.cpp -qtHaveModule(jsondb) { - isEmpty(ORGANIZER_DEFAULT_ENGINE): ORGANIZER_DEFAULT_ENGINE=jsondb -} - !isEmpty(ORGANIZER_DEFAULT_ENGINE): DEFINES += Q_ORGANIZER_DEFAULT_ENGINE=$$ORGANIZER_DEFAULT_ENGINE HEADERS += $$PUBLIC_HEADERS $$PRIVATE_HEADERS diff --git a/src/organizer/qorganizermanagerengine.cpp b/src/organizer/qorganizermanagerengine.cpp index 342201249..488025139 100644 --- a/src/organizer/qorganizermanagerengine.cpp +++ b/src/organizer/qorganizermanagerengine.cpp @@ -1233,7 +1233,6 @@ bool QOrganizerManagerEngine::addDefaultSorted(QMultiMap<QDateTime, QOrganizerIt QDateTime sortTime; if (toAdd.type() == QOrganizerItemType::TypeEvent || toAdd.type() == QOrganizerItemType::TypeEventOccurrence) { QOrganizerEventTime eventTime = toAdd.detail(QOrganizerItemDetail::TypeEventTime); - // both start and end times are mandatory for an event in jsondb schema, so all this checking might redundant if (eventTime.startDateTime().isValid()) sortTime = eventTime.startDateTime(); else if (eventTime.endDateTime().isValid()) diff --git a/src/plugins/contacts/contacts.pro b/src/plugins/contacts/contacts.pro index e1faa72ba..69245f374 100644 --- a/src/plugins/contacts/contacts.pro +++ b/src/plugins/contacts/contacts.pro @@ -2,8 +2,6 @@ TEMPLATE = subdirs CONFIG += ordered -qtHaveModule(jsondb): SUBDIRS += jsondb - SUBDIRS += memory #contains(mobility_modules,serviceframework): SUBDIRS += serviceactionmanager diff --git a/src/plugins/contacts/jsondb/jsondb.json b/src/plugins/contacts/jsondb/jsondb.json deleted file mode 100644 index d127ebcb7..000000000 --- a/src/plugins/contacts/jsondb/jsondb.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "Keys": [ "jsondb" ] -} diff --git a/src/plugins/contacts/jsondb/jsondb.pro b/src/plugins/contacts/jsondb/jsondb.pro deleted file mode 100644 index c4f384d0f..000000000 --- a/src/plugins/contacts/jsondb/jsondb.pro +++ /dev/null @@ -1,24 +0,0 @@ -TARGET = qtcontacts_jsondb -QT += contacts-private jsondb - -PLUGIN_TYPE = contacts -load(qt_plugin) - -HEADERS += qcontactjsondbenginefactory.h \ - qcontactjsondbengine.h \ - qcontactjsondbrequesthandler.h \ - qcontactjsondbrequestmanager.h \ - qcontactjsondbconverter.h \ - qcontactjsondbglobal.h \ - qcontactjsondbid.h \ - qcontactjsondbstring.h - -SOURCES += qcontactjsondbenginefactory.cpp \ - qcontactjsondbengine.cpp \ - qcontactjsondbrequesthandler.cpp \ - qcontactjsondbrequestmanager.cpp \ - qcontactjsondbconverter.cpp \ - qcontactjsondbid.cpp \ - qcontactjsondbstring.cpp - -OTHER_FILES += jsondb.json diff --git a/src/plugins/contacts/jsondb/qcontactjsondbconverter.cpp b/src/plugins/contacts/jsondb/qcontactjsondbconverter.cpp deleted file mode 100644 index 8a89f7ce7..000000000 --- a/src/plugins/contacts/jsondb/qcontactjsondbconverter.cpp +++ /dev/null @@ -1,1441 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtContacts module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qcontactjsondbconverter.h" - -#include <QtCore/qcryptographichash.h> -#include <QtCore/qdebug.h> -#include <QtCore/qjsonarray.h> -#include <QtCore/qlist.h> -#include <QtCore/quuid.h> - -#include <QtContacts/qcontactdetail.h> -#include <QtContacts/qcontacttype.h> -#include <QtContacts/qcontactid.h> -#include <QtContacts/qcontactname.h> -#include <QtContacts/qcontactaddress.h> -#include <QtContacts/qcontactnickname.h> -#include <QtContacts/qcontactemailaddress.h> -#include <QtContacts/qcontactphonenumber.h> -#include <QtContacts/qcontactmanager.h> -#include <QtContacts/qcontactmanagerengine.h> -#include <QtContacts/qcontactid.h> -#include <QtContacts/qcontacturl.h> -#include <QtContacts/qcontactabstractrequest.h> - -#include <QtContacts/qcontactactionfilter.h> -#include <QtContacts/qcontactchangelogfilter.h> -#include <QtContacts/qcontactdetailfilter.h> -#include <QtContacts/qcontactidfilter.h> -#include <QtContacts/qcontactintersectionfilter.h> -#include <QtContacts/qcontactrelationshipfilter.h> - -#include "qcontactjsondbglobal.h" -#include "qcontactjsondbid.h" -#include "qcontactjsondbstring.h" - -QT_BEGIN_NAMESPACE_CONTACTS - -const int QContactJsonDbConverter::jsonDbVersionLength(10); - -QContactJsonDbConverter::QContactJsonDbConverter() -{ - initializeMappings(); -} - -QContactJsonDbConverter::~QContactJsonDbConverter() -{ -} - -bool QContactJsonDbConverter::toQContact(const QJsonObject& object, QContact* contact, const QString &partitionName) { - QJsonObject temporaryJsonObject; - QString stringValue; - - stringValue = object.value(QContactJsonDbStr::uuid()).toString(); - if (stringValue.isEmpty()) { - return false; - } - - QContactAbstractRequest::StorageLocation storageLocation; - storageLocation = storageLocationMapping.key(partitionName); - contact->setId(QContactId(new QContactJsonDbId(stringValue, storageLocation))); - - // TODO: other types - contact->setType(QContactType::TypeContact); - - // Go through all fields in loop. - QJsonObject::ConstIterator i = object.constBegin(); - while (i != object.constEnd()) { - if (i.key() == QContactJsonDbStr::version()) { - //version - QContactVersion contactVersion; - jsonDbVersionToContactVersion(i.value().toString(), &contactVersion); - contact->appendDetail(contactVersion); - } else if (i.key() == detailsToJsonMapping.value(QContactName::Type)) { - //name - QContactName name; - temporaryJsonObject = i.value().toObject(); - QHash<int, QString>::ConstIterator nameFieldsIterator = contactNameFieldsMapping.constBegin(); - while (nameFieldsIterator != contactNameFieldsMapping.constEnd()) { - stringValue = temporaryJsonObject.value(nameFieldsIterator.value()).toString(); - if (!stringValue.isEmpty()) { - switch (sanitizeContactDetailString(&stringValue)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": Name field of json object does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - name.setValue(nameFieldsIterator.key(), stringValue); - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - } - nameFieldsIterator++; - } - if (!name.isEmpty()) - contact->appendDetail(name); - } else if (i.key() == detailsToJsonMapping.value(QContactGender::Type)) { - //gender - QContactGender gender; - temporaryJsonObject = i.value().toObject(); - stringValue = temporaryJsonObject.value(detailsToJsonMapping.value(QContactGender::Type)).toString(); - if (!stringValue.isEmpty()) - gender.setGender(static_cast<QContactGender::GenderField>(genderValuesMapping.key(stringValue))); - if (!gender.isEmpty()) - contact->appendDetail(gender); - } else if (i.key() == detailsToJsonMapping.value(QContactOrganization::Type)) { - //organization - QJsonArray array = i.value().toArray(); - for (int i = 0; i < array.size(); ++i) { - QContactOrganization organization; - QJsonObject temporaryJsonObject = array.at(i).toObject(); - QHash<QContactOrganization::OrganizationField, QString>::ConstIterator organizationIter = organizationFieldsMapping.constBegin(); - while (organizationIter != organizationFieldsMapping.constEnd()) { - stringValue = temporaryJsonObject.value(organizationIter.value()).toString(); - if (!stringValue.isEmpty()) { - switch (sanitizeContactDetailString(&stringValue)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": Organization field of json object does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - organization.setValue(organizationIter.key(), stringValue); - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - } - organizationIter++; - } - // logoUrl - stringValue = temporaryJsonObject.value(organizationFieldsMapping.value(QContactOrganization::FieldLogoUrl)).toString(); - if (!stringValue.isEmpty()) - organization.setLogoUrl(QUrl(stringValue)); - // Add organization to details - if (!organization.isEmpty()) - contact->appendDetail(organization); - } - } else if (i.key() == QContactJsonDbStr::contactDetails()) { - temporaryJsonObject = i.value().toObject(); - //birthday - QString dateString; - dateString = temporaryJsonObject[detailsToJsonMapping.value(QContactBirthday::Type)].toString(); - if (!dateString.isEmpty()) { - QDateTime date = toQDateTime(dateString); - QContactBirthday birthday; - birthday.setDateTime(date); - contact->appendDetail(birthday); - } - - //avatar - QString avatarUrlString; - avatarUrlString = temporaryJsonObject[detailsToJsonMapping.value(QContactAvatar::Type)].toString(); - if (!avatarUrlString.isEmpty()) { - QUrl avatarUrl(avatarUrlString); - QContactAvatar avatar; - avatar.setImageUrl(avatarUrl); - contact->appendDetail(avatar); - } - - //ringtone - QString ringtoneUrlString; - ringtoneUrlString = temporaryJsonObject[detailsToJsonMapping.value(QContactRingtone::Type)].toString(); - if (!ringtoneUrlString.isEmpty()) { - QUrl ringtoneUrl(ringtoneUrlString); - QContactRingtone ringtone; - ringtone.setAudioRingtoneUrl(ringtoneUrl); - contact->appendDetail(ringtone); - } - - //nickname - QContactNickname nick; - if (!temporaryJsonObject[detailsToJsonMapping.value(QContactNickname::Type)].toString().isEmpty()) { - QString nickString = temporaryJsonObject[detailsToJsonMapping.value(QContactNickname::Type)].toString(); - switch (sanitizeContactDetailString(&nickString)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": Nickname field of json object does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - nick.setNickname(nickString); - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - } - if (!nick.isEmpty()) - contact->appendDetail(nick); - - //displayLabel - QString displayLabelString; - displayLabelString = temporaryJsonObject[detailsToJsonMapping.value(QContactDisplayLabel::Type)].toString(); - if (!displayLabelString.isEmpty()) { - QContactDisplayLabel label; - label.setLabel(displayLabelString); - contact->appendDetail(label); - } - - //note - QContactNote note; - if (!temporaryJsonObject[detailsToJsonMapping.value(QContactNote::Type)].toString().isEmpty()) { - QString noteString = temporaryJsonObject[detailsToJsonMapping.value(QContactNote::Type)].toString(); - switch (sanitizeContactDetailString(¬eString, 1000)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": Note field of json object does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - note.setNote(noteString); - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - } - if (!note.isEmpty()) { - contact->appendDetail(note); - } - - } else if (i.key() == detailsToJsonMapping.value(QContactEmailAddress::Type)) { - //email - QJsonArray array = i.value().toArray(); - for (int i = 0; i < array.size(); ++i) { - QContactEmailAddress email; - QJsonObject temporaryJsonObject = array[i].toObject(); - if (!temporaryJsonObject["value"].toString().isEmpty()) { - QString emailString = temporaryJsonObject["value"].toString(); - switch (sanitizeContactDetailString(&emailString, 126)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": email field of json object does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - email.setEmailAddress(emailString); - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - } - if (!email.isEmpty()) { - updateContexts(temporaryJsonObject,&email); - contact->appendDetail(email); - } - } - } else if (i.key() == detailsToJsonMapping.value(QContactPhoneNumber::Type)) { - //phone number - QJsonArray array = i.value().toArray(); - for (int i = 0; i < array.size(); ++i) { - QJsonObject temporaryJsonObject = array[i].toObject(); - stringValue = temporaryJsonObject.value("value").toString(); - if (stringValue.isEmpty()) { - qWarning() << Q_FUNC_INFO <<": ignoring phone number field of json object " - << object << "because it is empty."; - continue; - } - if (sanitizePhoneNumberString(&stringValue)) { - QContactPhoneNumber number; - number.setNumber(stringValue); - stringValue = temporaryJsonObject["context"].toString(); - if (stringValue == QContactJsonDbStr::contextHome() || - stringValue == QContactJsonDbStr::contextWork() || - stringValue == QContactJsonDbStr::contextOther()) { - updateContexts(temporaryJsonObject, &number); - } - stringValue = temporaryJsonObject["subType"].toString(); - if (stringValue == QContactJsonDbStr::subTypeFax()) { - QList<int> myType; - myType << QContactPhoneNumber::SubTypeFax; - number.setSubTypes(myType); - } else if (stringValue == QContactJsonDbStr::subTypeCell()) { - QList<int> myType; - myType << QContactPhoneNumber::SubTypeMobile; - number.setSubTypes(myType); - } else if (stringValue == QContactJsonDbStr::subTypeVideo()) { - QList<int> myType; - myType << QContactPhoneNumber::SubTypeVideo; - number.setSubTypes(myType); - } else if (stringValue == QContactJsonDbStr::subTypeLandline()) { - QList<int> myType; - myType << QContactPhoneNumber::SubTypeLandline; - number.setSubTypes(myType); - }; - contact->appendDetail(number); - } else { - qWarning() << Q_FUNC_INFO <<":Number field of json object does not contain a valid " - << " jsondb phone number."; - return false; - } - } - } else if (i.key() == detailsToJsonMapping.value(QContactAddress::Type)) { - //address - QJsonArray array = i.value().toArray(); - for (int j = 0; j < array.size(); ++j) { - QContactAddress address; - QJsonObject temporaryJsonObject = array.at(j).toObject(); - QHash<QContactAddress::AddressField, QString>::ConstIterator addressIter = addressFieldsMapping.constBegin(); - while (addressIter != addressFieldsMapping.constEnd()) { - stringValue = temporaryJsonObject.value(addressIter.value()).toString(); - if (!stringValue.isEmpty()) { - switch (sanitizeContactDetailString(&stringValue)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": address field of json object does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - address.setValue(addressIter.key(), stringValue); - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - } - addressIter++; - } - if (!address.isEmpty()) { - updateContexts(temporaryJsonObject, &address); - contact->appendDetail(address); - } - } - } else if (i.key() == detailsToJsonMapping.value(QContactUrl::Type)) { - //url - QJsonArray array = i.value().toArray(); - for (int i = 0; i < array.size(); ++i) { - QContactUrl url; - QJsonObject temporaryJsonObject = array[i].toObject(); - url.setUrl(temporaryJsonObject["value"].toString()); - if (updateContexts(temporaryJsonObject, &url)) - url.setSubType(static_cast<QContactUrl::SubType>(url.contexts().first()));//TODO decide if we use "Context" or "SubTypes" to store the jsondb SubTypes - contact->appendDetail(url); - } - } else if (i.key() == detailsToJsonMapping.value(QContactSyncTarget::Type)) { - stringValue = object.value(detailsToJsonMapping.value(QContactSyncTarget::Type)).toString(); - if (!stringValue.isEmpty()) { - QContactSyncTarget syncTarget; - syncTarget.setSyncTarget(stringValue); - contact->appendDetail(syncTarget); - } - } else if (i.key() == detailsToJsonMapping.value(QContactGuid::Type)) { - stringValue = object.value(detailsToJsonMapping.value(QContactGuid::Type)).toString(); - if (!stringValue.isEmpty()) { - QContactGuid guid; - guid.setGuid(stringValue); - contact->appendDetail(guid); - } - } else if (i.key().at(0) == QChar('_')) { - // skip as it's used internally - } else { - // we map anything else to extended details - QContactExtendedDetail extendedDetail; - extendedDetail.setName(i.key()); - extendedDetail.setData(i.value().toVariant()); - contact->appendDetail(extendedDetail); - } - ++i; - } - if (contact->isEmpty()) { - return false; - } else { - return true; - }; -} - -bool QContactJsonDbConverter::toJsonContact(QJsonObject* object, const QContact& contact, const QList<QContactDetail::DetailType> &detailMask) -{ - - QList<QContactDetail> details = contact.details(); - QContactDetail detail; - QContactName* name; - QContactNickname* nick; - QContactDisplayLabel *label; - QContactEmailAddress* email; - QContactPhoneNumber* number; - QContactAddress* address; - QContactUrl* url; - QContactVersion* version; - QContactOrganization* organization; - QContactBirthday* birthday; - QContactAvatar* avatar; - QContactRingtone* ringtone; - QContactNote* note; - QContactGender* gender; - QContactExtendedDetail* extendedDetail; - QContactSyncTarget* syncTarget; - QContactGuid* guid; - QJsonArray phoneNumbers; - QJsonArray emails; - QJsonArray urls; - QJsonArray organizations; - QJsonArray addresses; - QJsonObject embeddedDetailsObject; - - if (!contact.id().isNull()) - object->insert (QContactJsonDbStr::uuid(), contactIdToUuid(contact.id())); - - // get all available contact details. - object->insert(QContactJsonDbStr::type(), QContactJsonDbStr::contactsJsonDbType()); - - if (!object->empty()) { - if (detailMask.empty()) { - // Quickfix for preserving possible extra fields in jsondb contact. - // Wipe QContact fields that may be empty/deleted, preserve all other data. - object->remove(detailsToJsonMapping.value(QContactName::Type)); - object->remove(detailsToJsonMapping.value(QContactGender::Type)); - object->remove(detailsToJsonMapping.value(QContactOrganization::Type)); - object->remove(detailsToJsonMapping.value(QContactEmailAddress::Type)); - object->remove(detailsToJsonMapping.value(QContactPhoneNumber::Type)); - object->remove(detailsToJsonMapping.value(QContactAddress::Type)); - object->remove(detailsToJsonMapping.value(QContactUrl::Type)); - embeddedDetailsObject = object->value(QContactJsonDbStr::contactDetails()).toObject(); - object->remove(QContactJsonDbStr::contactDetails()); - embeddedDetailsObject.remove(detailsToJsonMapping.value(QContactBirthday::Type)); - embeddedDetailsObject.remove(detailsToJsonMapping.value(QContactAvatar::Type)); - embeddedDetailsObject.remove(detailsToJsonMapping.value(QContactRingtone::Type)); - embeddedDetailsObject.remove(detailsToJsonMapping.value(QContactNickname::Type)); - embeddedDetailsObject.remove(detailsToJsonMapping.value(QContactNote::Type)); - embeddedDetailsObject.remove(detailsToJsonMapping.value(QContactDisplayLabel::Type)); - // Preseserve possible extra contact details jsondb contact object may have. - if (!embeddedDetailsObject.isEmpty()) { - object->insert(QContactJsonDbStr::contactDetails(), embeddedDetailsObject); - } - // End of Quickfix - } else { - // Remove masked details from the object as they will be updated later - // with a new value if one exists in the in given QContact. - // If a new value does not exists in the QContact the detail stays removed. - foreach (const QContactDetail::DetailType &type, detailMask) { - // For now, try to remove from both though each type is in one object only. - object->remove(detailsToJsonMapping.value(type)); - embeddedDetailsObject.remove(detailsToJsonMapping.value(type)); - } - } - } - - for(int i = 0; i < details.size(); ++i) { - detail = details.at(i); - - // If it is partial save and the detail is not in the mask we keep the original detail. - if (!detailMask.isEmpty() && !detailMask.contains(detail.type())) - continue; - - switch (detail.type()) { - case QContactDetail::TypeName: { - QJsonObject nameObject; - name = static_cast<QContactName *>(&detail); - QMap<int, QVariant>::const_iterator nameFieldsIterator = name->values().constBegin(); - QString name_field; - while (nameFieldsIterator != name->values().constEnd()) { - if (nameFieldsIterator.value().type() == QVariant::String) { - name_field = nameFieldsIterator.value().toString(); - switch (sanitizeContactDetailString(&name_field)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": Name detail does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - nameObject[contactNameFieldsMapping.value(nameFieldsIterator.key())] = name_field; - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - } - nameFieldsIterator++; - } - if (!nameObject.isEmpty()) - object->insert(detailsToJsonMapping.value(QContactName::Type), nameObject); - break; - } - case QContactDetail::TypeGender: { - QJsonObject genderObject; - gender = static_cast<QContactGender *>(&detail); - genderObject[detailsToJsonMapping.value(QContactGender::Type)] = genderValuesMapping.value(gender->gender()); - object->insert(detailsToJsonMapping.value(QContactGender::Type), genderObject); - break; - } - case QContactDetail::TypeOrganization: { - QJsonObject jsonObject; - organization = static_cast<QContactOrganization *>(&detail); - QMap<int, QVariant>::const_iterator organizationIter = organization->values().constBegin(); - QString organization_field; - organization_field = organizationIter.value().toString(); - switch (sanitizeContactDetailString(&organization_field)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": Name field of organization detail does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - jsonObject[organizationFieldsMapping.value(QContactOrganization::FieldName)] = organization_field; - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - // - for (int i=0; i<organization->department().count();i++) - { - organization_field = organization->department().at(i); // .join("") - switch (sanitizeContactDetailString(&organization_field)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": Department field of organization detail does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - jsonObject[organizationFieldsMapping.value(QContactOrganization::FieldDepartment)] = organization_field; - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - } - // - organization_field = organization->title(); - switch (sanitizeContactDetailString(&organization_field)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": Title field of organization detail does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - jsonObject[organizationFieldsMapping.value(QContactOrganization::FieldTitle)] = organization_field; - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - // - organization_field = organization->role(); - switch (sanitizeContactDetailString(&organization_field)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": Role field of organization detail does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - jsonObject[organizationFieldsMapping.value(QContactOrganization::FieldRole)] = organization_field; - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - // - organization_field = organization->assistantName(); - switch (sanitizeContactDetailString(&organization_field)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": AssistantName field of organization detail does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - jsonObject[organizationFieldsMapping.value(QContactOrganization::FieldAssistantName)] = organization_field; - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - // - organization_field = organization->location(); - switch (sanitizeContactDetailString(&organization_field)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": Location field of organization detail does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - jsonObject[organizationFieldsMapping.value(QContactOrganization::FieldLocation)] = organization_field; - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - - jsonObject[organizationFieldsMapping.value(QContactOrganization::FieldLogoUrl)] = organization->logoUrl().toString(); - if (!jsonObject.isEmpty()) { - updateContexts(*organization, &jsonObject); - organizations.append(jsonObject); - break; - } - } - case QContactDetail::TypeBirthday: { - birthday = static_cast<QContactBirthday *>(&detail); - QDateTime date = birthday->dateTime(); - QString dateString = toJsonDbDate(date); - embeddedDetailsObject[detailsToJsonMapping.value(QContactBirthday::Type)] = dateString; - object->insert(QContactJsonDbStr::contactDetails(), embeddedDetailsObject); - break; - } - case QContactDetail::TypeAvatar: { - avatar = static_cast<QContactAvatar *>(&detail); - embeddedDetailsObject[detailsToJsonMapping.value(QContactAvatar::Type)] = avatar->imageUrl().toString(); - object->insert(QContactJsonDbStr::contactDetails(), embeddedDetailsObject); - break; - } - case QContactDetail::TypeRingtone: { - ringtone = static_cast<QContactRingtone *>(&detail); - embeddedDetailsObject[detailsToJsonMapping.value(QContactRingtone::Type)] = ringtone->audioRingtoneUrl().toString(); - object->insert(QContactJsonDbStr::contactDetails(), embeddedDetailsObject); - break; - } - case QContactDetail::TypeNickname: { - nick = static_cast<QContactNickname *>(&detail); - QString nickname_field = nick->nickname(); - switch (sanitizeContactDetailString(&nickname_field)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": nick detail does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - embeddedDetailsObject[detailsToJsonMapping.value(QContactNickname::Type)] = nickname_field; - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - if (!embeddedDetailsObject.isEmpty()) - object->insert(QContactJsonDbStr::contactDetails(), embeddedDetailsObject); - break; - } - case QContactDetail::TypeDisplayLabel: { - label = static_cast<QContactDisplayLabel *>(&detail); - embeddedDetailsObject[detailsToJsonMapping.value(QContactDisplayLabel::Type)] = label->label(); - object->insert(QContactJsonDbStr::contactDetails(), embeddedDetailsObject); - break; - } - case QContactDetail::TypeNote: { - note = static_cast<QContactNote *>(&detail); - QString note_field = note->note(); - switch (sanitizeContactDetailString(¬e_field, 1000)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": note detail does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - embeddedDetailsObject[detailsToJsonMapping.value(QContactNote::Type)] = note_field; - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - if (!embeddedDetailsObject.isEmpty()) - object->insert(QContactJsonDbStr::contactDetails(), embeddedDetailsObject); - break; - } - case QContactDetail::TypeEmailAddress: { - QJsonObject emailObject; - email = static_cast<QContactEmailAddress *>(&detail); - QString email_field = email->emailAddress(); - switch (sanitizeContactDetailString(&email_field, 126)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": email detail does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - emailObject["value"] = email_field; - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - if (!emailObject.isEmpty()) { - updateContexts(*email, &emailObject); - emails.append(emailObject); - } - break; - } - case QContactDetail::TypePhoneNumber: { - QJsonObject phoneObject; - number = static_cast<QContactPhoneNumber *>(&detail); - QString phoneString (number->number()); - if (phoneString.isEmpty()) { - qWarning() << Q_FUNC_INFO <<": Ignoring number field of detail " - << detail << "because it is empty. "; - break; - } - if (sanitizePhoneNumberString(&phoneString)) { - phoneObject["value"] = phoneString; - updateContexts(*number, &phoneObject); - QList<int> subTypes = number->subTypes(); - if (!subTypes.empty()) - phoneObject["subType"] = phoneNumbersSubtypesMapping.value(number->subTypes().first()); - phoneNumbers.append(phoneObject); - } else { - qWarning() << Q_FUNC_INFO <<": Number field of detail " << detail << "does not contain a valid " - << " jsondb phone number."; - return false; - } - break; - } - case QContactDetail::TypeAddress: { - QJsonObject addressObject; - address = static_cast<QContactAddress *>(&detail); - QMap<int, QVariant>::const_iterator addressIter = address->values().constBegin(); - QString address_field; - address_field = addressIter.value().toString(); - switch (sanitizeContactDetailString(&address_field)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": Street field of address detail does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - addressObject[addressFieldsMapping.value(QContactAddress::FieldStreet)] = address_field; - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - // - address_field = address->locality(); - switch (sanitizeContactDetailString(&address_field)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": Locality field of address detail does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - addressObject[addressFieldsMapping.value(QContactAddress::FieldLocality)] = address_field; - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - // - address_field = address->postcode(); - switch (sanitizeContactDetailString(&address_field)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": PostCode field of address detail does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - addressObject[addressFieldsMapping.value(QContactAddress::FieldPostcode)] = address_field; - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - // - address_field = address->postOfficeBox(); - switch (sanitizeContactDetailString(&address_field)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": PostOfficeBox field of address detail does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - addressObject[addressFieldsMapping.value(QContactAddress::FieldPostOfficeBox)] = address_field; - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - // - address_field = address->region(); - switch (sanitizeContactDetailString(&address_field)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": Region field of address detail does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - addressObject[addressFieldsMapping.value(QContactAddress::FieldRegion)] = address_field; - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - // - address_field = address->country(); - switch (sanitizeContactDetailString(&address_field)) { - case QContactJsonDbConverter::InvalidArgumentError: - qWarning() << Q_FUNC_INFO <<": Country field of address detail does not contain a valid jsondb detail"; - return false; - break; - case QContactJsonDbConverter::NoError: - addressObject[addressFieldsMapping.value(QContactAddress::FieldCountry)] = address_field; - break; - case QContactJsonDbConverter::EmptyArgumentError: - break; - } - // - if (!addressObject.isEmpty()) { - updateContexts(*address, &addressObject); - addresses.append(addressObject); - } - break; - } - case QContactDetail::TypeUrl: { - QJsonObject urlObject; - url = static_cast<QContactUrl *>(&detail); - urlObject["value"] = url->url(); - updateContexts(*url, &urlObject); - urls.append(urlObject); - break; - } - case QContactDetail::TypeVersion: { - version = static_cast<QContactVersion *>(&detail); - QString jsonDbVersion; - contactVersionToJsonDbVersion(*version, &jsonDbVersion); - if (!jsonDbVersion.isEmpty()) - object->insert(QContactJsonDbStr::version(), jsonDbVersion); - break; - } - case QContactDetail::TypeExtendedDetail: { - extendedDetail = static_cast<QContactExtendedDetail *>(&detail); - QString extDetailName = extendedDetail->name(); - if ( (!extDetailName.isEmpty()) && ((extDetailName.at(0) != QChar('_'))) ) { - QJsonValue property = QJsonValue::fromVariant(details.at(i).value(QContactExtendedDetail::FieldData)); - if (!property.isNull()) - object->insert(extDetailName, property); - } - break; - } - case QContactDetail::TypeSyncTarget: { - syncTarget = static_cast<QContactSyncTarget *>(&detail); - if (!syncTarget->syncTarget().isEmpty()) - object->insert(QContactJsonDbStr::syncTargetDefinitionName(), syncTarget->syncTarget()); - break; - } - case QContactDetail::TypeGuid: { - guid = static_cast<QContactGuid *>(&detail); - if (!guid->guid().isEmpty()) - object->insert(QContactJsonDbStr::guidDefinitionName(), guid->guid()); - break; - } - case QContactDetail::TypeType: - default: - break; - } - } - if (!phoneNumbers.isEmpty()) - object->insert(detailsToJsonMapping.value(QContactPhoneNumber::Type), phoneNumbers); - if (!emails.isEmpty()) - object->insert(detailsToJsonMapping.value(QContactEmailAddress::Type), emails); - if (!urls.isEmpty()) - object->insert(detailsToJsonMapping.value(QContactUrl::Type), urls); - if (!organizations.isEmpty()) - object->insert(detailsToJsonMapping.value(QContactOrganization::Type), organizations); - if (!addresses.isEmpty()) - object->insert(detailsToJsonMapping.value(QContactAddress::Type), addresses); - return true; -} - -bool QContactJsonDbConverter::updateContexts(const QJsonObject &object, QContactDetail *detail) -{ - if (!detail) - return false; - QString stringValue = object["context"].toString(); - if (stringValue == QContactJsonDbStr::contextHome()) { - detail->setContexts(QContactDetail::ContextHome); - return true; - } else if (stringValue == QContactJsonDbStr::contextWork()) { - detail->setContexts(QContactDetail::ContextWork); - return true; - } else if (stringValue == QContactJsonDbStr::contextOther()) { - detail->setContexts(QContactDetail::ContextOther); - return true; - } - return false; -} - -bool QContactJsonDbConverter::updateContexts(const QContactDetail& detail, QJsonObject* object) { - QList<int> contexts = detail.contexts(); - if(contexts.size() == 0) - return false; - if(contexts.contains(QContactDetail::ContextHome)) - object->insert("context", QContactJsonDbStr::contextHome()); - else if(contexts.contains(QContactDetail::ContextWork)) - object->insert("context", QContactJsonDbStr::contextWork()); - else if(contexts.contains(QContactDetail::ContextOther)) - object->insert("context", QContactJsonDbStr::contextOther()); - return true; -} - -bool QContactJsonDbConverter::queryFromRequest(QContactAbstractRequest *request,QString &newJsonDbQuery) -{ - bool isValidQuery = false; - if (!request) { - newJsonDbQuery = ""; - return isValidQuery; - } - - newJsonDbQuery = "[?" + QContactJsonDbStr::type() + "=\""+ QContactJsonDbStr::contactsJsonDbType() + "\"]"; - switch (request->type()) { - case QContactAbstractRequest::ContactSaveRequest: { - //TODO: - break; - } - case QContactAbstractRequest::ContactFetchByIdRequest: { - QContactFetchByIdRequest* fetchReq = static_cast<QContactFetchByIdRequest*>(request); - QString idString; - idsToJsondbQuery(fetchReq->contactIds(), idString); - newJsonDbQuery.append(idString); - isValidQuery = true; - break; - } - case QContactAbstractRequest::ContactFetchRequest: { - QContactFetchRequest* fetchReq = static_cast<QContactFetchRequest*>(request); - QContactFilter filter = fetchReq->filter(); - QString filterString; - isValidQuery = compoundFilterToJsondbQuery(filter,filterString); - newJsonDbQuery.append(filterString); - if (!isValidQuery) - return isValidQuery; - QList<QContactSortOrder> sorting = fetchReq->sorting(); - newJsonDbQuery.append(convertSortOrder(sorting)); - break; - } - case QContactAbstractRequest::ContactIdFetchRequest: { - newJsonDbQuery.append(QContactJsonDbStr::uuidSelectQuery()); - - QContactIdFetchRequest* idReq = static_cast<QContactIdFetchRequest*>(request); - QContactFilter filter = idReq->filter(); - QString filterString; - isValidQuery = compoundFilterToJsondbQuery(filter,filterString); - newJsonDbQuery.append(filterString); - if (!isValidQuery) - return isValidQuery; - QList<QContactSortOrder> sorting = idReq->sorting(); - newJsonDbQuery.append(convertSortOrder(sorting)); - break; - } - default: - break; - } - if (qt_debug_jsondb_contacts()) - qDebug() << " JSONDB QUERY: " << newJsonDbQuery; - return isValidQuery; -} - -bool QContactJsonDbConverter::compoundFilterToJsondbQuery(const QContactFilter &filter, QString &jsonDbQueryStr) const -{ - bool isValidFilter = true; - switch (filter.type()) { - case QContactFilter::IntersectionFilter: { - const QContactIntersectionFilter isf(filter); - const QList<QContactFilter> filterList = isf.filters(); - foreach (const QContactFilter &filter, filterList){ - QString filterStr; - if (compoundFilterToJsondbQuery(filter, filterStr)) - jsonDbQueryStr += filterStr; - else //For intersection filter, single filter invalid means empty result from jsondb query - isValidFilter = false; - } - break; - } - case QContactFilter::UnionFilter: { - //not supported yet - isValidFilter = false; - break; - } - default: - isValidFilter = singleFilterToJsondbQuery(filter, jsonDbQueryStr); - break; - } - if (!isValidFilter) - jsonDbQueryStr.clear(); - - if (qt_debug_jsondb_contacts()) { - if (filter.type() == QContactFilter::IntersectionFilter) - qDebug()<<"INTERSECTION FILTER PART OF THE QUERY:"<<jsonDbQueryStr; - } - - return isValidFilter; -} - -bool QContactJsonDbConverter::singleFilterToJsondbQuery(const QContactFilter &filter,QString &jsonDbQueryStr) const -{ - bool isValidFilter = true; - switch (filter.type()) { - case QContactFilter::ContactDetailFilter: { - isValidFilter = detailFilterToJsondbQuery(filter, jsonDbQueryStr); - break; - } - case QContactFilter::IdFilter: { - isValidFilter = idFilterToJsondbQuery(filter, jsonDbQueryStr); - break; - } - case QContactFilter::DefaultFilter: { - jsonDbQueryStr.clear(); - isValidFilter = true; - break; - } - case QContactFilter::InvalidFilter: - case QContactFilter::ContactDetailRangeFilter: - case QContactFilter::ChangeLogFilter: - case QContactFilter::ActionFilter: - case QContactFilter::RelationshipFilter: - case QContactFilter::IntersectionFilter: - case QContactFilter::UnionFilter: - default: { - jsonDbQueryStr.clear(); - isValidFilter = false; - break; - } - } - if (qt_debug_jsondb_contacts()) - qDebug() << "SINGLE FILTER PART OF THE QUERY: " << jsonDbQueryStr; - return isValidFilter; -} - -bool QContactJsonDbConverter::detailFilterToJsondbQuery(const QContactFilter &filter, QString &jsonDbQueryStr) const -{ - //bool isValidFilter = isSupportedDetailFilter(filter, detailType, detailField); - //TODO isSupportedDetailFilter implementation to be done, as of now we assume that support - //filters for all detail types - bool isValidFilter = true; - QContactDetailFilter detailFilter(filter); - if (detailFilter.detailType() == QContactDetail::TypeUndefined) { - //If definitionName is empty, the detail filter will match no contacts - jsonDbQueryStr = ""; - return false; - } - QString jsondbField = detailsToJsonMapping.value(detailFilter.detailType()); - if (!jsondbField.isEmpty() && detailFilter.detailField()<0) { - // If fieldName or value is empty, the detail filter acts like a "detail exists" filter - jsonDbQueryStr.append("[?" + jsondbField + " exists]"); - return true; - } - // Filter by name (first or last) - if (detailFilter.detailType() == QContactName::Type) - { - if (qt_debug_jsondb_contacts()) - qDebug() << "Filter by name"; - jsonDbQueryStr.append("[?" + jsondbField + "." + contactNameFieldsMapping.value(detailFilter.detailField())); - QString paramValue = detailFilter.value().toString(); - if (paramValue.isEmpty() || (sanitizeContactDetailString(¶mValue)!=InvalidArgumentError)) { - createMatchFlagQuery(jsonDbQueryStr, detailFilter.matchFlags(), paramValue); - } else { - //detail value could not be sanitized, hence the filter is not valid - isValidFilter = false; - } - } - // Filter by phone number - else if (detailFilter.detailType() == QContactPhoneNumber::Type) - { - if (qt_debug_jsondb_contacts()) - qDebug() << "Filter by phone number"; - if (detailFilter.detailField() == QContactPhoneNumber::FieldNumber) { - jsonDbQueryStr.append("[?" + jsondbField + ".0.value"); - QString paramValue = detailFilter.value().toString(); - if (paramValue.isEmpty() || sanitizePhoneNumberString(¶mValue)) { - createMatchFlagQuery(jsonDbQueryStr, detailFilter.matchFlags(), paramValue); - } else { - //detail value could not be sanitized, hence the filter is not valid - isValidFilter = false; - } - } else { - //We do not support currently filtering by other fields than number - isValidFilter = false; - } - } - // Filter by email address - else if (detailFilter.detailType() == QContactEmailAddress::Type) - { - if (qt_debug_jsondb_contacts()) - qDebug() << "Filter by email address"; - if (detailFilter.detailField() == QContactEmailAddress::FieldEmailAddress) { - jsonDbQueryStr.append("[?" + jsondbField + ".0.value" ); - QString paramValue = detailFilter.value().toString(); - if (paramValue.isEmpty() || (sanitizeContactDetailString(¶mValue)!=InvalidArgumentError)) { - createMatchFlagQuery(jsonDbQueryStr, detailFilter.matchFlags(), paramValue); - } - else { - //detail value could not be sanitized, hence the filter is not valid - isValidFilter = false; - } - } else { - //We do not support currently filter by other fields than email address - isValidFilter = false; - } - } - // Filter by Url - else if (detailFilter.detailType() == QContactUrl::Type) - { - if (qt_debug_jsondb_contacts()) - qDebug() << "Filter by url"; - if (detailFilter.detailField() == QContactUrl::FieldUrl) { - jsonDbQueryStr.append("[?" + jsondbField + ".0.value" ); - QString paramValue = detailFilter.value().toString(); - createMatchFlagQuery(jsonDbQueryStr, detailFilter.matchFlags(), paramValue); - } else { - //We do not support currently filter by other fields than Url - isValidFilter = false; - } - } - // Default case: return all the contacts - else { - // No need to add anything to the already present query: query [?_type="com.nokia.mt.contacts.Contact"] - qWarning() << "Detail" << detailFilter.detailType() - << "not supported by filtering"; - qWarning() << "Query string: " << jsonDbQueryStr; - isValidFilter = false; - } - return isValidFilter; -} - -bool QContactJsonDbConverter::isValidPhoneNumberCharacter(const QChar *character) -{ - return (character->isDigit() || - character->toLatin1() == 'p' || - character->toLatin1() == 'w' || - character->toLatin1() == 'a' || - character->toLatin1() == 'b' || - character->toLatin1() == 'c' || - character->toLatin1() == 'd' || - character->toLatin1() == '#' || - character->toLatin1() == '*' || - character->toLatin1() == '(' || - character->toLatin1() == ')' || - character->toLatin1() == '-'); -} - -bool QContactJsonDbConverter::idFilterToJsondbQuery(const QContactFilter &filter, QString &newJsonDbQuery) const -{ - QContactIdFilter idFilter(filter); - QList<QContactId> ids = idFilter.ids(); - if (!ids.isEmpty()) - idsToJsondbQuery(ids, newJsonDbQuery); - else - newJsonDbQuery.append("[?" + QContactJsonDbStr::uuid() + " in []]"); - return true; -} - -void QContactJsonDbConverter::idsToJsondbQuery(const QList<QContactId> &ids, QString &newJsonDbQuery) const -{ - if (!ids.isEmpty()) { - newJsonDbQuery.append("[?" + QContactJsonDbStr::uuid() + - " in ["); - foreach (const QContactId &id, ids) { - newJsonDbQuery.append("\"" + contactIdToUuid(id) + "\""); - newJsonDbQuery.append(","); - } - newJsonDbQuery.chop(1); - newJsonDbQuery.append("]]"); - } -} - -QString QContactJsonDbConverter::convertSortOrder(const QList<QContactSortOrder> &sortOrders) const { - QString newJsonDbQuery; - foreach (QContactSortOrder sortOrder, sortOrders) { - if (sortOrder.detailType() == QContactName::Type) { - sortOrder.direction() == Qt::AscendingOrder ? newJsonDbQuery.append("[/") : newJsonDbQuery.append("[\\"); - newJsonDbQuery.append(detailsToJsonMapping.value(QContactName::Type)); - if (sortOrder.detailField() == QContactName::FieldFirstName) { - newJsonDbQuery.append("." + contactNameFieldsMapping.value(QContactName::FieldFirstName) + "]"); - } else if (sortOrder.detailField() == QContactName::FieldLastName) { - newJsonDbQuery.append("." + contactNameFieldsMapping.value(QContactName::FieldLastName) + "]"); - } - } - else if (sortOrder.detailType() == QContactEmailAddress::Type) { - sortOrder.direction() == Qt::AscendingOrder ? newJsonDbQuery.append("[/") : newJsonDbQuery.append("[\\"); - newJsonDbQuery.append(detailsToJsonMapping.value(QContactEmailAddress::Type)); - newJsonDbQuery.append("."); // + "0" + "." + "value" + "]"); - newJsonDbQuery.append("0"); - newJsonDbQuery.append("."); - newJsonDbQuery.append("value"); - newJsonDbQuery.append("]"); - } - } - if (qt_debug_jsondb_contacts()) - qDebug() << "SORTING PART OF THE QUERY: " << newJsonDbQuery; - return newJsonDbQuery; -} - -QString QContactJsonDbConverter::contactIdToUuid(const QContactId &id) const -{ - if (id.isNull()) - return QString(); - const QContactJsonDbId *jsonDbId = - static_cast<const QContactJsonDbId *>(QContactManagerEngine::engineId(id)); - return jsonDbId->uuid().toString(); -} - -QContactId QContactJsonDbConverter::uuidtoContactId(QString &uuid, const QString &partitionName) const -{ - QContactAbstractRequest::StorageLocation storageLocation; - storageLocation = storageLocationMapping.key(partitionName); - QContactJsonDbId *jsonId = new QContactJsonDbId(uuid, storageLocation); - return QContactId(jsonId); -} - -void QContactJsonDbConverter::initializeMappings() -{ - detailsToJsonMapping.insert(QContactName::Type, QContactJsonDbStr::nameDefinitionName()); - detailsToJsonMapping.insert(QContactGender::Type, QContactJsonDbStr::genderDefinitionName()); - detailsToJsonMapping.insert(QContactPhoneNumber::Type, QContactJsonDbStr::phoneNumberDefinitionName()); - detailsToJsonMapping.insert(QContactEmailAddress::Type, QContactJsonDbStr::emailAddressDefinitionName()); - detailsToJsonMapping.insert(QContactUrl::Type, QContactJsonDbStr::urlDefinitionName()); - detailsToJsonMapping.insert(QContactNickname::Type, QContactJsonDbStr::nicknameDefinitionName()); - detailsToJsonMapping.insert(QContactDisplayLabel::Type, QContactJsonDbStr::displayLabelDefinitionName()); - detailsToJsonMapping.insert(QContactAddress::Type, QContactJsonDbStr::addressDefinitionName()); - detailsToJsonMapping.insert(QContactBirthday::Type, QContactJsonDbStr::birthdayDefinitionName()); - detailsToJsonMapping.insert(QContactAvatar::Type, QContactJsonDbStr::avatarDefinitionName()); - detailsToJsonMapping.insert(QContactRingtone::Type, QContactJsonDbStr::ringtoneDefinitionName()); - detailsToJsonMapping.insert(QContactOrganization::Type,QContactJsonDbStr::organizationDefinitionName()); - detailsToJsonMapping.insert(QContactNote::Type, QContactJsonDbStr::noteDefinitionName()); - detailsToJsonMapping.insert(QContactSyncTarget::Type, QContactJsonDbStr::syncTargetDefinitionName()); - detailsToJsonMapping.insert(QContactGuid::Type, QContactJsonDbStr::guidDefinitionName()); - contactNameFieldsMapping.insert(QContactName::FieldFirstName, QContactJsonDbStr::nameFieldFirstName()); - contactNameFieldsMapping.insert(QContactName::FieldLastName, QContactJsonDbStr::nameFieldLastName()); - contactNameFieldsMapping.insert(QContactName::FieldMiddleName, QContactJsonDbStr::nameFieldMiddleName()); - contactNameFieldsMapping.insert(QContactName::FieldPrefix, QContactJsonDbStr::nameFieldPrefix()); - contactNameFieldsMapping.insert(QContactName::FieldSuffix, QContactJsonDbStr::nameFieldSuffix()); - addressFieldsMapping.insert(QContactAddress::FieldCountry, QContactJsonDbStr::addressFieldCountry()); - addressFieldsMapping.insert(QContactAddress::FieldRegion, QContactJsonDbStr::addressFieldRegion()); - addressFieldsMapping.insert(QContactAddress::FieldLocality, QContactJsonDbStr::addressFieldLocality()); - addressFieldsMapping.insert(QContactAddress::FieldPostcode, QContactJsonDbStr::addressFieldPostcode()); - addressFieldsMapping.insert(QContactAddress::FieldPostOfficeBox, QContactJsonDbStr::addressFieldPostOfficeBox()); - addressFieldsMapping.insert(QContactAddress::FieldStreet, QContactJsonDbStr::addressFieldStreet()); - organizationFieldsMapping.insert(QContactOrganization::FieldName, QContactJsonDbStr::organizationFieldName()); - organizationFieldsMapping.insert(QContactOrganization::FieldDepartment, QContactJsonDbStr::organizationFieldDepartment()); - organizationFieldsMapping.insert(QContactOrganization::FieldTitle, QContactJsonDbStr::organizationFieldTitle()); - organizationFieldsMapping.insert(QContactOrganization::FieldRole, QContactJsonDbStr::organizationFieldRole()); - organizationFieldsMapping.insert(QContactOrganization::FieldAssistantName, QContactJsonDbStr::organizationFieldAssistantName()); - organizationFieldsMapping.insert(QContactOrganization::FieldLogoUrl, QContactJsonDbStr::organizationFieldLogoUrl()); - phoneNumbersSubtypesMapping.insert(QContactPhoneNumber::SubTypeMobile, QContactJsonDbStr::subTypeCell()); - phoneNumbersSubtypesMapping.insert(QContactPhoneNumber::SubTypeFax, QContactJsonDbStr::subTypeFax()); - phoneNumbersSubtypesMapping.insert(QContactPhoneNumber::SubTypeVideo, QContactJsonDbStr::subTypeVideo()); - phoneNumbersSubtypesMapping.insert(QContactPhoneNumber::SubTypeLandline, QContactJsonDbStr::subTypeLandline()); - genderValuesMapping.insert(QContactGender::GenderMale, QContactJsonDbStr::genderMale()); - genderValuesMapping.insert(QContactGender::GenderFemale, QContactJsonDbStr::genderFemale()); - genderValuesMapping.insert(QContactGender::GenderUnspecified, QContactJsonDbStr::genderOther()); - contextsToJsonMapping.insert(QContactDetail::ContextHome, QContactJsonDbStr::contextHome()); - contextsToJsonMapping.insert(QContactDetail::ContextWork, QContactJsonDbStr::contextWork()); - contextsToJsonMapping.insert(QContactDetail::ContextOther, QContactJsonDbStr::contextOther()); - storageLocationMapping.insert(QContactAbstractRequest::UserDataStorage, QContactJsonDbStr::userDataPartition()); - storageLocationMapping.insert(QContactAbstractRequest::SystemStorage, QContactJsonDbStr::systemPartition()); - //TODO: FINISH THE MAPPING(S) - //MISSING DETAILS / FIELDS (TO BE ADDED ALSO TO PARSING LOGIC): - // - QContactTimestamp - // - QContactOnlineAccount -} - -bool QContactJsonDbConverter::toQContacts(const QList<QJsonObject>& jsonObjects, QList<QContact>& convertedContacts, QContactManager::Error& error, const QString &partitionName) -{//TODO: ERROR HANDLING - if (jsonObjects.isEmpty()) { - error = QContactManager::DoesNotExistError; - return false; - } - for (int i = 0; i < jsonObjects.size(); i++) { - QContact contact; - if (this->toQContact(jsonObjects.at(i), &contact, partitionName)) { - convertedContacts.append(contact); - } - } - error = QContactManager::NoError; - return true; -} - -void QContactJsonDbConverter::createMatchFlagQuery(QString& queryString, QContactFilter::MatchFlags flags, const QString& value) const -{ - - // 1)Any flag combined with MatchExactly is a invalid combination this is handled in documentation - - //Assuming other combinations as valid - QString queryWithWildCards; - if (flags.testFlag(QContactFilter::MatchExactly)) - queryWithWildCards = QStringLiteral("=\""); - else - queryWithWildCards = QStringLiteral("=~\"/"); - - if (flags.testFlag(QContactFilter::MatchContains) || flags.testFlag(QContactFilter::MatchEndsWith)) - queryWithWildCards += QStringLiteral("*"); - - queryWithWildCards += value; - - if (flags.testFlag(QContactFilter::MatchContains) || flags.testFlag(QContactFilter::MatchStartsWith)) - queryWithWildCards += QStringLiteral("*"); - - if (!(flags.testFlag(QContactFilter::MatchExactly))) { - queryWithWildCards += QStringLiteral("/w"); - if (!(flags.testFlag(QContactFilter::MatchCaseSensitive))) - queryWithWildCards += QStringLiteral("i"); - } - - if (flags.testFlag(QContactFilter::MatchFixedString)) - queryWithWildCards += QStringLiteral("/"); - - queryWithWildCards.append("\"]"); - queryString.append(queryWithWildCards); -} - -QString QContactJsonDbConverter::toJsonDbDate(const QDateTime& dateAsQDateTime) const -{ - return dateAsQDateTime.toLocalTime().toString("yyyy-MM-dd"); -} - -QDateTime QContactJsonDbConverter::toQDateTime(const QString &jsonDbDate) const -{ - return QDateTime(QDate::fromString(jsonDbDate, Qt::ISODate)); -} - -QContactId QContactJsonDbConverter::jsonDbNotificationObjectToContactId(const QJsonObject &object, QContactAbstractRequest::StorageLocation storageLocation) const -{ - QString jsonUuid = object.value(QContactJsonDbStr::uuid()).toString(); - if (jsonUuid.isEmpty()) - return QContactId(); - else - return QContactId(new QContactJsonDbId(jsonUuid, storageLocation)); -} - -void QContactJsonDbConverter::jsonDbVersionToContactVersion(const QString &jsonDbVersion, QContactVersion *contactVersion) const -{ - QStringList jsonDbVersions = jsonDbVersion.split(QLatin1Char('-')); - if (jsonDbVersions.size() != 2) - return; - int sequenceNumber = jsonDbVersions.at(0).toInt(); - if (sequenceNumber > 0 && jsonDbVersions.at(1).length() == jsonDbVersionLength) { - contactVersion->setSequenceNumber(sequenceNumber); - contactVersion->setExtendedVersion(jsonDbVersions.at(1).toLatin1()); - } -} - -void QContactJsonDbConverter::contactVersionToJsonDbVersion(const QContactVersion &contactVersion, QString *jsonDbVersion) const -{ - int sequenceNumber = contactVersion.sequenceNumber(); - QByteArray extendedVersion = contactVersion.extendedVersion(); - if (sequenceNumber > 0 && extendedVersion.length() == jsonDbVersionLength) { - *jsonDbVersion = QString::number(sequenceNumber) + QStringLiteral("-") + QString::fromLatin1(extendedVersion.constData()); - } -} - -QContactManager::Error QContactJsonDbConverter::jsonDbRequestErrorToContactError(QJsonDbRequest::ErrorCode error) const -{ - switch (error) { - case QJsonDbRequest::NoError: - return QContactManager::NoError; - case QJsonDbRequest::MissingObject: - return QContactManager::DoesNotExistError; - case QJsonDbRequest::MissingType: - case QJsonDbRequest::MissingQuery: - case QJsonDbRequest::InvalidLimit: - return QContactManager::BadArgumentError; - case QJsonDbRequest::InvalidPartition: - return QContactManager::InvalidStorageLocationError; - case QJsonDbRequest::DatabaseConnectionError: - return QContactManager::TimeoutError; - default: - return QContactManager::UnspecifiedError; - } -} - -bool QContactJsonDbConverter::sanitizePhoneNumberString(QString *phoneNumberString) const -{ - if (!phoneNumberString->isEmpty()) { - QString trimmedAndLowerCase = phoneNumberString->trimmed().toLower(); - QString cleaned; - const int len = trimmedAndLowerCase.length(); - if (!len) - return false; - cleaned.reserve(int(len)); - - QString::ConstIterator numberCharsIterator = trimmedAndLowerCase.constBegin(); - //First character can also be equal to '+' - if (isValidPhoneNumberCharacter(numberCharsIterator) || - *numberCharsIterator == '+') - cleaned += *numberCharsIterator; - //Now we sanitize the remaining part of the number string - //by removing all characters that are neither arabic numbers nor - //few more special characters (p, w, a, b, c, d, #, *, (, )) - numberCharsIterator++; - while (numberCharsIterator != trimmedAndLowerCase.constEnd()) { - if (isValidPhoneNumberCharacter(numberCharsIterator)) - cleaned += numberCharsIterator->toLatin1(); - numberCharsIterator++; - } - cleaned.squeeze(); - *phoneNumberString = cleaned; - if ((phoneNumberString->length() >64) || (phoneNumberString->isEmpty())) { - return false; - } else { - return true; - } - } else { - return true; - } -} - -QContactAbstractRequest::StorageLocation QContactJsonDbConverter::partitionNameToStorageLocation( - const QString partitionName) -{ - return storageLocationMapping.key(partitionName); -} - -const QStringList QContactJsonDbConverter::storageLocationsToPartitionNames( - QContactAbstractRequest::StorageLocations storageLocations) -{ - QStringList partitionNames; - - if (QContactAbstractRequest::UserDataStorage & storageLocations) - partitionNames.append(storageLocationMapping[QContactAbstractRequest::UserDataStorage]); - if (QContactAbstractRequest::SystemStorage & storageLocations) - partitionNames.append(storageLocationMapping[QContactAbstractRequest::SystemStorage]); - - return partitionNames; -} - -/*! - Parses the input string to eliminate extra white spaces and enforce maximum length. - */ -QContactJsonDbConverter::SanitizeError QContactJsonDbConverter::sanitizeContactDetailString(QString *stringToBeSanitized, int maxStringLength) const -{ - if (!stringToBeSanitized->isEmpty()) { - // cut leading and trailing white spaces - QString simplified = stringToBeSanitized->simplified(); - QString cleaned; - const int len = simplified.length(); - if (!len) - return EmptyArgumentError; // The string is empty after being simplified, return error - cleaned.reserve(int(len)); - QString::ConstIterator numberCharsIterator = simplified.constBegin(); - while (numberCharsIterator != simplified.constEnd()) { - cleaned += numberCharsIterator->toLatin1(); - numberCharsIterator++; - } - cleaned.squeeze(); - *stringToBeSanitized = cleaned; - if ((stringToBeSanitized->length() > maxStringLength) || (stringToBeSanitized->isEmpty())) { - qWarning() << Q_FUNC_INFO <<"The string is either empty or too long. The maximum length allowed is " << maxStringLength; - return InvalidArgumentError; // String too long, return error - } else { - return NoError; // No error - } - } else { - return EmptyArgumentError; // The string passed as argument was empty in the first place - } -} - -QT_END_NAMESPACE_CONTACTS diff --git a/src/plugins/contacts/jsondb/qcontactjsondbconverter.h b/src/plugins/contacts/jsondb/qcontactjsondbconverter.h deleted file mode 100644 index 88ebb404e..000000000 --- a/src/plugins/contacts/jsondb/qcontactjsondbconverter.h +++ /dev/null @@ -1,114 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtContacts module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QCONTACTJSONDBCONVERTER_H -#define QCONTACTJSONDBCONVERTER_H - -#include <QtCore/qhash.h> - -#include <QtJsonDb/qjsondbrequest.h> - -#include <QtContacts/qcontact.h> -#include <QtContacts/qcontactabstractrequest.h> -#include <QtContacts/qcontactfilter.h> - -#include "qcontactjsondbengine.h" - -QT_USE_NAMESPACE_JSONDB - -QT_BEGIN_NAMESPACE_CONTACTS - -class QContactJsonDbConverter -{ -public: - enum SanitizeError { - NoError = 0x0000, - EmptyArgumentError = 0x0001, - InvalidArgumentError = 0x0002 - }; - QContactJsonDbConverter(); - ~QContactJsonDbConverter(); - QContactManager::Error jsonDbRequestErrorToContactError(QJsonDbRequest::ErrorCode error) const; - bool toQContact(const QJsonObject& object, QContact* contact, const QString &partitionName); - bool toQContacts(const QList<QJsonObject> &jsonObjects, QList<QContact>& convertedContacts, QContactManager::Error& error, const QString &partitionName); - bool toJsonContact(QJsonObject* object, const QContact& contact, const QList<QContactDetail::DetailType> &detailMask = QList<QContactDetail::DetailType>()); - bool updateContexts(const QJsonObject& object, QContactDetail* detail); - bool updateContexts(const QContactDetail& detail, QJsonObject* object); - bool queryFromRequest(QContactAbstractRequest* request,QString &jsonDbQueryStr); - bool singleFilterToJsondbQuery(const QContactFilter& filter,QString &jsonDbQueryStr) const; - bool compoundFilterToJsondbQuery(const QContactFilter &filter, QString &jsonDbQueryStr) const; - QString convertSortOrder(const QList<QContactSortOrder>& sortOrders) const; - QContactId jsonDbNotificationObjectToContactId(const QJsonObject &object, QContactAbstractRequest::StorageLocation storageLocation) const; - QString contactIdToUuid(const QContactId &id) const; - QContactId uuidtoContactId(QString &uuid, const QString &partitionName) const; - void jsonDbVersionToContactVersion(const QString &jsonDbVersion, QContactVersion *contactVersion) const; - void contactVersionToJsonDbVersion(const QContactVersion &contactVersion, QString *jsonDbVersion) const; - bool sanitizePhoneNumberString(QString *phoneNumberString) const; - const QStringList storageLocationsToPartitionNames(QContactAbstractRequest::StorageLocations storageLocations); - QContactAbstractRequest::StorageLocation partitionNameToStorageLocation(const QString partitionName); - SanitizeError sanitizeContactDetailString(QString *stringToBeSanitized, int maxStringLength = 50) const; - -private: - void initializeMappings(); - void createMatchFlagQuery(QString& queryString, QContactFilter::MatchFlags flags, const QString& value) const; - QString toJsonDbDate(const QDateTime& dateAsQDateTime) const; - QDateTime toQDateTime(const QString& jsonDbDate) const; - bool idFilterToJsondbQuery(const QContactFilter &filter, QString &jsonDbQueryStr) const; - bool detailFilterToJsondbQuery(const QContactFilter &filter, QString &jsonDbQueryStr) const; - void idsToJsondbQuery(const QList<QContactId> &ids, QString &newJsonDbQuery) const; - - static bool isValidPhoneNumberCharacter (const QChar *character); - - static const int jsonDbVersionLength; - - QHash<QContactDetail::DetailType, QString> detailsToJsonMapping; - QHash<int, QString> contactNameFieldsMapping; - QHash<QContactOrganization::OrganizationField, QString> organizationFieldsMapping; - QHash<QContactAddress::AddressField, QString> addressFieldsMapping; - QHash<int, QString> phoneNumbersSubtypesMapping; - QHash<int, QString> genderValuesMapping; - QHash<QContactDetail::DetailContext, QString> contextsToJsonMapping; - QHash<QContactAbstractRequest::StorageLocation, QString> storageLocationMapping; -}; - -QT_END_NAMESPACE_CONTACTS - -#endif // QCONTACTJSONDBCONVERTER_H diff --git a/src/plugins/contacts/jsondb/qcontactjsondbengine.cpp b/src/plugins/contacts/jsondb/qcontactjsondbengine.cpp deleted file mode 100644 index ef5f482a0..000000000 --- a/src/plugins/contacts/jsondb/qcontactjsondbengine.cpp +++ /dev/null @@ -1,468 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtContacts module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qcontactjsondbengine.h" - -#include <QtCore/qdebug.h> -#include <QtCore/qeventloop.h> -#include <QtCore/qthread.h> - -#include "qcontactjsondbconverter.h" -#include "qcontactjsondbglobal.h" -#include "qcontactjsondbstring.h" -#include "qcontactjsondbrequesthandler.h" - -QT_BEGIN_NAMESPACE_CONTACTS - -/* - class QContactJsonDbEngine - \brief The QContactJsonDbEngine class provides an implementation of - QContactManagerEngine whose functions always return an error. - - The JsonDb engine. - */ - -QContactJsonDbEngine::QContactJsonDbEngine(const QMap<QString, QString>& parameters) -{ - Q_UNUSED(parameters); - m_requestHandler = new QContactJsonDbRequestHandler(); - qRegisterMetaType<QContactAbstractRequest::State>("QContactAbstractRequest::State"); - qRegisterMetaType<QList<QContactId> >("QList<QContactId>"); - qRegisterMetaType<QContactId>("QContactId"); - m_thread = new QThread(); - m_thread->start(); - connect(this, SIGNAL(requestReceived(QContactAbstractRequest*)), - m_requestHandler, SLOT(handleRequest(QContactAbstractRequest*))); - m_requestHandler->moveToThread(m_thread); - QMetaObject::invokeMethod(m_requestHandler,"init",Qt::BlockingQueuedConnection); - m_requestHandler->setEngine(this); -} - - - - - -QContactJsonDbEngine::~QContactJsonDbEngine() -{ - if (m_requestHandler) - m_requestHandler->deleteLater(); - if (m_thread) { - m_thread->quit(); - m_thread->wait(); - delete m_thread; - } - -} - - - - - - -bool QContactJsonDbEngine::startRequest(QContactAbstractRequest* req){ - QContactManagerEngine::updateRequestState(req, QContactAbstractRequest::ActiveState); - connect(req, SIGNAL(destroyed(QObject*)), m_requestHandler, SLOT(removeDestroyed(QObject*)),Qt::QueuedConnection); - emit requestReceived(req); - return true; -} - - - - - -/* \reimp */ -QString QContactJsonDbEngine::managerName() const -{ - return QContactJsonDbStr::contactJsonDbEngineName(); -} - -QList<QContactDetail::DetailType> QContactJsonDbEngine::supportedContactDetailTypes() const -{ - QList<QContactDetail::DetailType> supportedDetails; - supportedDetails << QContactAddress::Type - << QContactAvatar::Type - << QContactBirthday::Type - << QContactDisplayLabel::Type - << QContactEmailAddress::Type - << QContactExtendedDetail::Type - << QContactGender::Type - << QContactGuid::Type - << QContactName::Type - << QContactNickname::Type - << QContactNote::Type - << QContactOrganization::Type - << QContactPhoneNumber::Type - << QContactRingtone::Type - << QContactSyncTarget::Type - << QContactType::Type - << QContactUrl::Type - << QContactVersion::Type; - return supportedDetails; -} - - - -bool QContactJsonDbEngine::validateContact(const QContact& contact, QContactManager::Error* error) const -{ - QContactManagerEngine::validateContact(contact, error); - if ((*error == QContactManager::InvalidContactTypeError) || (*error == QContactManager::DoesNotExistError)) - return false; - - QList<QContactDetail> contactDetailList = contact.details(); - - for (int i=0; i<contactDetailList.count(); i++) - { - QContactDetail currentDetail = contactDetailList.value(i); - if (!supportedContactDetailTypes().contains(currentDetail.type())) - { - *error = QContactManager::InvalidDetailError; - return false; - } - } - - *error = QContactManager::NoError; - return true; -} - - -QContactId QContactJsonDbEngine::selfContactId(QContactManager::Error* error) const -{ - // TODO: THE IDENTIFICATION FIELD DOES NOT EXIST YET IN JSON SCHEMA! - // Just return "NotSupported" error - *error = QContactManager::NotSupportedError; - return QContactId(); -} - - -QList<QContactId> QContactJsonDbEngine::contactIds(const QContactFilter& filter, const QList<QContactSortOrder>& sortOrders, QContactManager::Error* error) const -{ - QContactJsonDbConverter converter; - QList<QContactId> contactIds; - QVariantMap map; - QContactFetchRequest request; - request.setFilter(filter); - request.setSorting(sortOrders); - *error = QContactManager::NoError; - //QString query = converter.queryFromRequest(&request); - doSyncRequest(&request, 5000); - *error = request.error(); - if (*error != QContactManager::NoError) { - if (qt_debug_jsondb_contacts()) - qDebug() << "[QContactJsonDb] Error at " << Q_FUNC_INFO << ":" << *error; - return QList<QContactId>(); - } - QList<QContact> queryResults = (QList<QContact>)request.contacts(); - // found any results? - if(queryResults.size() == 0) { - *error = QContactManager::DoesNotExistError; - qDebug() << "Error by function contactIds: no contacts found (DoesNotExistError)"; - return QList<QContactId>(); - } - // Convert results for needed format - QList<QContactId> results; - - foreach (const QContact &contact, queryResults) - results.append(contact.id()); - - return results; -} - - - - - -QList<QContact> QContactJsonDbEngine::contacts(const QContactFilter & filter, const QList<QContactSortOrder> & sortOrders, const QContactFetchHint & fetchHint, QContactManager::Error* error ) const -{ - // TODO: ERROR HANDLING (?) - QList<QContact> contacts; - QContactJsonDbConverter converter; - QContactFetchRequest fetchReq; - fetchReq.setFilter(filter); - fetchReq.setSorting(sortOrders); - fetchReq.setFetchHint(fetchHint); - *error = QContactManager::NoError; - //QString query = converter.queryFromRequest(&fetchReq); - doSyncRequest(&fetchReq, 5000); - *error = fetchReq.error(); - if (*error != QContactManager::NoError) { - if (qt_debug_jsondb_contacts()) - qDebug() << "[QContactJsonDb] Error at " << Q_FUNC_INFO << ":" << *error; - return QList<QContact>(); - } - QList<QContact> queryResults = (QList<QContact>)fetchReq.contacts(); - // found any results? - if(queryResults.size() == 0) { - *error = QContactManager::DoesNotExistError; - qDebug() << "Error by function contacts: no contacts found (DoesNotExistError)"; - return QList<QContact>(); - } - /* - else { - converter.toQContacts(jsonDbObjectList, contacts, *this, *error); - } - */ - return queryResults; -} - - - - -QContact QContactJsonDbEngine::contact(const QContactId& contactId, const QContactFetchHint& fetchHint, QContactManager::Error* error) const -{ - QContact contact; - QContactJsonDbConverter converter; - QContactFetchRequest request; - QList<QContactId> filterIds; - QContactIdFilter idFilter; - QString query; - QVariantList results; - - filterIds.append(contactId); - idFilter.setIds(filterIds); - request.setFilter(idFilter); - request.setFetchHint(fetchHint); - *error = QContactManager::NoError; - - //query = converter.queryFromRequest(&request); - doSyncRequest(&request, 5000); - *error = request.error(); - if (*error != QContactManager::NoError) { - if (qt_debug_jsondb_contacts()) - qDebug() << "[QContactJsonDb] Error at " << Q_FUNC_INFO << ":" << *error; - return QContact(); - } - QList<QContact> queryResults = (QList<QContact>)request.contacts(); - // Check if query returned a value and it can be converted - if(queryResults.size() == 0) { - *error = QContactManager::DoesNotExistError; - qDebug() << "Error by function contact: no contact found (DoesNotExistError)"; - return QContact(); - } - - // Extract the desired results - foreach (QContact curr, queryResults) { - if (curr.id() == contactId) contact = curr; ; - } - return contact; -} - - - - -bool QContactJsonDbEngine::saveContacts(QList<QContact>* contacts, QMap<int, QContactManager::Error>* errorMap, QContactManager::Error* error) -{ - QContactSaveRequest saveReq; - - saveReq.setContacts(*contacts); - doSyncRequest(&saveReq, 5000); - *error = saveReq.error(); - if (*error != QContactManager::NoError) { - if (qt_debug_jsondb_contacts()) - qDebug() << "[QContactJsonDb] Error at " << Q_FUNC_INFO << ":" << *error; - } - - for (int i = 0; i < saveReq.contacts().size(); i++) - contacts->replace(i, saveReq.contacts()[i]); - *errorMap = saveReq.errorMap(); - return *error == QContactManager::NoError; // No problem detected, return NoError -} - - - - - -bool QContactJsonDbEngine::removeContacts(const QList<QContactId>& ids, QMap<int, QContactManager::Error>* errorMap, QContactManager::Error* error) -{ - QContactRemoveRequest removeReq; - removeReq.setContactIds(ids); - doSyncRequest(&removeReq, 5000); - *error = removeReq.error(); - *errorMap = removeReq.errorMap(); - if (*error != QContactManager::NoError) { - qWarning() << "Error at function removeContacts:" << *error; - return false; - } else { - return true; - } -} - -bool QContactJsonDbEngine::saveContact(QContact* contact, QContactManager::Error* error) -{ - QContactSaveRequest saveReq; - *error = QContactManager::NoError; - - saveReq.setContact(*contact); - doSyncRequest(&saveReq, 5000); - *error = saveReq.error(); - if (*error != QContactManager::NoError) { - if (qt_debug_jsondb_contacts()) - qDebug() << "[QContactJsonDb] Error at " << Q_FUNC_INFO << ":" << *error; - return false; - } - *contact = saveReq.contacts().first(); // Check if this is the desired behavior !!! - return *error == QContactManager::NoError; // No problem detected, return NoError -} - - - -bool QContactJsonDbEngine::removeContact(const QContactId& contactId, QContactManager::Error* error) -{ - Q_UNUSED(contactId) - Q_UNUSED(error) - - QContactRemoveRequest removeReq; - *error = QContactManager::NoError; - removeReq.setContactId(contactId); - doSyncRequest(&removeReq, 5000); - *error = removeReq.error(); - if (*error != QContactManager::NoError) { - if (qt_debug_jsondb_contacts()) - qDebug() << "[QContactJsonDb] Error at " << Q_FUNC_INFO << ":" << *error; - return false; - } - else return true; -} - -bool QContactJsonDbEngine::isFilterSupported(const QContactFilter& filter) const -{ - switch (filter.type()) { - case QContactFilter::ContactDetailFilter: { - QContactDetailFilter detailFilter = static_cast<QContactDetailFilter>(filter); - int field = detailFilter.detailField(); - if (field < 0) - return false; - switch (detailFilter.detailType()) { - case QContactDetail::TypeEmailAddress: - if (field != QContactEmailAddress::FieldEmailAddress) - return false; - case QContactDetail::TypePhoneNumber: - if (field != QContactPhoneNumber::FieldNumber) - return false; - case QContactDetail::TypeUrl: - if (field != QContactUrl::FieldUrl) - return false; - case QContactDetail::TypeName: - return true; - default: - return false; - }; - return false; - } - case QContactFilter::InvalidFilter: - case QContactFilter::DefaultFilter: - case QContactFilter::IdFilter: - case QContactFilter::IntersectionFilter: - return true; - default: - return false; - } -} - -QList<QVariant::Type> QContactJsonDbEngine::supportedDataTypes() const { - QList<QVariant::Type> st; - st.append(QVariant::String); - st.append(QVariant::Int); - st.append(QVariant::UInt); - st.append(QVariant::Double); - st.append(QVariant::Date); - st.append(QVariant::DateTime); - st.append(QVariant::Bool); - st.append(QVariant::Url); - return st; -} - -void QContactJsonDbEngine::requestDestroyed(QContactAbstractRequest* req){ - //We inform the handler that this request is about to be destroyed so as to - //avoid that the worker handler thread will start handling request objects during - //their destruction. - QMetaObject::invokeMethod(m_requestHandler,"removeDestroyed",Qt::BlockingQueuedConnection,Q_ARG(QObject*, req)); - return QContactManagerEngine::requestDestroyed(req); -} - -bool QContactJsonDbEngine::cancelRequest(QContactAbstractRequest* req){ - /* - TODO - - Cancel an in progress async request. If not possible, return false from here. - */ - return QContactManagerEngine::cancelRequest(req); -} - -bool QContactJsonDbEngine::waitForRequestProgress(QContactAbstractRequest* req, int msecs){ - Q_UNUSED(msecs); - Q_UNUSED(req); - //TODO: can we get progress info from jsondb?? - - return true; -} - -bool QContactJsonDbEngine::waitForRequestFinished(QContactAbstractRequest* req, int msecs){ - bool result = false; - result = m_requestHandler->waitForRequestFinished(req, msecs); - return result; -} - -bool QContactJsonDbEngine::doSyncRequest(QContactAbstractRequest* req, int msecs) const { - Q_UNUSED(msecs); // TODO - //if (req->ContactFetchRequest) - const_cast<QContactJsonDbEngine*>(this)->startRequest(req); - const_cast<QContactJsonDbEngine*>(this)->waitForRequestFinished(req, 0); - //if (req->FinishedState) - if (req->isFinished() == true) - return true; - else - return false; -} - - -/* Internal, for debugging */ -bool qt_debug_jsondb_contacts() -{ - static int debug_env = -1; - if (debug_env == -1) - debug_env = QT_PREPEND_NAMESPACE(qgetenv)("QT_DEBUG_JSONDB_CONTACTS").toInt(); - - return debug_env != 0; -} - -#include "moc_qcontactjsondbengine.cpp" - -QT_END_NAMESPACE_CONTACTS diff --git a/src/plugins/contacts/jsondb/qcontactjsondbengine.h b/src/plugins/contacts/jsondb/qcontactjsondbengine.h deleted file mode 100644 index e36ea7182..000000000 --- a/src/plugins/contacts/jsondb/qcontactjsondbengine.h +++ /dev/null @@ -1,127 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtContacts module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QCONTACTJSONDBENGINE_H -#define QCONTACTJSONDBENGINE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/qlist.h> -#include <QtCore/qmap.h> -#include <QtCore/qqueue.h> -#include <QtCore/qvariant.h> - -#include <QtContacts/qcontacts.h> -#include <QtContacts/qcontactmanager.h> -#include <QtContacts/private/qcontactmanager_p.h> - -#include "qcontactjsondbstring.h" - -QT_FORWARD_DECLARE_CLASS(QThread) - -QT_BEGIN_NAMESPACE_CONTACTS - -class QContactJsonDbRequestHandler; - -class QContactJsonDbEngine : public QContactManagerEngine -{ - Q_OBJECT - -public: - ~QContactJsonDbEngine(); - QContactJsonDbEngine(const QMap<QString, QString> ¶meters = (QMap<QString, QString>())); - - QString managerName() const; - bool validateContact(const QContact&, QContactManager::Error* error) const; - - /* "Self" contact id (MyCard) */ - QContactId selfContactId(QContactManager::Error* errors) const; - - /* Filtering */ - QList<QContactId> contactIds(const QContactFilter& filter, const QList<QContactSortOrder>& sortOrders, QContactManager::Error* error) const; - - /* Contacts - Accessors and Mutators */ - QContact contact(const QContactId& contactId, const QContactFetchHint& fetchHint, QContactManager::Error* error) const; - QList<QContact> contacts(const QContactFilter& filter, const QList<QContactSortOrder>& sortOrders, const QContactFetchHint& fetchHint, QContactManager::Error* error ) const; - bool saveContact(QContact* contact, QContactManager::Error* error); - bool removeContact(const QContactId& contactId, QContactManager::Error* error); - bool saveContacts(QList<QContact>*, QMap<int, QContactManager::Error>*, QContactManager::Error* error); // implemented in terms of the singular saveContact - bool removeContacts(const QList<QContactId>&, QMap<int, QContactManager::Error>*, QContactManager::Error* error); // implemented in terms of the singular removeContact - - /* Version Reporting */ - int implementationVersion() const { return QContactJsonDbStr::ContactJsonDbEngineVersion; } - int managerVersion() const { return QContactJsonDbStr::ContactJsonDbEngineVersion; } - - bool isFilterSupported(const QContactFilter& filter) const; - QList<QVariant::Type> supportedDataTypes() const; - QList<QContactType::TypeValues> supportedContactTypes() const {return (QList<QContactType::TypeValues> () << QContactType::TypeContact);} - QList<QContactDetail::DetailType> supportedContactDetailTypes() const; - - /* Asynchronous Request Support - synchronous versions until thread worker is stable */ - void requestDestroyed(QContactAbstractRequest *req); - bool startRequest(QContactAbstractRequest *req); - bool cancelRequest(QContactAbstractRequest *req); - bool waitForRequestProgress(QContactAbstractRequest* req, int msecs); - bool waitForRequestFinished(QContactAbstractRequest* req, int msecs); - signals: - void requestReceived(QContactAbstractRequest* req); - private: - bool doSyncRequest(QContactAbstractRequest* req, int msecs) const; - - Q_DISABLE_COPY(QContactJsonDbEngine); - - QQueue<QContactAbstractRequest*> m_asynchronousOperations; // async requests to be performed. - QContactJsonDbRequestHandler *m_requestHandler; - QThread* m_thread; -}; - -QT_END_NAMESPACE_CONTACTS - -#endif // QCONTACTJSONDBENGINE_H diff --git a/src/plugins/contacts/jsondb/qcontactjsondbenginefactory.cpp b/src/plugins/contacts/jsondb/qcontactjsondbenginefactory.cpp deleted file mode 100644 index 48b8d639b..000000000 --- a/src/plugins/contacts/jsondb/qcontactjsondbenginefactory.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtContacts module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qcontactjsondbengine.h" - -#include "qcontactjsondbenginefactory.h" -#include "qcontactjsondbid.h" - -QT_BEGIN_NAMESPACE_CONTACTS - -QContactJsonDbEngineFactory::QContactJsonDbEngineFactory() -{ -} - - -QContactManagerEngine* QContactJsonDbEngineFactory::engine(const QMap<QString, QString>& parameters, QContactManager::Error* error) -{ - Q_UNUSED(error); - - return new QContactJsonDbEngine(parameters); //Manager engine will take ownership of this object. -} - - -QContactEngineId *QContactJsonDbEngineFactory::createContactEngineId(const QMap<QString, QString> ¶meters, const QString &engineIdString) const -{ - Q_UNUSED(parameters) - return new QContactJsonDbId(engineIdString); -} - -QString QContactJsonDbEngineFactory::managerName() const -{ - return QContactJsonDbStr::contactJsonDbEngineName(); -} - -#include "moc_qcontactjsondbenginefactory.cpp" - -QT_END_NAMESPACE_CONTACTS diff --git a/src/plugins/contacts/jsondb/qcontactjsondbenginefactory.h b/src/plugins/contacts/jsondb/qcontactjsondbenginefactory.h deleted file mode 100644 index 1c26a79bf..000000000 --- a/src/plugins/contacts/jsondb/qcontactjsondbenginefactory.h +++ /dev/null @@ -1,78 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtContacts module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QCONTACTJSONDBENGINEFACTORY_H -#define QCONTACTJSONDBENGINEFACTORY_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtContacts/qcontactengineid.h> -#include <QtContacts/qcontactmanager.h> -#include <QtContacts/qcontactmanagerenginefactory.h> - -QT_BEGIN_NAMESPACE_CONTACTS - -class Q_DECL_EXPORT QContactJsonDbEngineFactory : public QContactManagerEngineFactory -{ - Q_OBJECT - Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QContactManagerEngineFactoryInterface" FILE "jsondb.json") - public: - QContactJsonDbEngineFactory(); - QContactManagerEngine* engine(const QMap<QString, QString>& parameters, QContactManager::Error*); - QString managerName() const; - QContactEngineId *createContactEngineId(const QMap<QString, QString> ¶meters, const QString &engineIdString) const; - - private: - Q_DISABLE_COPY(QContactJsonDbEngineFactory) -}; - -QT_END_NAMESPACE_CONTACTS - -#endif // QCONTACTJSONDBENGINEFACTORY_H diff --git a/src/plugins/contacts/jsondb/qcontactjsondbglobal.h b/src/plugins/contacts/jsondb/qcontactjsondbglobal.h deleted file mode 100644 index 5b8c98214..000000000 --- a/src/plugins/contacts/jsondb/qcontactjsondbglobal.h +++ /dev/null @@ -1,51 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtContacts module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QCONTACTJSONDBGLOBAL_H -#define QCONTACTJSONDBGLOBAL_H - -QT_BEGIN_NAMESPACE_CONTACTS - -bool qt_debug_jsondb_contacts(); - -QT_END_NAMESPACE_CONTACTS - -#endif // QCONTACTJSONDBGLOBAL_H diff --git a/src/plugins/contacts/jsondb/qcontactjsondbid.cpp b/src/plugins/contacts/jsondb/qcontactjsondbid.cpp deleted file mode 100644 index f97d5e560..000000000 --- a/src/plugins/contacts/jsondb/qcontactjsondbid.cpp +++ /dev/null @@ -1,154 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Pim module. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qcontactjsondbid.h" - -#ifndef QT_NO_DEBUG_STREAM -#include <QtCore/qdebug.h> -#endif - -#include "qcontactjsondbstring.h" - -QT_BEGIN_NAMESPACE_CONTACTS - -QContactJsonDbId::QContactJsonDbId(const QString &engineId) -{ - QStringList splitEngineId = engineId.split("/"); - if (splitEngineId.size() == 2) { - m_uuid = splitEngineId.last(); - m_storageLocation = QContactAbstractRequest::StorageLocation( - splitEngineId.first().toInt()); - } -} - -QContactJsonDbId::QContactJsonDbId(const QContactJsonDbId &other) - : m_uuid(other.m_uuid), - m_storageLocation(other.m_storageLocation) -{ -} - -QContactJsonDbId::QContactJsonDbId(const QUuid &uuid, const QContactAbstractRequest::StorageLocation &storageLocation) - : m_uuid(uuid), - m_storageLocation(storageLocation) -{ -} - -QContactJsonDbId::~QContactJsonDbId() -{ -} - -bool QContactJsonDbId::isEqualTo(const QContactEngineId *other) const -{ - const QContactJsonDbId *otherJsonDbId = static_cast<const QContactJsonDbId *>(other); - QUuid otherUuid = otherJsonDbId->m_uuid; - QContactAbstractRequest::StorageLocation otherStorageLocation = otherJsonDbId->m_storageLocation; - return ((m_uuid == otherUuid) && (m_storageLocation == otherStorageLocation)); -} - -bool QContactJsonDbId::isLessThan(const QContactEngineId *other) const -{ - const QContactJsonDbId *otherJsonDbId = static_cast<const QContactJsonDbId *>(other); - QUuid otherUuid = otherJsonDbId->m_uuid; - QContactAbstractRequest::StorageLocation otherStorageLocation = otherJsonDbId->m_storageLocation; - return ((m_storageLocation < otherStorageLocation) || - ((m_storageLocation == otherStorageLocation) && (m_uuid < otherUuid))); -} - -QString QContactJsonDbId::managerUri() const -{ - return QContactJsonDbStr::managerUri(); -} - -QContactEngineId *QContactJsonDbId::clone() const -{ - return new QContactJsonDbId(m_uuid, m_storageLocation); -} - -#ifndef QT_NO_DEBUG_STREAM -QDebug &QContactJsonDbId::debugStreamOut(QDebug &dbg) const -{ - dbg.nospace() << "QContactJsonDbId(" << this->toString() << ")"; - return dbg.maybeSpace(); -} -#endif - -QString QContactJsonDbId::toString() const -{ - QString stringifiedIdFormat("%1/%2"); - return stringifiedIdFormat.arg(QString::number(m_storageLocation)).arg(m_uuid.toString()); -} - -uint QContactJsonDbId::hash() const -{ - /* - TODO - - Provide a hash function for your engine-specific id. - Note that the hash doesn't strictly need to be unique, since isEqualTo() - ensures that individual id's in a single hash-bucket can be uniquely - determined; however a better hash function will result in better performance - because the ids will be distributed more randomly in a hash table. - - In the example implementation below, we could simply return the id, since the - id is a quint32. In more complex id classes, however, you may need to - qHash() individual data members and combine the results somehow. - */ - - return QT_PREPEND_NAMESPACE(qHash)(this->toString()); -} - -/*! - * Returns the jsondb uuid of the contact - */ -QUuid QContactJsonDbId::uuid() const -{ - return m_uuid; -} - -/*! - * Returns the storage location where the contact is stored in - */ -QContactAbstractRequest::StorageLocation QContactJsonDbId::storageLocation() const -{ - return m_storageLocation; -} - -QT_END_NAMESPACE_CONTACTS diff --git a/src/plugins/contacts/jsondb/qcontactjsondbid.h b/src/plugins/contacts/jsondb/qcontactjsondbid.h deleted file mode 100644 index 14032e9c4..000000000 --- a/src/plugins/contacts/jsondb/qcontactjsondbid.h +++ /dev/null @@ -1,97 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Pim Module -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QCONTACTJSONDBID_H -#define QCONTACTJSONDBID_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/quuid.h> - -#include <QtContacts/qcontactabstractrequest.h> -#include <QtContacts/qcontactengineid.h> -#include <QtContacts/qcontactid.h> - -QT_BEGIN_NAMESPACE_CONTACTS - -class QContactJsonDbId : public QContactEngineId -{ -public: - explicit QContactJsonDbId(const QString &engineId); - QContactJsonDbId(const QUuid &uuid, const QContactAbstractRequest::StorageLocation &storageLocation); - QContactJsonDbId(const QContactJsonDbId &other); - ~QContactJsonDbId(); - - bool isEqualTo(const QContactEngineId *other) const; - bool isLessThan(const QContactEngineId *other) const; - - QString managerUri() const; - - QContactEngineId *clone() const; - - QString toString() const; - -#ifndef QT_NO_DEBUG_STREAM - QDebug &debugStreamOut(QDebug &dbg) const; -#endif - - uint hash() const; - - QUuid uuid() const; - QContactAbstractRequest::StorageLocation storageLocation() const; - -private: - QUuid m_uuid; - QContactAbstractRequest::StorageLocation m_storageLocation; -}; - -QT_END_NAMESPACE_CONTACTS - -#endif // QCONTACTJSONDBID_H diff --git a/src/plugins/contacts/jsondb/qcontactjsondbrequesthandler.cpp b/src/plugins/contacts/jsondb/qcontactjsondbrequesthandler.cpp deleted file mode 100644 index da35e70a3..000000000 --- a/src/plugins/contacts/jsondb/qcontactjsondbrequesthandler.cpp +++ /dev/null @@ -1,1090 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtContacts module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qcontactjsondbrequesthandler.h" - -#include <QtCore/qcoreapplication.h> -#include <QtCore/qdebug.h> -#include <QtCore/qtimer.h> - -#include <QtJsonDb/qjsondbreadrequest.h> -#include <QtJsonDb/qjsondbwriterequest.h> - -#include <QtContacts/qcontact.h> - -#include "qcontactjsondbconverter.h" -#include "qcontactjsondbengine.h" -#include "qcontactjsondbglobal.h" -#include "qcontactjsondbid.h" -#include "qcontactjsondbrequestmanager.h" -#include "qcontactjsondbstring.h" - -QT_BEGIN_NAMESPACE_CONTACTS - -const int QContactJsonDbRequestHandler::TIMEOUT_INTERVAL(100); - -QContactJsonDbRequestHandler::QContactJsonDbRequestHandler() - : m_engine(0), m_jsonDbConnection(0), m_timer(0) -{ -} - -QContactJsonDbRequestHandler::~QContactJsonDbRequestHandler() -{ - delete m_timer; - delete m_reqStateMutex; - delete m_converter; - delete m_requestMgr; - m_jsonDbConnection->deleteLater(); -} - -void QContactJsonDbRequestHandler::init() -{ - m_reqStateMutex = new QMutex(); - m_requestMgr = new QContactJsonDbRequestManager(); - m_converter = new QContactJsonDbConverter(); - m_jsonDbConnection = new QJsonDbConnection(this); - connect(m_jsonDbConnection, SIGNAL(error(QtJsonDb::QJsonDbConnection::ErrorCode,QString)), - this, SLOT(onJsonDbConnectionError(QtJsonDb::QJsonDbConnection::ErrorCode,QString))); - m_jsonDbConnection->connectToServer(); - Q_ASSERT(storageLocationToPartition(QContactAbstractRequest::UserDataStorage) != - storageLocationToPartition(QContactAbstractRequest::SystemStorage)); - createWatcherForStorageLocation(QContactAbstractRequest::UserDataStorage); - createWatcherForStorageLocation(QContactAbstractRequest::SystemStorage); - - // Be optimistic, reduce them later on error. - m_availableStorageLocations = supportedStorageLocations(); -} - -void QContactJsonDbRequestHandler::createWatcherForStorageLocation(QContactAbstractRequest::StorageLocation storageLocation) -{ - QJsonDbWatcher* jsonDbWatcher = new QJsonDbWatcher(this); - jsonDbWatcher->setWatchedActions(QJsonDbWatcher::All); - jsonDbWatcher->setQuery(QContactJsonDbStr::contactsJsonDbNotificationQuery()); - jsonDbWatcher->setPartition(storageLocationToPartition(storageLocation)); - new QContactJsonDbPartitionWatcher(this, jsonDbWatcher, storageLocation); - m_jsonDbConnection->addWatcher(jsonDbWatcher); -} - -void QContactJsonDbRequestHandler::setEngine(QContactJsonDbEngine *engine) -{ - m_engine = engine; -} - -bool QContactJsonDbRequestHandler::waitForRequestFinished(QContactAbstractRequest *req, int msecs) -{ - // This function is called by the QContactJsonDbEngine thread (main thread) - - // TODO: timeout handling - Q_UNUSED(msecs); - - QMutexLocker locker(m_reqStateMutex); - QWaitCondition waitCondition; - - if (req->state() == QContactAbstractRequest::FinishedState) - return true; - else if (req->state() == QContactAbstractRequest::CanceledState) - return false; - - // Request might still be inactive if this function is called immediatelly after sending a signal to - // handleRequest slot. The signal goes to event loop and might be handled later than this function is executed. - bool requestInactive = !m_requestMgr->setWaitCondition(req,&waitCondition); - bool requestFinished; - - if (msecs <= 0) - requestFinished = waitCondition.wait(m_reqStateMutex); - else - requestFinished = waitCondition.wait(m_reqStateMutex, msecs); - - if (requestInactive && !requestFinished) { - // The request was never started or was started but not yet finished - m_requestMgr->removeWaitCondition(req); - } - return requestFinished; -} - -void QContactJsonDbRequestHandler::handleRequest(QContactAbstractRequest *req) -{ - // Detects what kind of request is at hand, updates the state to "active", calls "addRequest" and - // "addRequest" from requestManager, sends resultsAvailable signal - QMutexLocker locker(m_reqStateMutex); - QContactManager::Error error = QContactManager::NoError; - if (m_reqList.contains(req)) { - error = QContactManager::UnspecifiedError; - qWarning() << Q_FUNC_INFO << "Trying to handle destroyed request: throwing ERROR: " << error; - return; - } - switch (req->type()) { - case QContactAbstractRequest::ContactSaveRequest: { - QContactSaveRequest* saveReq = static_cast<QContactSaveRequest*>(req); - handleContactSaveRequest(saveReq); - break; - } - case QContactAbstractRequest::ContactFetchRequest: { - QContactFetchRequest* fetchReq = static_cast<QContactFetchRequest*>(req); - handleContactFetchRequest(fetchReq); - break; - } - case QContactAbstractRequest::ContactFetchByIdRequest: { - QContactFetchByIdRequest* fetchReq = static_cast<QContactFetchByIdRequest*>(req); - handleContactFetchByIdRequest(fetchReq); - break; - } - case QContactAbstractRequest::ContactRemoveRequest: { - QContactRemoveRequest* removeReq = static_cast<QContactRemoveRequest*>(req); - handleContactRemoveRequest(removeReq); - break; - } - case QContactAbstractRequest::ContactIdFetchRequest: { - QContactIdFetchRequest* idReq = static_cast<QContactIdFetchRequest*>(req); - handleContactIdFetchRequest(idReq); - break; - } - default: - break; - } -} - - -void QContactJsonDbRequestHandler::handleContactSaveRequest(QContactSaveRequest* saveReq) { - //TODO: handle duplicates(?) - QList<QContact> contacts = saveReq->contacts(); - QContactManager::Error lastError = QContactManager::NoError; - QMap<int, QContactManager::Error> errorMap; - m_requestMgr->addRequest(saveReq, contacts); - for (int i = 0; i < contacts.size(); i++) { - QContactManager::Error error = QContactManager::NoError; - QContact contact = contacts.at(i); - - const QContactAbstractRequest::StorageLocation storageLocationForTheContact = - contact.id().isNull() ? saveReq->storageLocation() : extractStorageLocation(contact.id()); - const QString partition = storageLocationToPartition(storageLocationForTheContact); - if (partition.isEmpty()) { - error = QContactManager::InvalidStorageLocationError; - errorMap.insert(i,error); - lastError = errorPrecedence(lastError, error); - continue; - } - - if (!m_engine->validateContact(contact, &error)) { - errorMap.insert(i,error); - lastError = errorPrecedence(lastError, error); - // For an invalid contact in addition to reporting error we also clear the contact id. - QContactId contactId; - contact.setId(contactId); - continue; - } - if (!contact.id().isNull()) { - // Update to existing contact with given id. Fetch complete contact data from jsondb before saving. - // This preserves possible extra fields in jsondb contact object. Actual update request is made in - // the response handler for this prefetch request. - QContactIdFilter idFilter; - idFilter.add(contact.id()); - QContactFetchRequest *fetchRequest = new QContactFetchRequest(this); - fetchRequest->setFilter(idFilter); - QString fetchQuery; - bool isValid = m_converter->queryFromRequest(fetchRequest, fetchQuery); - if (isValid) { - m_requestMgr->addRequest(fetchRequest); - m_requestMgr->addPrefetchRequest(fetchRequest, saveReq); - if (!makeJsonDbRequest(fetchRequest, - QContactJsonDbRequestManager::PrefetchForSaveRequest, - i, - partition, - fetchQuery)) { - error = QContactManager::TimeoutError; - errorMap.insert(i,error); - lastError = errorPrecedence( lastError, error); - } - } else { - error = QContactManager::BadArgumentError; - errorMap.insert(i,error); - lastError = errorPrecedence(lastError, error); - } - } else { - // No prefetch needed, just create a new contact. - QJsonObject newJsonDbItem; - if (m_converter->toJsonContact(&newJsonDbItem, contact, saveReq->typeMask())) { - if (!makeJsonDbRequest(saveReq, - QContactJsonDbRequestManager::SaveRequest, - i, - partition, - QString(), - QList<QJsonObject>() << newJsonDbItem)) { - error = QContactManager::TimeoutError; - errorMap.insert(i,error); - lastError = errorPrecedence(lastError, error); - } - } else { - error = QContactManager::BadArgumentError; - errorMap.insert(i,error); - lastError = errorPrecedence(lastError, error); - } - } - } - if (errorMap.size() == contacts.size()) { //None of the contacts could be saved - QWaitCondition* waitCondition = m_requestMgr->waitCondition(saveReq); - m_requestMgr->removeRequest(saveReq); - QContactManagerEngine::updateContactSaveRequest(saveReq, contacts, lastError, errorMap, QContactAbstractRequest::FinishedState); - if (waitCondition) - waitCondition->wakeAll(); - } else { - QContactManagerEngine::updateContactSaveRequest(saveReq, contacts, lastError, errorMap, QContactAbstractRequest::ActiveState); - } -} - -QString QContactJsonDbRequestHandler::storageLocationToPartition(QContactAbstractRequest::StorageLocation storageLocation) -{ - const QStringList partitions = m_converter->storageLocationsToPartitionNames(QContactAbstractRequest::StorageLocations(storageLocation)); - if (partitions.isEmpty()) - return QString(); - else - return partitions.first(); -} - -QContactAbstractRequest::StorageLocations QContactJsonDbRequestHandler::storageLocationsOrDefault( - QContactAbstractRequest::StorageLocations storageLocation) -{ - return storageLocation ? storageLocation : QContactAbstractRequest::UserDataStorage; -} - -QContactAbstractRequest::StorageLocation QContactJsonDbRequestHandler::extractStorageLocation(const QContactId &id) -{ - const QContactEngineId *engineId = QContactManagerEngine::engineId(id); - if (engineId) - return engineId->storageLocation(); - else - return QContactAbstractRequest::StorageLocation(0); -} - -QContactAbstractRequest::StorageLocations QContactJsonDbRequestHandler::extractStorageLocations(const QList<QContactId> &contactIds) -{ - QContactAbstractRequest::StorageLocations storageLocations(0); - foreach (const QContactId &id, contactIds) { - storageLocations |= extractStorageLocation(id); - } - return storageLocations; -} - -void QContactJsonDbRequestHandler::handleContactFetchRequest(QContactFetchRequest* req) { - - QContactManager::Error error = QContactManager::NoError; - QString newJsonDbQuery; - m_requestMgr->addRequest(req); - if (m_converter->queryFromRequest(req, newJsonDbQuery)) { - QContactAbstractRequest::StorageLocations storageLocations = storageLocationsOrDefault(req->storageLocations()); - if (storageLocations & ~m_availableStorageLocations) - error = QContactManager::InvalidStorageLocationError; - QStringList partitions = m_converter->storageLocationsToPartitionNames(storageLocations); - if (!partitions.isEmpty()) { - foreach (const QString &partition, partitions) { - if (!makeJsonDbRequest(req, - QContactJsonDbRequestManager::FetchRequest, - 0, - partition, - newJsonDbQuery)) { - error = errorPrecedence(error, QContactManager::TimeoutError); - break; - } - } - } else { - error = errorPrecedence(error, QContactManager::InvalidStorageLocationError); - } - } else { - error = QContactManager::BadArgumentError; - } - - const QList<QContact> emptyContactList; - if (error != QContactManager::NoError) { - QWaitCondition* waitCondition = m_requestMgr->waitCondition(req); - m_requestMgr->removeRequest(req); - QContactManagerEngine::updateContactFetchRequest(req, - emptyContactList,error,QContactAbstractRequest::FinishedState); - if (waitCondition) - waitCondition->wakeAll(); - } else { - QContactManagerEngine::updateContactFetchRequest(req, emptyContactList, error, - QContactAbstractRequest::ActiveState); - } -} - -void QContactJsonDbRequestHandler::handleContactFetchByIdRequest(QContactFetchByIdRequest* req) { - QContactManager::Error error = QContactManager::NoError; - QMap<int, QContactManager::Error> errorMap; - QList<QContact> emptyContactList; - QString newJsonDbQuery; - m_requestMgr->addRequest(req); - m_converter->queryFromRequest(req, newJsonDbQuery); // Always ok for fetch by id requests as an empty query is also ok. - QContactAbstractRequest::StorageLocations storageLocations = extractStorageLocations(req->contactIds()); - if (storageLocations & ~m_availableStorageLocations) - error = QContactManager::InvalidStorageLocationError; - QStringList partitions = m_converter-> storageLocationsToPartitionNames(storageLocations); - if (!partitions.isEmpty()) { - foreach (const QString &partition, partitions) { - if (!makeJsonDbRequest(req, - QContactJsonDbRequestManager::FetchByIdRequest, - 0, - partition, - newJsonDbQuery)) { - error = errorPrecedence(error, QContactManager::TimeoutError); - break; - } - } - } else { - // None of the ids had valid partition specifie, prepare request with errors and empty contacts. - // Here we keep DoesNotExistError for empty contact ids to keep consistency with memory backend - // and existing test asset for null operations. - for (int index = 0;index < req->contactIds().size();index++) { - emptyContactList << QContact(); - if (req->contactIds().at(index).isNull()) { - errorMap.insert(index, QContactManager::DoesNotExistError); - error = errorPrecedence(error, QContactManager::DoesNotExistError); - } else { - errorMap.insert(index, QContactManager::InvalidStorageLocationError); - error = errorPrecedence(error, QContactManager::InvalidStorageLocationError); - } - } - } - - if (error != QContactManager::NoError) { - QWaitCondition* waitCondition = m_requestMgr->waitCondition(req); - m_requestMgr->removeRequest(req); - QContactManagerEngine::updateContactFetchByIdRequest(req, emptyContactList, error, errorMap, QContactAbstractRequest::FinishedState); - if (waitCondition) - waitCondition->wakeAll(); - } -} - -void QContactJsonDbRequestHandler::handleContactRemoveRequest(QContactRemoveRequest* req) { - QContactManager::Error lastError = QContactManager::NoError; - QMap<int, QContactManager::Error> errorMap; - - QList<QContactId> contactIds = req->contactIds(); - QContactManagerEngine::updateContactRemoveRequest(req, lastError, errorMap, QContactAbstractRequest::ActiveState); - m_requestMgr->addRequest(req); - - for (int i = 0; i < contactIds.size(); i++) { - QContactId contactId = contactIds.at(i); - QContactManager::Error error = QContactManager::NoError; - if ( (!(contactId.isNull())) && (contactId.managerUri() == QContactJsonDbStr::managerUri()) ) { - QContactAbstractRequest::StorageLocation storageLocation = QContactAbstractRequest::StorageLocation(extractStorageLocation(contactId)); - QString partition = storageLocationToPartition(storageLocation); - if ((storageLocation & ~m_availableStorageLocations) || (partition.isEmpty())) { - error = QContactManager::InvalidStorageLocationError; - errorMap.insert(i, error); - lastError = errorPrecedence(lastError, error); - } else { - QJsonObject newJsonDbContact; - newJsonDbContact.insert(QContactJsonDbStr::type(), QContactJsonDbStr::contactsJsonDbType()); - newJsonDbContact.insert(QContactJsonDbStr::uuid(), m_converter->contactIdToUuid(contactId)); - if (!makeJsonDbRequest(req, - QContactJsonDbRequestManager::RemoveRequest, - i, - partition, - QString(), - QList<QJsonObject>() << newJsonDbContact)) { - error = QContactManager::TimeoutError; - errorMap.insert(i,error); - lastError = errorPrecedence(lastError, error); - } - } - } else { - // Set DoesNotExistsError for an id if trying to remove contact with a null - // id or id is belonging to another contact manager engine. - error = QContactManager::DoesNotExistError; - errorMap.insert(i,error); - lastError = errorPrecedence(lastError, error); - } - } - if (errorMap.size() == contactIds.size()) { - //jsondbrequest could not be created at all - //so we remove it from manager and set its state to finished - QWaitCondition* waitCondition = m_requestMgr->waitCondition(req); - m_requestMgr->removeRequest(req); - QContactManagerEngine::updateContactRemoveRequest(req, - lastError,errorMap,QContactAbstractRequest::FinishedState); - if (waitCondition) - waitCondition->wakeAll(); - } else { - QContactManagerEngine::updateContactRemoveRequest(req, lastError, errorMap, QContactAbstractRequest::ActiveState); - } -} - -void QContactJsonDbRequestHandler::handleContactIdFetchRequest(QContactIdFetchRequest *req) -{ - QContactManager::Error error = QContactManager::NoError; - m_requestMgr->addRequest(req); - QString newJsonDbQuery; - if (m_converter->queryFromRequest(req, newJsonDbQuery)) { - QContactAbstractRequest::StorageLocations storageLocations = storageLocationsOrDefault(req->storageLocations()); - if (storageLocations & ~m_availableStorageLocations) - error = QContactManager::InvalidStorageLocationError; - QStringList partitions = m_converter->storageLocationsToPartitionNames(storageLocations); - if (!partitions.isEmpty()) { - foreach (const QString &partition, partitions) { - if (!makeJsonDbRequest(req, - QContactJsonDbRequestManager::ContactIdFetchRequest, - 0, - partition, - newJsonDbQuery)) { - error = errorPrecedence(error, QContactManager::TimeoutError); - break; - } - } - } else { - error = QContactManager::InvalidStorageLocationError; - } - } else { - error = QContactManager::BadArgumentError; - } - - const QList<QContactId> emptyContactIdList; - if (error!=QContactManager::NoError) { - QWaitCondition* waitCondition = m_requestMgr->waitCondition(req); - m_requestMgr->removeRequest(req); - QContactManagerEngine::updateContactIdFetchRequest(req,emptyContactIdList,error, - QContactAbstractRequest::FinishedState); - if (waitCondition) - waitCondition->wakeAll(); - } else { - QContactManagerEngine::updateContactIdFetchRequest(req,emptyContactIdList,error, - QContactAbstractRequest::ActiveState); - } -} - -void QContactJsonDbRequestHandler::onJsonDbWatcherNotificationsAvailable(QJsonDbWatcher *jsonDbWatcher, - QContactAbstractRequest::StorageLocation storageLocation) -{ - // There is no need for mutex locker since we do not access any request from here. - QList<QJsonDbNotification> notifications = jsonDbWatcher->takeNotifications(); - foreach (const QJsonDbNotification ¬ification, notifications) { - QJsonObject jsonDbObject = notification.object(); - QContactId contactId = m_converter->jsonDbNotificationObjectToContactId(jsonDbObject, storageLocation); - switch (notification.action()) { - case QJsonDbWatcher::Created: { - m_ccs.insertAddedContact(contactId); - startTimer(); - break; - } - case QJsonDbWatcher::Updated: { - m_ccs.insertChangedContact(contactId); - startTimer(); - break; - } - case QJsonDbWatcher::Removed: { - m_ccs.insertRemovedContact(contactId); - startTimer(); - break; - } - default: - break; - } - } -} - -void QContactJsonDbRequestHandler::startTimer() -{ - // There is no need for mutex locker since we do not access any request data from here. - - if (!m_timer) { - m_timer = new QTimer(this); - m_timer->setSingleShot(true); - m_timer->setInterval(TIMEOUT_INTERVAL); - connect(m_timer, SIGNAL(timeout()), this, SLOT(onTimeout())); - } - if (!m_timer->isActive()) - m_timer->start(); -} - -void QContactJsonDbRequestHandler::onTimeout() -{ - // There is no need for mutex locker since we do not access any request data from here. - - if (m_engine) { - m_ccs.emitSignals(m_engine); - m_ccs.clearAll(); - } -} - - -void QContactJsonDbRequestHandler::handleResponse(QJsonDbRequest *jsonDbRequest) -{ - QMutexLocker locker(m_reqStateMutex); - - int contactIndex; - QContactJsonDbRequestManager::RequestType requestType; - QString partitionName; - QContactAbstractRequest *req = m_requestMgr->removeRequest(jsonDbRequest, requestType, contactIndex, &partitionName); - - // For recovering from no partitions available state. - m_availableStorageLocations |= m_converter->partitionNameToStorageLocation(partitionName); - - // Handle responses for requests having no QContactAbstractRequest associated. - switch (requestType) { - case QContactJsonDbRequestManager::OrphanRequest: { - qWarning() << Q_FUNC_INFO << "Orphaned request:"<< jsonDbRequest; - return; - } - case QContactJsonDbRequestManager::InvalidRequest: { - qWarning() << Q_FUNC_INFO << "InvalidrequestType, request:" << jsonDbRequest; - return; - } - default: - break; - } - // Rest of the jsonDbRequest responses should have assosisated QContactAbstractRequest. - // However, if client already has deleted the request we just give a warning. - if (!req) { - qWarning() << Q_FUNC_INFO << "request id" << jsonDbRequest << "missing associated QContactAbstractRequest"; - return; - } - switch (requestType) { - case QContactJsonDbRequestManager::PrefetchForSaveRequest: { - QContactFetchRequest* preFetchReq = static_cast<QContactFetchRequest*>(req); - handleContactSavePrefetchResponse(preFetchReq, jsonDbRequest, contactIndex); - break; - } - case QContactJsonDbRequestManager::UpdateRequest: - case QContactJsonDbRequestManager::SaveRequest: { - QContactSaveRequest* saveReq = static_cast<QContactSaveRequest*>(req); - handleContactSaveResponse(saveReq, jsonDbRequest, contactIndex); - break; - } - case QContactJsonDbRequestManager::FetchRequest: { - QContactFetchRequest* fetchReq = static_cast<QContactFetchRequest*>(req); - handleContactFetchResponse(fetchReq, jsonDbRequest, partitionName); - break; - } - case QContactJsonDbRequestManager::FetchByIdRequest: { - QContactFetchByIdRequest* fetchByIdReq = static_cast<QContactFetchByIdRequest*>(req); - handleContactFetchByIdResponse(fetchByIdReq, jsonDbRequest, partitionName); - break; - } - case QContactJsonDbRequestManager::RemoveRequest: { - QContactRemoveRequest* removeReq = static_cast<QContactRemoveRequest*>(req); - handleContactRemoveResponse(removeReq); - break; - } - case QContactJsonDbRequestManager::ContactIdFetchRequest: { - QContactIdFetchRequest* idReq = static_cast<QContactIdFetchRequest*>(req); - handleContactIdFetchResponse(idReq, jsonDbRequest); - break; - } - default: - break; - } -} - -void QContactJsonDbRequestHandler::onJsonDbConnectionError(QtJsonDb::QJsonDbConnection::ErrorCode connectionError, const QString &message) -{ - //currently there are no error codes in QJsonDbConnection - //TODO handle them once its there - qWarning()<<Q_FUNC_INFO<<"error"<<connectionError<<"message"<<message; -} - -void QContactJsonDbRequestHandler::onJsonDbRequestError(QtJsonDb::QJsonDbRequest::ErrorCode error, - QString message) -{ - qWarning()<<Q_FUNC_INFO<<"error"<<error<<"message"<<message; - QJsonDbRequest *request = qobject_cast<QJsonDbRequest *>(sender()); - int contactIndex; - QContactJsonDbRequestManager::RequestType jsonDbRequestType; - QString partitionName; - QContactAbstractRequest *req = m_requestMgr->removeRequest(request, jsonDbRequestType, contactIndex, &partitionName); - - switch (jsonDbRequestType) { - case QContactJsonDbRequestManager::OrphanRequest: { - qWarning() << Q_FUNC_INFO << "Orphaned request with requestId:" << req; - return; - } - case QContactJsonDbRequestManager::InvalidRequest: { - qWarning() << Q_FUNC_INFO << "Invalid request with requestId:" << req; - return; - } - default: - break; - } - - // Rest of the jsonDbRequest responses should have associated QContactAbstractRequest. - // However, if client already has deleted the request we just give a warning. - if (!req) { - qWarning() << Q_FUNC_INFO << "request id" << req << "missing associated QContactAbstractRequest."; - return; - } - - QContactManager::Error contactError = m_converter->jsonDbRequestErrorToContactError(error); - if (request && (contactError == QContactManager::InvalidStorageLocationError)) { - const QContactAbstractRequest::StorageLocation storageLocation = - m_converter->partitionNameToStorageLocation(request->partition()); - if (storageLocation & ~supportedStorageLocations()) - qWarning() << Q_FUNC_INFO << "Unsupported storage location value:" << storageLocation; - m_availableStorageLocations &= ~storageLocation; - if (!m_availableStorageLocations) - // No partitions available in jsondb, indicate in the error. - contactError = errorPrecedence(contactError, QContactManager::MissingPlatformRequirementsError); - qCritical("QContacts - JsonDb backend - all storage locations unavailable."); - } - QContactManager::Error errorStatus = errorPrecedence(req->error(), contactError); - - switch (jsonDbRequestType) { - case QContactJsonDbRequestManager::FetchRequest: { - QList<QContact> emptyContactList; - if (m_requestMgr->isRequestCompleted(req)) { - QWaitCondition* waitCondition = m_requestMgr->waitCondition(req); - m_requestMgr->removeRequest(req); - QContactManagerEngine::updateContactFetchRequest (static_cast<QContactFetchRequest*>(req), emptyContactList, - errorStatus, QContactAbstractRequest::FinishedState); - if (waitCondition) - waitCondition->wakeAll(); - } else { - QContactManagerEngine::updateContactFetchRequest (static_cast<QContactFetchRequest*>(req), emptyContactList, - errorStatus, QContactAbstractRequest::ActiveState); - } - break; - } - case QContactJsonDbRequestManager::FetchByIdRequest: { - QContactFetchByIdRequest *fetchByIdrequest = static_cast<QContactFetchByIdRequest*>(req); - if (m_requestMgr->isRequestCompleted(req)) { - // There may be already contacts fetched for this request before jsondb error. - QMap<int, QContactManager::Error> errorMap = fetchByIdrequest->errorMap(); - QContactManager::Error errorToDiscard = QContactManager::NoError; - QList<QContact> contacts = orderedContacts(fetchByIdrequest->contactIds(), fetchByIdrequest->contacts(), &errorMap, &errorToDiscard); - QWaitCondition* waitCondition = m_requestMgr->waitCondition(req); - m_requestMgr->removeRequest(req); - QContactManagerEngine::updateContactFetchByIdRequest(fetchByIdrequest, contacts, errorStatus, - errorMap, QContactAbstractRequest::FinishedState); - if (waitCondition) - waitCondition->wakeAll(); - } else { - QContactManagerEngine::updateContactFetchByIdRequest(fetchByIdrequest, fetchByIdrequest->contacts(), - errorStatus, fetchByIdrequest->errorMap(), - QContactAbstractRequest::ActiveState); - } - break; - } - // The following two request types are both related to contact save request. - // They do share exactly the same handling down below. - case QContactJsonDbRequestManager::PrefetchForSaveRequest: - case QContactJsonDbRequestManager::SaveRequest: { - QContactSaveRequest* saveReq = static_cast<QContactSaveRequest*>(req); - QList<QContact> contacts = saveReq->contacts(); - QMap<int, QContactManager::Error> errorMap = saveReq->errorMap(); - if (contactError != QContactManager::NoError) { - errorMap.insert(contactIndex, contactError); - } - if (contacts.size() > contactIndex) { - qWarning() << Q_FUNC_INFO << "Save request failed for contact at index" << contactIndex - << "and contact id" << contacts.at(contactIndex).id(); - } else { - qWarning() << Q_FUNC_INFO << "Save request failed for contact at index" << contactIndex; - } - if (m_requestMgr->isRequestCompleted(req)) { - QWaitCondition* waitCondition = m_requestMgr->waitCondition(req); - m_requestMgr->removeRequest(req); - QContactManagerEngine::updateContactSaveRequest(static_cast<QContactSaveRequest*>(req),contacts, - contactError,errorMap,QContactAbstractRequest::FinishedState); - if (waitCondition) - waitCondition->wakeAll(); - } else { - QContactManagerEngine::updateContactSaveRequest(static_cast<QContactSaveRequest*>(req),contacts, - contactError,errorMap,QContactAbstractRequest::ActiveState); - } - break; - } - case QContactJsonDbRequestManager::RemoveRequest: { - QContactRemoveRequest* removeReq = static_cast<QContactRemoveRequest*>(req); - QMap<int, QContactManager::Error> errorMap = removeReq->errorMap(); - if (contactError != QContactManager::NoError) - errorMap.insert(contactIndex, contactError); - if (m_requestMgr->isRequestCompleted(req)) { - QWaitCondition* waitCondition = m_requestMgr->waitCondition(req); - m_requestMgr->removeRequest(req); - QContactManagerEngine::updateContactRemoveRequest(removeReq, errorStatus, errorMap, QContactAbstractRequest::FinishedState); - if (waitCondition) - waitCondition->wakeAll(); - } else { - // If request not yet completed, just add error to the requests' error map. - QContactManagerEngine::updateContactRemoveRequest(removeReq, errorStatus, errorMap, QContactAbstractRequest::ActiveState); - } - break; - } - case QContactJsonDbRequestManager::ContactIdFetchRequest: { - QContactIdFetchRequest* idFetchReq = static_cast<QContactIdFetchRequest*>(req); - QList<QContactId> ids; - // There may be already contact ids fetched for this request before jsondb error. - if (idFetchReq) - ids = idFetchReq->ids(); - if (m_requestMgr->isRequestCompleted(req)) { - QWaitCondition* waitCondition = m_requestMgr->waitCondition(req); - m_requestMgr->removeRequest(req); - QContactManagerEngine::updateContactIdFetchRequest(idFetchReq, ids, contactError, QContactAbstractRequest::FinishedState); - if (waitCondition) - waitCondition->wakeAll(); - } else { - QContactManagerEngine::updateContactIdFetchRequest(idFetchReq, ids, contactError, QContactAbstractRequest::ActiveState); - } - - break; - } - default: - break; - } -} - -void QContactJsonDbRequestHandler::removeDestroyed(QObject * req) -{ QMutexLocker locker(m_reqStateMutex); - QContactAbstractRequest* aReq = static_cast<QContactAbstractRequest*>(req); - if ((aReq)&&(!m_reqList.contains(aReq))&&(m_requestMgr->contains(aReq))) { - m_reqList.append((aReq)); - m_requestMgr->removeRequest(aReq); - } -} - -void QContactJsonDbRequestHandler::handleContactSaveResponse(QContactSaveRequest* req, QJsonDbRequest *jsonDbRequest, int index) -{ - QContactManager::Error lastError = req->error(); - QMap<int, QContactManager::Error> errorMap = req->errorMap(); - QList<QJsonObject> results = jsonDbRequest->takeResults(); - foreach (const QJsonObject &result, results) { - QString jsonUuid = result.value(QContactJsonDbStr::uuid()).toString(); - if (!jsonUuid.isEmpty()) { - QContact contact = req->contacts().at(index); - bool isNewContact = (contact.id().isNull() || contact.id().managerUri().isEmpty()); - if (isNewContact) { - contact.setId(m_converter->uuidtoContactId(jsonUuid, jsonDbRequest->partition())); - } - m_requestMgr->addContact(req, contact, index); - } - } - if (!m_requestMgr->pendingPrefetchRequests(req) && m_requestMgr->isRequestCompleted(req)) { - QList<QContact> contacts = m_requestMgr->contacts(req); - QWaitCondition* waitCondition = m_requestMgr->waitCondition(req); - m_requestMgr->removeRequest(req); - QContactManagerEngine::updateContactSaveRequest(req, contacts, lastError, errorMap, QContactAbstractRequest::FinishedState); - if (waitCondition) - waitCondition->wakeAll(); - } -} - -void QContactJsonDbRequestHandler::handleContactSavePrefetchResponse(QContactFetchRequest *prefetchReq, QJsonDbRequest *jsonDbRequest, int index) -{ - QContactManager::Error error = QContactManager::NoError; - QContactSaveRequest *saveReq = m_requestMgr->removePrefetchRequest(prefetchReq); - if (!saveReq) { - qWarning() << Q_FUNC_INFO << "prefetch request not found"; - return; - } - QList<QJsonObject> results = jsonDbRequest->takeResults(); - QJsonObject result; - // use a local variable instead of const reference in foreach since it is modified in the loop - foreach (result, results) { - if (result.isEmpty()) { - // An empty response for prefetch request means attempt to update a non-existing contact. - error = errorPrecedence(error, QContactManager::DoesNotExistError); - qWarning() << Q_FUNC_INFO << "Empty prefetch response from jsondb."; - } else { - // Convert QContact to jsondb contact over the prefetched jsondb contact and save it. - QString partition = storageLocationToPartition( - extractStorageLocation(saveReq->contacts().at(index).id())); - if (!m_converter->toJsonContact(&result, saveReq->contacts().at(index),saveReq->typeMask())) { - qWarning() << Q_FUNC_INFO << "Conversion from QContact to QJsonObject failed."; - // Converter failed to map this QContact to Jsondb contact. - error = errorPrecedence(error, QContactManager::BadArgumentError); - } else { - // Make save request for this contact. - if (!makeJsonDbRequest(saveReq, - QContactJsonDbRequestManager::UpdateRequest, - index, - partition, - QString(), - QList<QJsonObject>() << result)) { - error = errorPrecedence(error, QContactManager::TimeoutError); - } else { - return; - } - } - } - } - // In a rare case of an error we need to update the error map and last error. - QMap<int, QContactManager::Error> errorMap = saveReq->errorMap(); - if (results.isEmpty()) { - error = errorPrecedence(error, QContactManager::DoesNotExistError); - } - errorMap.insert(index, error); - error = errorPrecedence(error, saveReq->error()); - QList<QContact> contacts = m_requestMgr->contacts(saveReq); - if ((!m_requestMgr->pendingPrefetchRequests(saveReq)) && - m_requestMgr->isRequestCompleted(saveReq)) { - // Error happens to the last contact in the save request and the whole request gets finished. - QWaitCondition* waitCondition = m_requestMgr->waitCondition(saveReq); - m_requestMgr->removeRequest(saveReq); - QContactManagerEngine::updateContactSaveRequest(saveReq, contacts, error, errorMap, QContactAbstractRequest::FinishedState); - if (waitCondition) - waitCondition->wakeAll(); - } else { - QContactManagerEngine::updateContactSaveRequest(saveReq, contacts, error, errorMap, QContactAbstractRequest::ActiveState); - } - qWarning() << Q_FUNC_INFO << "Failed for" << saveReq->contacts().at(index).id(); -} - - -void QContactJsonDbRequestHandler::handleContactFetchResponse(QContactFetchRequest *req, QJsonDbRequest *jsonDbRequest, const QString &partitionName) -{ - QList<QContact> contacts; - QContactManager::Error error = QContactManager::NoError; - if (req) { - error = req->error(); - contacts = req->contacts(); - } - QList<QJsonObject> results = jsonDbRequest->takeResults(); - foreach (const QJsonObject &result, results) { - if (!result.isEmpty()) { - QContact contact; - m_converter->toQContact(result, &contact, partitionName); - contacts.append(contact); - } - } - if ((contacts.isEmpty()) || results.isEmpty()) - error = errorPrecedence(error, QContactManager::DoesNotExistError); - if (m_requestMgr->isRequestCompleted(req)) { - QWaitCondition* waitCondition = m_requestMgr->waitCondition(req); - m_requestMgr->removeRequest(req); - QContactManagerEngine::updateContactFetchRequest (req, contacts, error, QContactAbstractRequest::FinishedState); - if (waitCondition) - waitCondition->wakeAll(); - - } else { - QContactManagerEngine::updateContactFetchRequest(req, contacts, error, QContactAbstractRequest::ActiveState); - } - -} - -void QContactJsonDbRequestHandler::handleContactFetchByIdResponse(QContactFetchByIdRequest *req, QJsonDbRequest *jsonDbRequest, const QString &partitionName) -{ - QList<QContact> fetchedContacts; - QContactManager::Error error = QContactManager::NoError; - if (req) { - error = req->error(); - fetchedContacts = req->contacts(); - } - QList<QJsonObject> resultsFromResponse = jsonDbRequest->takeResults(); - foreach (const QJsonObject &result, resultsFromResponse) { - if (!result.isEmpty()) { - QContact contact; - if (m_converter->toQContact(result, &contact, partitionName)) - fetchedContacts.append(contact); - } - } - if (m_requestMgr->isRequestCompleted(req)) { - QList<QContact> contacts; - QMap<int, QContactManager::Error> errorMap; - QList<QContactId> idsFromRequest; - if (req) - idsFromRequest = req->contactIds(); - QContactManager::Error errorFromOrdering = QContactManager::NoError; - contacts = orderedContacts(idsFromRequest, fetchedContacts, &errorMap, &errorFromOrdering); - error = errorPrecedence(error, errorFromOrdering); - QWaitCondition* waitCondition = m_requestMgr->waitCondition(req); - m_requestMgr->removeRequest(req); - QContactManagerEngine::updateContactFetchByIdRequest(req, contacts, error, errorMap, QContactAbstractRequest::FinishedState); - if (waitCondition) - waitCondition->wakeAll(); - } else { - QMap<int, QContactManager::Error> emptyErrorMap; // Error map can be properly updated only when request is completely finished. - QContactManagerEngine::updateContactFetchByIdRequest(req, fetchedContacts, error, emptyErrorMap, QContactAbstractRequest::ActiveState); - } -} - -QList<QContact> QContactJsonDbRequestHandler::orderedContacts(const QList<QContactId> &ids, - const QList<QContact> &contacts, - QMap<int, QContactManager::Error> *errorMap, - QContactManager::Error *lastError) -{ - Q_ASSERT(errorMap); - Q_ASSERT(lastError); - // Order contacts in the same order with given ids. - // First build an index into contacts, value is index into unordered list. - QHash<QContactId, int> idToIndexMap; - for (int i = 0; i < contacts.size(); i++) { - idToIndexMap.insert(contacts.at(i).id(), i); - } - - // Then ind the order in which the contacts results should be presented - // and build ordered contact list and related error map. - int index=0; - QList<QContact> ordered; - foreach (const QContactId &id, ids) { - if (!idToIndexMap.contains(id)) { - errorMap->insert(index, QContactManager::DoesNotExistError); - *lastError = QContactManager::DoesNotExistError; - ordered.append(QContact()); - } else { - ordered.append(contacts.at(idToIndexMap[id])); - } - index++; - } - return ordered; -} - -void QContactJsonDbRequestHandler::handleContactRemoveResponse(QContactRemoveRequest *req) -{ - if (m_requestMgr->isRequestCompleted(req)) { - QWaitCondition* waitCondition = m_requestMgr->waitCondition(req); - m_requestMgr->removeRequest(req); - QContactManager::Error lastError = req->error(); - QMap<int, QContactManager::Error> errorMap = req->errorMap(); - QContactManagerEngine::updateContactRemoveRequest(req, lastError, errorMap, QContactAbstractRequest::FinishedState); - if (waitCondition) - waitCondition->wakeAll(); - } -} - -void QContactJsonDbRequestHandler::handleContactIdFetchResponse(QContactIdFetchRequest* req, QJsonDbRequest *jsonDbRequest) -{ - QList<QContactId> ids; - QContactManager::Error error = QContactManager::NoError; - if (req) { - ids = req->ids(); - error = req->error(); - } - QList<QJsonObject> results = jsonDbRequest->takeResults(); - foreach (const QJsonObject &result, results) { - QString uuid = result.value(QContactJsonDbStr::uuid()).toString(); - ids.append(m_converter->uuidtoContactId(uuid, jsonDbRequest->partition())); - } - if (ids.isEmpty() || results.isEmpty()) - error = errorPrecedence(error, QContactManager::DoesNotExistError); - if (m_requestMgr->isRequestCompleted(req)) { - QWaitCondition* waitCondition = m_requestMgr->waitCondition(req); - m_requestMgr->removeRequest(req); - QContactManagerEngine::updateContactIdFetchRequest(req, ids, error, QContactAbstractRequest::FinishedState); - if (waitCondition) - waitCondition->wakeAll(); - } else { - QContactManagerEngine::updateContactIdFetchRequest(req, ids, error, QContactAbstractRequest::ActiveState); - } -} - -bool QContactJsonDbRequestHandler::makeJsonDbRequest(QContactAbstractRequest *contactRequest, - QContactJsonDbRequestManager::RequestType jsonDbRequestType, - int index, - const QString &partition, - const QString &query, - const QList<QJsonObject> &objects) -{ - QJsonDbRequest *request; - switch (jsonDbRequestType) { - case QContactJsonDbRequestManager::PrefetchForSaveRequest: - request = new QJsonDbReadRequest(query, this); - break; - case QContactJsonDbRequestManager::SaveRequest: - request = new QJsonDbCreateRequest(objects,this); - break; - case QContactJsonDbRequestManager::UpdateRequest: - request = new QJsonDbUpdateRequest(objects, this); - break; - case QContactJsonDbRequestManager::ContactIdFetchRequest: - request = new QJsonDbReadRequest(query, this); - break; - case QContactJsonDbRequestManager::RemoveRequest: - request = new QJsonDbRemoveRequest(objects,this); - break; - case QContactJsonDbRequestManager::FetchRequest: - request = new QJsonDbReadRequest(query, this); - break; - case QContactJsonDbRequestManager::FetchByIdRequest: - request = new QJsonDbReadRequest(query, this); - break; - default: - request = NULL; - break; - } - QJsonDbWriteRequest *writeRequest = qobject_cast<QJsonDbWriteRequest*>(request); - if (writeRequest) - writeRequest->setConflictResolutionMode(QJsonDbWriteRequest::Replace); - request->setPartition(partition); - connect(request, SIGNAL(error(QtJsonDb::QJsonDbRequest::ErrorCode,QString)), - this, SLOT(onJsonDbRequestError(QtJsonDb::QJsonDbRequest::ErrorCode, - QString))); - connect(request, SIGNAL(finished()), this, SLOT(onJsonDbRequestFinished())); - - if (m_jsonDbConnection->send(request)) { - m_requestMgr->addRequest(request, jsonDbRequestType, contactRequest, index); - return true; - } else { - delete request; - return false; - } -} - -void QContactJsonDbRequestHandler::onJsonDbRequestFinished() -{ - QJsonDbRequest *request = qobject_cast<QJsonDbRequest *>(sender()); - if (request) - handleResponse(request); -} - -QContactJsonDbPartitionWatcher::QContactJsonDbPartitionWatcher(QContactJsonDbRequestHandler *requestHandler, - QJsonDbWatcher *jsonDbWatcher, - QContactAbstractRequest::StorageLocation storageLocation) - : QObject(requestHandler), m_requestHandler(requestHandler), m_jsonDbWatcher(jsonDbWatcher), m_storageLocation(storageLocation) -{ - connect(m_jsonDbWatcher, SIGNAL(error(QtJsonDb::QJsonDbWatcher::ErrorCode,QString)), - this, SLOT(onJsonDbWatcherError(QtJsonDb::QJsonDbWatcher::ErrorCode,QString))); - connect(m_jsonDbWatcher, SIGNAL(notificationsAvailable(int)), - this, SLOT(onJsonDbWatcherNotificationsAvailable())); -} - -void QContactJsonDbPartitionWatcher::onJsonDbWatcherNotificationsAvailable() -{ - m_requestHandler->onJsonDbWatcherNotificationsAvailable(m_jsonDbWatcher, m_storageLocation); -} - -void QContactJsonDbPartitionWatcher::onJsonDbWatcherError(QtJsonDb::QJsonDbWatcher::ErrorCode error, - QString message) -{ - // TODO handle the error when partition is supported - if (error!=QJsonDbWatcher::NoError) - qCritical()<<Q_FUNC_INFO<<"error"<<error<<"message"<<message; -} - -#include "moc_qcontactjsondbrequesthandler.cpp" - -QT_END_NAMESPACE_CONTACTS diff --git a/src/plugins/contacts/jsondb/qcontactjsondbrequesthandler.h b/src/plugins/contacts/jsondb/qcontactjsondbrequesthandler.h deleted file mode 100644 index e2e8a09a2..000000000 --- a/src/plugins/contacts/jsondb/qcontactjsondbrequesthandler.h +++ /dev/null @@ -1,190 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtContacts module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QCONTACTJSONDBREQUESTHANDLER_H -#define QCONTACTJSONDBREQUESTHANDLER_H - -#include <QtCore/qmap.h> -#include <QtCore/qmutex.h> -#include <QtCore/qthread.h> -#include <QtCore/qwaitcondition.h> - -#include <QtJsonDb/qjsondbconnection.h> -#include <QtJsonDb/qjsondbwatcher.h> -#include <QtJsonDb/qjsondbrequest.h> - -#include <QtContacts/qcontactabstractrequest.h> -#include <QtContacts/qcontactsaverequest.h> -#include <QtContacts/qcontactfetchrequest.h> -#include <QtContacts/qcontactidfetchrequest.h> -#include <QtContacts/qcontactremoverequest.h> -#include <QtContacts/qcontact.h> -#include <QtContacts/qcontactchangeset.h> -#include <QtContacts/qcontactmanager.h> - -#include "qcontactjsondbrequestmanager.h" - -QT_FORWARD_DECLARE_CLASS(QTimer) - -QT_USE_NAMESPACE_JSONDB - -QT_BEGIN_NAMESPACE_CONTACTS - -class QContactJsonDbEngine; -class QContactJsonDbConverter; -class QContactJsonDbRequestHandler : public QObject -{ - Q_OBJECT -public: - QContactJsonDbRequestHandler(); - virtual ~QContactJsonDbRequestHandler(); - - void setEngine(QContactJsonDbEngine* engine); - - void onJsonDbWatcherNotificationsAvailable(QJsonDbWatcher *jsonDbWatcher, - QContactAbstractRequest::StorageLocation storageLocation); - -public slots: - bool waitForRequestFinished(QContactAbstractRequest* req, int msecs); - void handleRequest(QContactAbstractRequest* req); - void handleResponse(QJsonDbRequest *request); - void init(); - void removeDestroyed(QObject *); - - void onJsonDbConnectionError(QtJsonDb::QJsonDbConnection::ErrorCode error, const QString &message); - void onJsonDbRequestError(QtJsonDb::QJsonDbRequest::ErrorCode error, - QString message); - void onJsonDbRequestFinished(); - -private slots: - void onTimeout(); - -private: - void createWatcherForStorageLocation(QContactAbstractRequest::StorageLocation storageLocation); - - QString storageLocationToPartition(QContactAbstractRequest::StorageLocation storageLocation); - QContactAbstractRequest::StorageLocations storageLocationsOrDefault( - QContactAbstractRequest::StorageLocations storageLocation); - QContactAbstractRequest::StorageLocation extractStorageLocation(const QContactId &id); - QContactAbstractRequest::StorageLocations extractStorageLocations(const QList<QContactId> &contactIds); - inline static QContactAbstractRequest::StorageLocations supportedStorageLocations() - { - return QContactAbstractRequest::UserDataStorage | QContactAbstractRequest::SystemStorage; - } - - void handleContactSaveRequest(QContactSaveRequest* req); - void handleContactFetchRequest(QContactFetchRequest* req); - void handleContactRemoveRequest(QContactRemoveRequest* req); - void handleContactIdFetchRequest(QContactIdFetchRequest* req); - void handleContactFetchByIdRequest(QContactFetchByIdRequest* req); - - void handleContactSaveResponse(QContactSaveRequest* saveReq, QJsonDbRequest *request, int contactIndex); - void handleContactSavePrefetchResponse(QContactFetchRequest *prefetchReq, QJsonDbRequest *request, int contactIndex); - void handleContactFetchResponse(QContactFetchRequest* fetchReq, QJsonDbRequest *request, const QString &partitionName); - void handleContactRemoveResponse(QContactRemoveRequest* removeReq); - void handleContactIdFetchResponse(QContactIdFetchRequest* idReq, QJsonDbRequest *request); - void handleContactFetchByIdResponse(QContactFetchByIdRequest *req, QJsonDbRequest *jsonDbRequest, const QString &partitionName); - - QList<QContact> orderedContacts(const QList<QContactId> &ids, const QList<QContact> &contacts, - QMap<int, QContactManager::Error> *errorMap, QContactManager::Error *lastError); - - bool makeJsonDbRequest(QContactAbstractRequest *contactRequest, - QContactJsonDbRequestManager::RequestType jsonDbRequestType, - int index, - const QString &partition, - const QString &query = QString(), - const QList<QJsonObject> &objects = QList<QJsonObject>()); - - void startTimer(); - - inline static QContactManager::Error errorPrecedence(QContactManager::Error firstError, QContactManager::Error secondError) - { - // Currently this makes a simple precedence for error codes. - // In case of nonidentical mapping is needed you need to modify this. - return (firstError < secondError) ? secondError : firstError; - } - -private: - Q_DISABLE_COPY(QContactJsonDbRequestHandler) - -private: - QContactJsonDbEngine* m_engine; - QJsonDbConnection *m_jsonDbConnection; - QContactJsonDbRequestManager* m_requestMgr; - QContactJsonDbConverter* m_converter; - // Mutex to make request state changes atomic. - // Main thread access the same requests we store in m_reqList. - QMutex* m_reqStateMutex; - QList <QContactAbstractRequest*> m_reqList; - - // For contact change notifications. - QContactChangeSet m_ccs; - static const int TIMEOUT_INTERVAL; - QTimer *m_timer; - - // For maintaining storage locations availability status. - QContactAbstractRequest::StorageLocations m_availableStorageLocations; -}; - -class QContactJsonDbPartitionWatcher : public QObject -{ - Q_OBJECT -public: - QContactJsonDbPartitionWatcher(QContactJsonDbRequestHandler *requestHandler, - QJsonDbWatcher *jsonDbWatcher, - QContactAbstractRequest::StorageLocation storageLocation); - -private slots: - void onJsonDbWatcherNotificationsAvailable(); - void onJsonDbWatcherError(QtJsonDb::QJsonDbWatcher::ErrorCode error, QString message); - -private: - Q_DISABLE_COPY(QContactJsonDbPartitionWatcher) - -private: - QContactJsonDbRequestHandler *m_requestHandler; - QJsonDbWatcher *m_jsonDbWatcher; - QContactAbstractRequest::StorageLocation m_storageLocation; -}; - -QT_END_NAMESPACE_CONTACTS - -#endif // QCONTACTJSONDBREQUESTHANDLER_H diff --git a/src/plugins/contacts/jsondb/qcontactjsondbrequestmanager.cpp b/src/plugins/contacts/jsondb/qcontactjsondbrequestmanager.cpp deleted file mode 100644 index 955a93ae4..000000000 --- a/src/plugins/contacts/jsondb/qcontactjsondbrequestmanager.cpp +++ /dev/null @@ -1,226 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtContacts module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qcontactjsondbrequestmanager.h" - -#include <QtCore/qdebug.h> -#include <QtCore/qthread.h> - -QT_BEGIN_NAMESPACE_CONTACTS - -QContactJsonDbRequestManager::QContactJsonDbRequestManager() -{ - m_operationMutex = new QMutex(); -} - -QContactJsonDbRequestManager::~QContactJsonDbRequestManager() -{ - delete m_operationMutex; -} - -void QContactJsonDbRequestManager::addRequest(QContactAbstractRequest* req, QList<QContact> items) -{ - QMutexLocker locker(m_operationMutex); - if (!m_activeRequests.contains(req)) { - QContactRequestData* newData = new QContactRequestData(); - newData->m_contactList = items; - if (m_inactiveRequests.contains(req)) { - newData->m_waitCondition = m_inactiveRequests.value(req); - m_inactiveRequests.remove(req); - } else { - newData->m_waitCondition = 0; - } - m_activeRequests.insert(req, newData); - } -} - -void QContactJsonDbRequestManager::removeRequest(QContactAbstractRequest* req) -{ - QMutexLocker locker(m_operationMutex); - if (m_activeRequests.contains(req)) { - delete m_activeRequests.value(req); - m_activeRequests.remove(req); - } -} - -void QContactJsonDbRequestManager::addPrefetchRequest(QContactFetchRequest *prefetchReq, QContactSaveRequest *saveReq) -{ - QMutexLocker locker(m_operationMutex); - if (!m_prefetchRequestsMap.contains(prefetchReq)) { - m_prefetchRequestsMap.insert(prefetchReq, saveReq); - } -} - -QContactSaveRequest* QContactJsonDbRequestManager::removePrefetchRequest(QContactFetchRequest *prefetchReq) -{ - QMutexLocker locker(m_operationMutex); - if (m_prefetchRequestsMap.contains(prefetchReq)) { - return m_prefetchRequestsMap.take(prefetchReq); - } - return 0; -} - -void QContactJsonDbRequestManager::addRequest(QJsonDbRequest *jsonDbRequest, RequestType requestType, QContactAbstractRequest *req, int contactIndex) -{ - QMutexLocker locker(m_operationMutex); - m_jsonDbRequestTypeMap.insert(jsonDbRequest, requestType); - if (m_activeRequests.contains(req)) { - m_activeRequests.value(req)->m_jsonDbRequestMap.insert(jsonDbRequest, contactIndex); - } -} - -QContactAbstractRequest* QContactJsonDbRequestManager::removeRequest(QJsonDbRequest *jsonDbRequest, RequestType &requestType, int &contactIndex, QString *partitionName) -{ - QMutexLocker locker(m_operationMutex); - if (m_jsonDbRequestTypeMap.contains(jsonDbRequest)) { - requestType = m_jsonDbRequestTypeMap.value(jsonDbRequest); - m_jsonDbRequestTypeMap.remove(jsonDbRequest); - if (requestType == OrphanRequest || requestType == InvalidRequest) - return 0; - } else { - qWarning() << Q_FUNC_INFO << "Could not find jsondbRequest:" << jsonDbRequest; - requestType = InvalidRequest; - return 0; - } - QList<QContactAbstractRequest*> reqList = m_activeRequests.keys(); - for (int i = 0; i < reqList.size(); i++) { - QContactAbstractRequest* req = reqList.at(i); - QMap<QJsonDbRequest*, int>* requestMap = &(m_activeRequests.value(req)->m_jsonDbRequestMap); - if (requestMap->contains(jsonDbRequest)) { - *partitionName = jsonDbRequest->partition(); - contactIndex = requestMap->value(jsonDbRequest); - requestMap->remove(jsonDbRequest); - return reqList.at(i); - } - } - // request already deleted so mark this as orphan. - requestType = OrphanRequest; - return 0; -} - - -bool QContactJsonDbRequestManager::setWaitCondition(QContactAbstractRequest *req, QWaitCondition *waitCondition) -{ - // This function is called by JsonDbEngine, which is in another thread - QMutexLocker locker(m_operationMutex); - - if (m_activeRequests.contains(req)) { - m_activeRequests.value(req)->m_waitCondition = waitCondition; - return true; - } else if (!m_inactiveRequests.contains(req)) { - // Request and wait condition stored here if waitForRequestFinished function is called without starting - // the request or after starting, but before slot JsonDbEngineRequestHandler::handleRequest is called. - m_inactiveRequests.insert(req, waitCondition); - return false; - } - //This should never happen... - return false; -} - -QWaitCondition* QContactJsonDbRequestManager::waitCondition(QContactAbstractRequest *req) -{ - QMutexLocker locker(m_operationMutex); - - if (m_activeRequests.contains(req)) { - return m_activeRequests.value(req)->m_waitCondition; - } - return 0; -} - -void QContactJsonDbRequestManager::removeWaitCondition(QContactAbstractRequest *req) -{ - QMutexLocker locker(m_operationMutex); - - // The request is found only if waitForRequestFinished function was called for an Inactive request - // which was never started. - - if (!m_inactiveRequests.contains(req)) { - m_inactiveRequests.remove(req); - } -} - -void QContactJsonDbRequestManager::addContact(QContactAbstractRequest* req, QContact item, int contactIndex) -{ - QMutexLocker locker(m_operationMutex); - - if (m_activeRequests.contains(req)) { - m_activeRequests.value(req)->m_contactList.replace(contactIndex, item); - } -} - -QList<QContact> QContactJsonDbRequestManager::contacts(QContactAbstractRequest* req) -{ - QMutexLocker locker(m_operationMutex); - - if (m_activeRequests.contains(req)) - return m_activeRequests.value(req)->m_contactList; - else - return QList<QContact>(); -} - - - -bool QContactJsonDbRequestManager::isRequestCompleted(QContactAbstractRequest* req) -{ - QMutexLocker locker(m_operationMutex); - - if (m_activeRequests.contains(req)) { - return m_activeRequests.value(req)->m_jsonDbRequestMap.isEmpty(); - } - return true; -} - -bool QContactJsonDbRequestManager::pendingPrefetchRequests(QContactSaveRequest *saveReq) -{ - QMutexLocker locker(m_operationMutex); - return ((m_activeRequests.contains(saveReq)) && - (!m_prefetchRequestsMap.keys(saveReq).isEmpty())); -} - -bool QContactJsonDbRequestManager::contains(QContactAbstractRequest *req) const -{ - QMutexLocker locker(m_operationMutex); - return m_activeRequests.contains(req);// || m_inactiveRequests.contains(req); -} - -#include "moc_qcontactjsondbrequestmanager.cpp" - -QT_END_NAMESPACE_CONTACTS diff --git a/src/plugins/contacts/jsondb/qcontactjsondbrequestmanager.h b/src/plugins/contacts/jsondb/qcontactjsondbrequestmanager.h deleted file mode 100644 index 134495b82..000000000 --- a/src/plugins/contacts/jsondb/qcontactjsondbrequestmanager.h +++ /dev/null @@ -1,138 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtContacts module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QCONTACTJSONDBREQUESTMANAGER_H -#define QCONTACTJSONDBREQUESTMANAGER_H -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/qmap.h> -#include <QtCore/qmutex.h> -#include <QtCore/qobject.h> -#include <QtCore/qwaitcondition.h> - -#include <QtJsonDb/qjsondbconnection.h> -#include <QtJsonDb/qjsondbwatcher.h> -#include <QtJsonDb/qjsondbrequest.h> - -#include <QtContacts/qcontact.h> -#include <QtContacts/qcontactrequests.h> - -QT_USE_NAMESPACE_JSONDB - -QT_BEGIN_NAMESPACE_CONTACTS - -class QContactRequestData -{ - public: - QContactRequestData() {} - QList<QContact> m_contactList; - QMap<QJsonDbRequest*, int> m_jsonDbRequestMap; - QWaitCondition* m_waitCondition; -}; - -class QContactJsonDbRequestManager : public QObject -{ - Q_OBJECT - -public: - - enum RequestType { - InvalidRequest = 0, - OrphanRequest, - PrefetchForSaveRequest, - SaveRequest, - UpdateRequest, - FetchRequest, - ContactIdFetchRequest, - RemoveRequest, - FetchByIdRequest - }; - - QContactJsonDbRequestManager(); - ~QContactJsonDbRequestManager(); - - void addRequest(QContactAbstractRequest* req, QList<QContact> contacts = QList<QContact>()); - void removeRequest(QContactAbstractRequest* req); - - void addPrefetchRequest(QContactFetchRequest *prefetchReq, QContactSaveRequest *saveReq); - QContactSaveRequest* removePrefetchRequest(QContactFetchRequest *prefetchReq); - - void addRequest(QJsonDbRequest *jsonDbRequest, RequestType requestType, QContactAbstractRequest *req = 0, int contactIndex = -1); - QContactAbstractRequest* removeRequest(QJsonDbRequest *jsonDbRequest, RequestType &requestType, int &contactIndex, QString *partitionName); - - bool setWaitCondition(QContactAbstractRequest* req, QWaitCondition* waitCondition); - QWaitCondition* waitCondition(QContactAbstractRequest* req); - void removeWaitCondition(QContactAbstractRequest* req); - - void addContact(QContactAbstractRequest* req, QContact item, int contactIndex); - QList<QContact> contacts(QContactAbstractRequest* req); - - bool isRequestCompleted(QContactAbstractRequest* req); - bool pendingPrefetchRequests(QContactSaveRequest *saveReq); - bool contains(QContactAbstractRequest* req) const; - -signals: - -public slots: - -private: - Q_DISABLE_COPY(QContactJsonDbRequestManager) - -private: - QMap<QContactAbstractRequest*, QContactRequestData* > m_activeRequests; - QMap<QContactAbstractRequest*, QWaitCondition* > m_inactiveRequests; - QMap<QContactFetchRequest*, QContactSaveRequest*> m_prefetchRequestsMap; - QMap<QJsonDbRequest*, QContactJsonDbRequestManager::RequestType> m_jsonDbRequestTypeMap; - QMutex* m_operationMutex; -}; - -QT_END_NAMESPACE_CONTACTS - -#endif // QCONTACTJSONDBREQUESTMANAGER_H diff --git a/src/plugins/contacts/jsondb/qcontactjsondbstring.cpp b/src/plugins/contacts/jsondb/qcontactjsondbstring.cpp deleted file mode 100644 index 0c18483a0..000000000 --- a/src/plugins/contacts/jsondb/qcontactjsondbstring.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtContacts module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qcontactjsondbstring.h" diff --git a/src/plugins/contacts/jsondb/qcontactjsondbstring.h b/src/plugins/contacts/jsondb/qcontactjsondbstring.h deleted file mode 100644 index 2e3bb7c92..000000000 --- a/src/plugins/contacts/jsondb/qcontactjsondbstring.h +++ /dev/null @@ -1,136 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the Qt Pim Module -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QCONTACTJSONDBSTRING_H -#define QCONTACTJSONDBSTRING_H - -#include <QtCore/qstring.h> - -#include <QtContacts/qcontactsglobal.h> - -QT_BEGIN_NAMESPACE_CONTACTS - -class QContactJsonDbStr -{ -public: - // Version - const static int ContactJsonDbEngineVersion = 1.0; - - // Engine meta-data - inline const static QString contactJsonDbEngineName() { return QStringLiteral("jsondb"); } - inline const static QString managerName() { return QStringLiteral("qtcontacts:jsondb::"); } - inline const static QString managerUri() { return QStringLiteral("qtcontacts:jsondb:"); } - - // Jsondb column names - inline const static QString type() { return QStringLiteral("_type"); } - inline const static QString uuid() { return QStringLiteral("_uuid"); } - inline const static QString version() { return QStringLiteral("_version"); } - - // Jsondb field names - inline const static QString nameDefinitionName() { return QStringLiteral("name"); } - inline const static QString genderDefinitionName() { return QStringLiteral("gender"); } - inline const static QString phoneNumberDefinitionName() { return QStringLiteral("phones"); } - inline const static QString emailAddressDefinitionName() { return QStringLiteral("emails"); } - inline const static QString urlDefinitionName() { return QStringLiteral("urls"); } - inline const static QString nicknameDefinitionName() { return QStringLiteral("nickname"); } - inline const static QString displayLabelDefinitionName() { return QStringLiteral("displayLabel"); } - inline const static QString addressDefinitionName() { return QStringLiteral("addresses"); } - inline const static QString birthdayDefinitionName() { return QStringLiteral("birthday"); } - inline const static QString avatarDefinitionName() { return QStringLiteral("photoUrl"); } - inline const static QString ringtoneDefinitionName() { return QStringLiteral("ringtoneUrl"); } - inline const static QString organizationDefinitionName() { return QStringLiteral("organizations"); } - inline const static QString noteDefinitionName() { return QStringLiteral("note"); } - inline const static QString syncTargetDefinitionName() { return QStringLiteral("synctarget"); } - inline const static QString guidDefinitionName() { return QStringLiteral("guid"); } - inline const static QString nameFieldFirstName() { return QStringLiteral("firstName"); } - inline const static QString nameFieldLastName() { return QStringLiteral("lastName"); } - inline const static QString nameFieldMiddleName() { return QStringLiteral("middleName"); } - inline const static QString nameFieldPrefix() { return QStringLiteral("prefix"); } - inline const static QString nameFieldSuffix() { return QStringLiteral("suffix"); } - inline const static QString addressFieldCountry() { return QStringLiteral("country"); } - inline const static QString addressFieldRegion() { return QStringLiteral("region"); } - inline const static QString addressFieldLocality() { return QStringLiteral("locality"); } - inline const static QString addressFieldPostcode() { return QStringLiteral("postcode"); } - inline const static QString addressFieldPostOfficeBox() { return QStringLiteral("postOfficeBox"); } - inline const static QString addressFieldStreet() { return QStringLiteral("street"); } - inline const static QString organizationFieldName() { return QStringLiteral("name"); } - inline const static QString organizationFieldDepartment() { return QStringLiteral("department"); } - inline const static QString organizationFieldTitle() { return QStringLiteral("title"); } - inline const static QString organizationFieldRole() { return QStringLiteral("role"); } - inline const static QString organizationFieldAssistantName() { return QStringLiteral("assistantName"); } - inline const static QString organizationFieldLogoUrl() { return QStringLiteral("logoUrl"); } - inline const static QString organizationFieldStartDate() { return QStringLiteral("startDate"); } - inline const static QString organizationFieldEndDate() { return QStringLiteral("endDate"); } - - //JsonDb enums - inline const static QString genderMale() { return QStringLiteral("male"); } - inline const static QString genderFemale() { return QStringLiteral("female"); } - inline const static QString genderOther() { return QStringLiteral("other"); } - - // Jsondb Contexts and Subtypes - inline const static QString contextHome() { return QStringLiteral("home"); } - inline const static QString contextWork() { return QStringLiteral("work"); } - inline const static QString contextOther() { return QStringLiteral("other"); } - inline const static QString subTypePref() { return QStringLiteral("pref"); } - inline const static QString subTypeFax() { return QStringLiteral("fax"); } - inline const static QString subTypeCell() { return QStringLiteral("cell"); } - inline const static QString subTypeVideo() { return QStringLiteral("video"); } - inline const static QString subTypeLandline() { return QStringLiteral("landline"); } - inline const static QString contactDetails() { return QStringLiteral("details"); } - - // Jsondb actions - inline const static QString actionCreate() { return QStringLiteral("create"); } - inline const static QString actionUpdate() { return QStringLiteral("update"); } - inline const static QString actionRemove() { return QStringLiteral("remove"); } - - // partition names - inline const static QString userDataPartition() { return QStringLiteral("com.nokia.mt.User"); } - inline const static QString systemPartition() { return QStringLiteral("com.nokia.mt.System"); } - - // Queries related - inline const static QString contactsJsonDbType() { return QStringLiteral("com.nokia.mt.contacts.Contact"); } - inline const static QString contactsJsonDbNotificationQuery() { return QStringLiteral("[?_type in [\"com.nokia.mt.contacts.Contact\"]]"); } - inline const static QString uuidSelectQuery() { return QStringLiteral("[={_uuid:_uuid}]"); } -}; - -QT_END_NAMESPACE_CONTACTS - -#endif // QCONTACTJSONDBSTRING_H diff --git a/src/plugins/organizer/jsondb/jsondb.json b/src/plugins/organizer/jsondb/jsondb.json deleted file mode 100644 index d127ebcb7..000000000 --- a/src/plugins/organizer/jsondb/jsondb.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "Keys": [ "jsondb" ] -} diff --git a/src/plugins/organizer/jsondb/jsondb.pro b/src/plugins/organizer/jsondb/jsondb.pro deleted file mode 100644 index 1def2110b..000000000 --- a/src/plugins/organizer/jsondb/jsondb.pro +++ /dev/null @@ -1,27 +0,0 @@ -TARGET = qtorganizer_jsondb -QT += organizer network jsondb - -PLUGIN_TYPE = organizer -load(qt_plugin) - -HEADERS += \ - qorganizerjsondbengine.h \ - qorganizerjsondbrequestthread.h \ - qorganizerjsondbenginefactory.h \ - qorganizerjsondbid.h \ - qorganizerjsondbrequestmanager.h \ - qorganizerjsondbstring.h \ - qorganizerjsondbconverter.h \ - qorganizerjsondbdatastorage.h - -SOURCES += \ - qorganizerjsondbengine.cpp \ - qorganizerjsondbrequestthread.cpp \ - qorganizerjsondbenginefactory.cpp \ - qorganizerjsondbid.cpp \ - qorganizerjsondbrequestmanager.cpp \ - qorganizerjsondbstring.cpp \ - qorganizerjsondbconverter.cpp \ - qorganizerjsondbdatastorage.cpp - -OTHER_FILES += jsondb.json diff --git a/src/plugins/organizer/jsondb/qorganizerjsondbconverter.cpp b/src/plugins/organizer/jsondb/qorganizerjsondbconverter.cpp deleted file mode 100644 index 035505c68..000000000 --- a/src/plugins/organizer/jsondb/qorganizerjsondbconverter.cpp +++ /dev/null @@ -1,2178 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtPIM module of the Qt toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qorganizerjsondbconverter.h" - -#include <QtCore/qjsonarray.h> - -#include <QtOrganizer/qorganizermanagerengine.h> -#include <QtOrganizer/qorganizeritemfilters.h> - -#include "qorganizerjsondbengine.h" -#include "qorganizerjsondbid.h" -#include "qorganizerjsondbstring.h" - -QT_BEGIN_NAMESPACE_ORGANIZER - -const int QOrganizerJsonDbConverter::enumMapEnd(-1212); - -const QMap<int, QString> QOrganizerJsonDbConverter::filterablePropertyNames() -{ - static QMap<int, QString> filterableProperties; - if (filterableProperties.isEmpty()) { - filterableProperties.insert(QOrganizerItemComment::FieldComment, - QOrganizerJsonDbStr::itemComments()); - filterableProperties.insert(QOrganizerItemDescription::FieldDescription, - QOrganizerJsonDbStr::itemDescription()); - filterableProperties.insert(QOrganizerItemDisplayLabel::FieldLabel, - QOrganizerJsonDbStr::itemDisplayName()); - filterableProperties.insert(QOrganizerEventRsvp::FieldOrganizerEmail, - QOrganizerJsonDbStr::eventRsvpOrganizerEmail()); - filterableProperties.insert(QOrganizerEventRsvp::FieldOrganizerName, - QOrganizerJsonDbStr::eventRsvpOrganizerName()); - filterableProperties.insert(QOrganizerEventRsvp::FieldParticipationRole, - QOrganizerJsonDbStr::eventRsvpParticipationRole()); - filterableProperties.insert(QOrganizerEventRsvp::FieldParticipationStatus, - QOrganizerJsonDbStr::eventRsvpParticipationStatus()); - filterableProperties.insert(QOrganizerEventRsvp::FieldResponseDate, - QOrganizerJsonDbStr::eventRsvpResponseDate()); - filterableProperties.insert(QOrganizerEventRsvp::FieldResponseDeadline, - QOrganizerJsonDbStr::eventRsvpResponseDeadline()); - filterableProperties.insert(QOrganizerEventRsvp::FieldResponseRequirement, - QOrganizerJsonDbStr::eventRsvpResponseRequirement()); - filterableProperties.insert(QOrganizerEventTime::FieldAllDay, - QOrganizerJsonDbStr::eventIsAllDay()); - filterableProperties.insert(QOrganizerEventTime::FieldEndDateTime, - QOrganizerJsonDbStr::eventEndDateTime()); - filterableProperties.insert(QOrganizerEventTime::FieldStartDateTime, - QOrganizerJsonDbStr::eventStartDateTime()); - filterableProperties.insert(QOrganizerItemGuid::FieldGuid, - QOrganizerJsonDbStr::itemGuid()); - filterableProperties.insert(QOrganizerItemLocation::FieldLabel, - QString(QStringLiteral("%1.%2") - .arg(QOrganizerJsonDbStr::eventLocation()) - .arg(QOrganizerJsonDbStr::eventLocationDisplayName())) - ); - filterableProperties.insert(QOrganizerItemLocation::FieldLatitude, - QString(QStringLiteral("%1.%2.%3") - .arg(QOrganizerJsonDbStr::eventLocation()) - .arg(QOrganizerJsonDbStr::eventLocationGeo()) - .arg(QOrganizerJsonDbStr::eventLocationGeoLatitude())) - ); - filterableProperties.insert(QOrganizerItemLocation::FieldLongitude, - QString(QStringLiteral("%1.%2.%3") - .arg(QOrganizerJsonDbStr::eventLocation()) - .arg(QOrganizerJsonDbStr::eventLocationGeo()) - .arg(QOrganizerJsonDbStr::eventLocationGeoLongitude())) - ); - filterableProperties.insert(QOrganizerItemPriority::FieldPriority, - QOrganizerJsonDbStr::itemPriority()); - filterableProperties.insert(QOrganizerItemTag::FieldTag, - QOrganizerJsonDbStr::itemTags()); - filterableProperties.insert(QOrganizerTodoProgress::FieldFinishedDateTime, - QOrganizerJsonDbStr::todoFinishedDateTime()); - filterableProperties.insert(QOrganizerTodoProgress::FieldPercentageComplete, - QOrganizerJsonDbStr::todoProgressPercentage()); - filterableProperties.insert(QOrganizerTodoProgress::FieldStatus, - QOrganizerJsonDbStr::todoStatus()); - filterableProperties.insert(QOrganizerTodoTime::FieldAllDay, - QOrganizerJsonDbStr::todoIsAllDay()); - filterableProperties.insert(QOrganizerTodoTime::FieldDueDateTime, - QOrganizerJsonDbStr::todoDueDateTime()); - filterableProperties.insert(QOrganizerTodoTime::FieldStartDateTime, - QOrganizerJsonDbStr::todoStartDateTime()); - }; - return filterableProperties; -} - -const QOrganizerJsonDbEnumConversionData *QOrganizerJsonDbConverter::organizerPriorityEnumMap() -{ - static const QOrganizerJsonDbEnumConversionData map[] = { - {QOrganizerItemPriority::UnknownPriority, QString(QStringLiteral("UnknownPriority"))}, - {QOrganizerItemPriority::ExtremelyHighPriority, QString(QStringLiteral("HighestPriority"))}, - {QOrganizerItemPriority::ExtremelyHighPriority, QString(QStringLiteral("ExtremelyHighPriority"))}, - {QOrganizerItemPriority::VeryHighPriority, QString(QStringLiteral("VeryHighPriority"))}, - {QOrganizerItemPriority::HighPriority, QString(QStringLiteral("HighPriority"))}, - {QOrganizerItemPriority::MediumPriority, QString(QStringLiteral("MediumPriority"))}, - {QOrganizerItemPriority::LowPriority, QString(QStringLiteral("LowPriority"))}, - {QOrganizerItemPriority::VeryLowPriority, QString(QStringLiteral("VeryLowPriority"))}, - {QOrganizerItemPriority::ExtremelyLowPriority, QString(QStringLiteral("ExtremelyLowPriority"))}, - {QOrganizerItemPriority::LowestPriority, QString(QStringLiteral("LowestPriority"))}, - {enumMapEnd, QString::null} - }; - return map; -} - -const QOrganizerJsonDbEnumConversionData *QOrganizerJsonDbConverter::organizerFrequencyEnumMap() -{ - static const QOrganizerJsonDbEnumConversionData map[] = { - {QOrganizerRecurrenceRule::Invalid, QString(QStringLiteral("Invalid"))}, - {QOrganizerRecurrenceRule::Daily, QString(QStringLiteral("Daily"))}, - {QOrganizerRecurrenceRule::Weekly, QString(QStringLiteral("Weekly"))}, - {QOrganizerRecurrenceRule::Monthly, QString(QStringLiteral("Monthly"))}, - {QOrganizerRecurrenceRule::Yearly, QString(QStringLiteral("Yearly"))}, - {enumMapEnd, QString::null} - }; - return map; -} - -const QOrganizerJsonDbEnumConversionData *QOrganizerJsonDbConverter::organizerDayEnumMap() -{ - static const QOrganizerJsonDbEnumConversionData map[] = { - {Qt::Monday, QString(QStringLiteral("Monday"))}, - {Qt::Tuesday, QString(QStringLiteral("Tuesday"))}, - {Qt::Wednesday, QString(QStringLiteral("Wednesday"))}, - {Qt::Thursday, QString(QStringLiteral("Thursday"))}, - {Qt::Friday, QString(QStringLiteral("Friday"))}, - {Qt::Saturday, QString(QStringLiteral("Saturday"))}, - {Qt::Sunday, QString(QStringLiteral("Sunday"))}, - {enumMapEnd, QString::null} - }; - return map; -} - -const QOrganizerJsonDbEnumConversionData *QOrganizerJsonDbConverter::organizerMonthEnumMap() -{ - static const QOrganizerJsonDbEnumConversionData map[] = { - {QOrganizerRecurrenceRule::January, QString(QStringLiteral("January"))}, - {QOrganizerRecurrenceRule::February, QString(QStringLiteral("February"))}, - {QOrganizerRecurrenceRule::March, QString(QStringLiteral("March"))}, - {QOrganizerRecurrenceRule::April, QString(QStringLiteral("April"))}, - {QOrganizerRecurrenceRule::May, QString(QStringLiteral("May"))}, - {QOrganizerRecurrenceRule::June, QString(QStringLiteral("June"))}, - {QOrganizerRecurrenceRule::July, QString(QStringLiteral("July"))}, - {QOrganizerRecurrenceRule::August, QString(QStringLiteral("August"))}, - {QOrganizerRecurrenceRule::September, QString(QStringLiteral("September"))}, - {QOrganizerRecurrenceRule::October, QString(QStringLiteral("October"))}, - {QOrganizerRecurrenceRule::November, QString(QStringLiteral("November"))}, - {QOrganizerRecurrenceRule::December, QString(QStringLiteral("December"))}, - {enumMapEnd, QString::null} - }; - return map; -} - -const QOrganizerJsonDbEnumConversionData *QOrganizerJsonDbConverter::organizerParticipationStatusMap() -{ - static const QOrganizerJsonDbEnumConversionData map[] = { - {QOrganizerEventAttendee::StatusUnknown, QString(QStringLiteral("Unknown"))}, - {QOrganizerEventAttendee::StatusAccepted, QString(QStringLiteral("Accepted"))}, - {QOrganizerEventAttendee::StatusDeclined, QString(QStringLiteral("Declined"))}, - {QOrganizerEventAttendee::StatusTentative, QString(QStringLiteral("Tentative"))}, - {QOrganizerEventAttendee::StatusDelegated, QString(QStringLiteral("Delegated"))}, - {QOrganizerEventAttendee::StatusInProcess, QString(QStringLiteral("InProcess"))}, - {QOrganizerEventAttendee::StatusCompleted, QString(QStringLiteral("Completed"))}, - {enumMapEnd, QString::null} - }; - return map; -} - -const QOrganizerJsonDbEnumConversionData *QOrganizerJsonDbConverter::organizerParticipationRoleMap() -{ - static const QOrganizerJsonDbEnumConversionData map[] = { - {QOrganizerEventAttendee::RoleUnknown, QString(QStringLiteral("Unknown"))}, - {QOrganizerEventAttendee::RoleOrganizer, QString(QStringLiteral("Organizer"))}, - {QOrganizerEventAttendee::RoleChairperson, QString(QStringLiteral("Chairperson"))}, - {QOrganizerEventAttendee::RoleHost, QString(QStringLiteral("Host"))}, - {QOrganizerEventAttendee::RoleRequiredParticipant, QString(QStringLiteral("RequiredParticipant"))}, - {QOrganizerEventAttendee::RoleOptionalParticipant, QString(QStringLiteral("OptionalParticipant"))}, - {QOrganizerEventAttendee::RoleNonParticipant, QString(QStringLiteral("NonParticipant"))}, - {enumMapEnd, QString::null} - }; - return map; -} - -const QOrganizerJsonDbEnumConversionData *QOrganizerJsonDbConverter::organizerResponseRequirementMap() -{ - static const QOrganizerJsonDbEnumConversionData map[] = { - {QOrganizerEventRsvp::ResponseNotRequired, QString(QStringLiteral("NotRequired"))}, - {QOrganizerEventRsvp::ResponseRequired, QString(QStringLiteral("Required"))}, - {enumMapEnd, QString::null} - }; - return map; -} - -const QOrganizerJsonDbEnumConversionData *QOrganizerJsonDbConverter::organizerItemTypeMap() -{ - static const QOrganizerJsonDbEnumConversionData map[] = { - {QOrganizerItemType::TypeUndefined, QString(QStringLiteral("Undefined"))}, - {QOrganizerItemType::TypeEvent, QString(QStringLiteral("Event"))}, - {QOrganizerItemType::TypeEventOccurrence, QString(QStringLiteral("EventOccurrence"))}, - {QOrganizerItemType::TypeTodo, QString(QStringLiteral("Todo"))}, - {QOrganizerItemType::TypeTodoOccurrence, QString(QStringLiteral("TodoOccurrence"))}, - {QOrganizerItemType::TypeJournal, QString(QStringLiteral("Journal"))}, - {QOrganizerItemType::TypeNote, QString(QStringLiteral("Note"))}, - {enumMapEnd, QString::null} - }; - return map; -} - -const QOrganizerJsonDbEnumConversionData *QOrganizerJsonDbConverter::organizerTodoStatusMap() -{ - static const QOrganizerJsonDbEnumConversionData map[] = { - {QOrganizerTodoProgress::StatusNotStarted, QString(QStringLiteral("NotStarted"))}, - {QOrganizerTodoProgress::StatusInProgress, QString(QStringLiteral("InProgress"))}, - {QOrganizerTodoProgress::StatusComplete, QString(QStringLiteral("Complete"))}, - {enumMapEnd, QString::null} - }; - return map; -} - -const QOrganizerJsonDbEnumConversionData *QOrganizerJsonDbConverter::organizerStorageLocationMap() -{ - static const QOrganizerJsonDbEnumConversionData map[] = { - {QOrganizerJsonDbEngine::UserDataStorage, QString(QStringLiteral("com.nokia.mt.User"))}, - {QOrganizerJsonDbEngine::SystemStorage, QString(QStringLiteral("com.nokia.mt.System"))}, - {enumMapEnd, QString::null} - }; - return map; -} - -QOrganizerJsonDbConverter::QOrganizerJsonDbConverter() -{ -} - -QOrganizerManager::Error QOrganizerJsonDbConverter::jsonDbConnectionErrorToOrganizerError(QJsonDbConnection::ErrorCode error) const -{ - switch (error) { - case QJsonDbConnection::NoError: - return QOrganizerManager::NoError; - } - return QOrganizerManager::NoError; -} - -QOrganizerManager::Error QOrganizerJsonDbConverter::jsonDbRequestErrorToOrganizerError(QJsonDbRequest::ErrorCode error) const -{ - // TODO: Add more error codes when they are available in jsondb - // currently there is no error code for missing UUID - switch (error) { - case QJsonDbRequest::NoError: - return QOrganizerManager::NoError; - case QJsonDbRequest::MissingObject: - return QOrganizerManager::DoesNotExistError; - case QJsonDbRequest::MissingType: - case QJsonDbRequest::MissingQuery: - case QJsonDbRequest::InvalidLimit: - return QOrganizerManager::BadArgumentError; - case QJsonDbRequest::InvalidPartition: - // FIXME; We propably need to add more finegrained error inspection - // related to partition accesses, now there is only InvalidPartition. - return QOrganizerManager::UnspecifiedError; - case QJsonDbRequest::DatabaseConnectionError: - return QOrganizerManager::UnspecifiedError; - default: - return QOrganizerManager::UnspecifiedError; - } -} - -bool QOrganizerJsonDbConverter::jsonDbObjectToItem(const QJsonObject &object, QOrganizerItem *item, QOrganizerJsonDbEngine::StorageLocation storageLocation) const -{ - QJsonObject objectToParse; - - // must handle type before reaching the loop - QString jsonDbType = object.value(QOrganizerJsonDbStr::jsonDbType()).toString(); - if (jsonDbType == QOrganizerJsonDbStr::jsonDbEventType()) { - item->setType(QOrganizerItemType::TypeEvent); - } else if (jsonDbType == QOrganizerJsonDbStr::jsonDbEventOccurrenceType()) { - item->setType(QOrganizerItemType::TypeEventOccurrence); - } else if (jsonDbType == QOrganizerJsonDbStr::jsonDbEventViewType()) { - // the data is stored in the "value" field, so dirty code here ;) - objectToParse = object.value(QOrganizerJsonDbStr::jsonDbValue()).toObject(); - if (!objectToParse.value("isVisible").toBool()) - return false; - objectToParse.insert(QOrganizerJsonDbStr::jsonDbUuid(), object.value(QOrganizerJsonDbStr::jsonDbUuid())); - item->setType(QOrganizerItemType::TypeEvent); - item->setData(QOrganizerJsonDbStr::eventIsSynthetic(), true); - } else if (jsonDbType == QOrganizerJsonDbStr::jsonDbTodoType()) { - item->setType(QOrganizerItemType::TypeTodo); - } else if (jsonDbType == QOrganizerJsonDbStr::jsonDbTodoOccurrenceType()) { - item->setType(QOrganizerItemType::TypeTodoOccurrence); - } else { - return false; - } - - if (objectToParse.isEmpty()) - objectToParse = object; - - // other mandatory fields - bool hasCollectionId(false); - bool hasGuid(false); - bool hasItemId(false); - bool hasItemVersion(false); - - // go through all fields - QJsonObject::const_iterator i = objectToParse.constBegin(); - while (i != objectToParse.constEnd()) { - if (i.key() == QOrganizerJsonDbStr::jsonDbUuid()) { - QString jsonDbUuid = i.value().toString(); - if (jsonDbUuid.isEmpty()) - return false; - QOrganizerJsonDbItemId *jsondbItemId = new QOrganizerJsonDbItemId(); - jsondbItemId->setJsonDbUuid(jsonDbUuid); - jsondbItemId->setStorageLocation(storageLocation); - item->setId(QOrganizerItemId(jsondbItemId)); - hasItemId = true; - } else if (i.key() == QOrganizerJsonDbStr::itemCollectionUuid()) { - QString jsonDbCollectionIdStr = i.value().toString(); - if (jsonDbCollectionIdStr.isEmpty()) - return false; - - QOrganizerJsonDbCollectionId *jsondbCollId = new QOrganizerJsonDbCollectionId(); - jsondbCollId->setJsonDbUuid(jsonDbCollectionIdStr); - jsondbCollId->setStorageLocation(storageLocation); - item->setCollectionId(QOrganizerCollectionId(jsondbCollId)); - hasCollectionId = true; - - } else if (i.key() == QOrganizerJsonDbStr::itemGuid()) { - QString guid = i.value().toString(); - if (guid.isEmpty()) - return false; - item->setGuid(guid); - hasGuid = true; - } else if (i.key() == QOrganizerJsonDbStr::itemDisplayName()) { - QString displayLabel = i.value().toString(); - if (!displayLabel.isEmpty()) - item->setDisplayLabel(displayLabel); - } else if (i.key() == QOrganizerJsonDbStr::itemDescription()) { - QString description = i.value().toString(); - if (!description.isEmpty()) - item->setDescription(description); - } else if (i.key() == QOrganizerJsonDbStr::itemComments()) { - QJsonArray array = i.value().toArray(); - if (!array.isEmpty()) { - QStringList comments; - for (int j = 0; j < array.size(); ++j) { - QString comment = array.at(j).toString(); - if (!comment.isEmpty()) - comments.append(comment); - } - if (!comments.isEmpty()) - item->setComments(comments); - } - } else if (i.key() == QOrganizerJsonDbStr::itemTags()) { - QJsonArray array = i.value().toArray(); - if (!array.isEmpty()) { - QStringList tags; - for (int j = 0; j < array.size(); ++j) { - QString tag = array.at(j).toString(); - if (!tag.isEmpty()) - tags.append(tag); - } - if (!tags.isEmpty()) - item->setTags(tags); - } - } else if (i.key() == QOrganizerJsonDbStr::itemPriority()) { - QString jsonDbPriority = i.value().toString(); - if (!jsonDbPriority.isEmpty()) { - QOrganizerItemPriority priority; - priority.setPriority(static_cast<QOrganizerItemPriority::Priority>(stringToEnum(organizerPriorityEnumMap(), jsonDbPriority))); - item->saveDetail(&priority); - } - } else if (i.key() == QOrganizerJsonDbStr::itemRecurrenceRules()) { - QSet<QOrganizerRecurrenceRule> recurrenceRules; - QJsonArray jsonDbRecurrenceRules = i.value().toArray(); - foreach (const QJsonValue &jsonDbRecurrenceRule, jsonDbRecurrenceRules) { - QOrganizerRecurrenceRule rule; - jsonDbObjectToRecurrenceRule(jsonDbRecurrenceRule.toObject(), &rule); - recurrenceRules.insert(rule); - } - - if (!recurrenceRules.isEmpty()) { - QOrganizerItemRecurrence recurrence = item->detail(QOrganizerItemDetail::TypeRecurrence); - recurrence.setRecurrenceRules(recurrenceRules); - item->saveDetail(&recurrence); - } - } else if (i.key() == QOrganizerJsonDbStr::itemExceptionRules()) { - QSet<QOrganizerRecurrenceRule> exceptionRules; - QJsonArray jsonDbExceptionRules = i.value().toArray(); - foreach (const QJsonValue &jsonDbExceptionRule, jsonDbExceptionRules) { - QOrganizerRecurrenceRule rule; - jsonDbObjectToRecurrenceRule(jsonDbExceptionRule.toObject(), &rule); - exceptionRules.insert(rule); - } - - if (!exceptionRules.isEmpty()) { - QOrganizerItemRecurrence recurrence = item->detail(QOrganizerItemDetail::TypeRecurrence); - recurrence.setExceptionRules(exceptionRules); - item->saveDetail(&recurrence); - } - } else if (i.key() == QOrganizerJsonDbStr::itemRecurrenceDates()) { - QSet<QDate> recurrenceDates; - QJsonArray jsonDbRecurrenceDates = i.value().toArray(); - foreach (const QJsonValue &jsonDbRecurrenceDate, jsonDbRecurrenceDates) { - QDate date = QDate::fromString(jsonDbRecurrenceDate.toString(), Qt::ISODate); - if (date.isValid()) - recurrenceDates.insert(date); - } - - if (!recurrenceDates.isEmpty()) { - QOrganizerItemRecurrence recurrence = item->detail(QOrganizerItemDetail::TypeRecurrence); - recurrence.setRecurrenceDates(recurrenceDates); - item->saveDetail(&recurrence); - } - } else if (i.key() == QOrganizerJsonDbStr::itemExceptionDates()) { - QSet<QDate> exceptionDates; - QJsonArray jsonDbExceptionDates = i.value().toArray(); - foreach (const QJsonValue &jsonDbExceptionDate, jsonDbExceptionDates) { - QDate date = QDate::fromString(jsonDbExceptionDate.toString(), Qt::ISODate); - if (date.isValid()) - exceptionDates.insert(date); - } - - if (!exceptionDates.isEmpty()) { - QOrganizerItemRecurrence recurrence = item->detail(QOrganizerItemDetail::TypeRecurrence); - recurrence.setExceptionDates(exceptionDates); - item->saveDetail(&recurrence); - } - } else if (i.key() == QOrganizerJsonDbStr::eventStartDateTime()) { - // EventStartDateTime is the same as TodoStartDateTime, thus a "hack" here ;) - QDateTime startTime = QDateTime::fromString(i.value().toString(), Qt::ISODate); - if (startTime.isValid()) { - if (item->type() == QOrganizerItemType::TypeEvent - || item->type() == QOrganizerItemType::TypeEventOccurrence) { - QOrganizerEventTime eventTime = item->detail(QOrganizerItemDetail::TypeEventTime); - eventTime.setStartDateTime(startTime); - item->saveDetail(&eventTime); - } else if (item->type() == QOrganizerItemType::TypeTodo - || item->type() == QOrganizerItemType::TypeTodoOccurrence) { - QOrganizerTodoTime todoTime = item->detail(QOrganizerItemDetail::TypeTodoTime); - todoTime.setStartDateTime(startTime); - item->saveDetail(&todoTime); - } - } - } else if (i.key() == QOrganizerJsonDbStr::eventEndDateTime()) { - QDateTime endTime = QDateTime::fromString(i.value().toString(), Qt::ISODate); - if (endTime.isValid()) { - QOrganizerEventTime eventTime = item->detail(QOrganizerItemDetail::TypeEventTime); - eventTime.setEndDateTime(endTime); - item->saveDetail(&eventTime); - } - } else if (i.key() == QOrganizerJsonDbStr::todoDueDateTime()) { - QDateTime dueTime = QDateTime::fromString(i.value().toString(), Qt::ISODate); - if (dueTime.isValid()) { - QOrganizerTodoTime todoTime = item->detail(QOrganizerItemDetail::TypeTodoTime); - todoTime.setDueDateTime(dueTime); - item->saveDetail(&todoTime); - } - } else if (i.key() == QOrganizerJsonDbStr::eventIsAllDay()) { - // EventIsAllDay is the same as TodoIsAllDay, thus a "hack" here ;) - bool isAllDay = i.value().toBool(); - if (item->type() == QOrganizerItemType::TypeEvent || item->type() == QOrganizerItemType::TypeEventOccurrence) { - QOrganizerEventTime eventTime = item->detail(QOrganizerItemDetail::TypeEventTime); - eventTime.setAllDay(isAllDay); - item->saveDetail(&eventTime); - } else if (item->type() == QOrganizerItemType::TypeTodo || item->type() == QOrganizerItemType::TypeTodoOccurrence) { - QOrganizerTodoTime todoTime = item->detail(QOrganizerItemDetail::TypeTodoTime); - todoTime.setAllDay(isAllDay); - item->saveDetail(&todoTime); - } - } else if (i.key() == QOrganizerJsonDbStr::eventAttendees()) { - QJsonArray jsonDbAttendees = i.value().toArray(); - foreach (const QJsonValue &jsonDbAttendee, jsonDbAttendees) { - QOrganizerEventAttendee attendee; - jsonDbObjectToAttendeeDetail(jsonDbAttendee.toObject(), &attendee); - if (!attendee.isEmpty()) - item->saveDetail(&attendee); - } - } else if (i.key() == QOrganizerJsonDbStr::eventRsvp()) { - QJsonObject jsonDbRsvp = i.value().toObject(); - if (!jsonDbRsvp.isEmpty()) { - // custom fields are supported for RSVP - QOrganizerEventRsvp rsvp; - QOrganizerItemExtendedDetail extendedDetail; - jsonDbObjectToRsvpDetail(jsonDbRsvp, &rsvp, &extendedDetail); - if (!rsvp.isEmpty()) - item->saveDetail(&rsvp); - if (!extendedDetail.isEmpty()) - item->saveDetail((&extendedDetail)); - } - } else if (i.key() == QOrganizerJsonDbStr::itemOccurrenceParent()) { - QOrganizerItemParent parentDetail = item->detail(QOrganizerItemDetail::TypeParent); - parentDetail.setParentId(QOrganizerItemId(new QOrganizerJsonDbItemId(i.value().toString()))); - item->saveDetail(&parentDetail); - } else if (i.key() == QOrganizerJsonDbStr::itemOccurrenceOriginalDate()) { - QDate originalDate = QDate::fromString(i.value().toString(), Qt::ISODate); - if (originalDate.isValid()) { - QOrganizerItemParent parentDetail = item->detail(QOrganizerItemDetail::TypeParent); - parentDetail.setOriginalDate(originalDate); - item->saveDetail(&parentDetail); - } - } else if (i.key() == QOrganizerJsonDbStr::itemReminder()) { - QJsonObject jsonDbReminder = i.value().toObject(); - if (!jsonDbReminder.isEmpty()) { - // custom fields are supported for reminders - QOrganizerItemAudibleReminder audibleReminder; - QOrganizerItemExtendedDetail extendedDetail; - jsonDbObjectToAudibleReminderDetail(jsonDbReminder, &audibleReminder, &extendedDetail); - if (!audibleReminder.isEmpty()) - item->saveDetail(&audibleReminder); - if (!extendedDetail.isEmpty()) - item->saveDetail((&extendedDetail)); - } - } else if (i.key() == QOrganizerJsonDbStr::eventLocation()) { - QJsonObject jsonDbLocation = i.value().toObject(); - if (!jsonDbLocation.isEmpty()) { - // custom fields are supported for reminders - QOrganizerItemLocation location; - QOrganizerItemExtendedDetail extendedDetail; - jsonDbObjectToLocationDetail(jsonDbLocation, &location, &extendedDetail); - if (!location.isEmpty()) - item->saveDetail(&location); - if (!extendedDetail.isEmpty()) - item->saveDetail((&extendedDetail)); - } - } else if (i.key() == QOrganizerJsonDbStr::jsonDbVersion()) { - QOrganizerItemVersion itemVersion; - jsonDbVersionToItemVersion(i.value().toString(), &itemVersion); - if (!itemVersion.isEmpty()) { - item->saveDetail(&itemVersion); - hasItemVersion = true; - } - } else if (i.key() == QOrganizerJsonDbStr::todoFinishedDateTime()) { - QDateTime finishedDateTime = QDateTime::fromString(i.value().toString(), Qt::ISODate); - if (finishedDateTime.isValid()) { - QOrganizerTodoProgress todoProgress = item->detail(QOrganizerItemDetail::TypeTodoProgress); - todoProgress.setFinishedDateTime(finishedDateTime); - item->saveDetail(&todoProgress); - } - } else if (i.key() == QOrganizerJsonDbStr::todoProgressPercentage()) { - int progressPercentage = i.value().toDouble(); - if (progressPercentage >= 0 && progressPercentage <= 100) { - QOrganizerTodoProgress todoProgress = item->detail(QOrganizerItemDetail::TypeTodoProgress); - todoProgress.setPercentageComplete(progressPercentage); - item->saveDetail(&todoProgress); - } - } else if (i.key() == QOrganizerJsonDbStr::todoStatus()) { - QOrganizerTodoProgress::Status todoStatus = - static_cast<QOrganizerTodoProgress::Status>(stringToEnum(organizerTodoStatusMap(), i.value().toString())); - QOrganizerTodoProgress todoProgress = item->detail(QOrganizerItemDetail::TypeTodoProgress); - todoProgress.setStatus(todoStatus); - item->saveDetail(&todoProgress); - } else if (i.key() == QOrganizerJsonDbStr::jsonDbType()) { - // skip already handled before the loop - } else if (i.key().at(0) == QChar('_')) { - // skip as it's used internally - } else { - // TODO any other fields to filter? - QOrganizerItemExtendedDetail extendedDetail; - extendedDetail.setName(i.key()); - extendedDetail.setData(i.value().toVariant()); - item->saveDetail(&extendedDetail); - } - ++i; - } - - // view object is guaranteed to be correct when generated, and missing several mandatory fields as nomral objects - if (jsonDbType == QOrganizerJsonDbStr::jsonDbEventViewType()) - return true; - - return hasCollectionId && hasGuid && hasItemId && hasItemVersion; -} - -bool QOrganizerJsonDbConverter::itemToJsonDbObject(const QOrganizerItem &item, QJsonObject *object) const -{ - const QList<QOrganizerItemDetail> details = item.details(); - - // the first detail should always be item type - QOrganizerItemType::ItemType itemType = static_cast<QOrganizerItemType::ItemType>(details.at(0).value(QOrganizerItemType::FieldType).toInt()); - switch (itemType) { - case QOrganizerItemType::TypeEvent: - object->insert(QOrganizerJsonDbStr::jsonDbType(), QOrganizerJsonDbStr::jsonDbEventType()); - break; - - case QOrganizerItemType::TypeEventOccurrence: - object->insert(QOrganizerJsonDbStr::jsonDbType(), QOrganizerJsonDbStr::jsonDbEventOccurrenceType()); - break; - - case QOrganizerItemType::TypeTodo: - object->insert(QOrganizerJsonDbStr::jsonDbType(), QOrganizerJsonDbStr::jsonDbTodoType()); - break; - - case QOrganizerItemType::TypeTodoOccurrence: - object->insert(QOrganizerJsonDbStr::jsonDbType(), QOrganizerJsonDbStr::jsonDbTodoOccurrenceType()); - break; - -// case QOrganizerItemType::TypeUndefined: -// case QOrganizerItemType::TypeJournal: -// case QOrganizerItemType::TypeNote: - default: - return false; - } - - // item ID - if (!item.id().isNull()) - object->insert(QOrganizerJsonDbStr::jsonDbUuid(), QOrganizerJsonDbItemId(item.id().toString()).jsondbUuid()); - - // collection ID has already been generated in QOrganizerJsonDbRequestThread::handleItemSaveRequest() if needed - if (!item.collectionId().isNull()) - object->insert(QOrganizerJsonDbStr::itemCollectionUuid(), QOrganizerJsonDbCollectionId(item.collectionId().toString()).jsondbUuid()); - - // certain details that allow multiple instances - QJsonArray comments; - QJsonArray tags; - QJsonArray attendees; - - // go through all the supported details - for (int i = 1; i < details.size(); ++i) { - switch (details.at(i).type()) { - case QOrganizerItemDetail::TypeComment: { - QString comment = details.at(i).value(QOrganizerItemComment::FieldComment).toString(); - if (!comment.isEmpty()) - comments.append(comment); - break; - } - - case QOrganizerItemDetail::TypeDescription: { - QString description = details.at(i).value(QOrganizerItemDescription::FieldDescription).toString(); - if (!description.isEmpty()) - object->insert(QOrganizerJsonDbStr::itemDescription(), description); - break; - } - - case QOrganizerItemDetail::TypeDisplayLabel: { - QString displayLabel = details.at(i).value(QOrganizerItemDisplayLabel::FieldLabel).toString(); - if (!displayLabel.isEmpty()) - object->insert(QOrganizerJsonDbStr::itemDisplayName(), displayLabel); - break; - } - - case QOrganizerItemDetail::TypeExtendedDetail: { - QString name = details.at(i).value(QOrganizerItemExtendedDetail::FieldName).toString(); - if (name.isEmpty()) - break; - - QJsonValue data = QJsonValue::fromVariant(details.at(i).value(QOrganizerItemExtendedDetail::FieldData)); - if (data.isNull()) - break; - - // custom fields are allowed for reminder, rsvp, and location - // in such cases, those values in extended details will be merged with reminder (or other) object in JsonDb - // for all other cases, the extended detail is stored as "name: data" in JsonDb - if (name == QOrganizerJsonDbStr::itemReminder() - || ((itemType == QOrganizerItemType::TypeEvent || itemType == QOrganizerItemType::TypeEventOccurrence) - && (name == QOrganizerJsonDbStr::eventRsvp() || name == QOrganizerJsonDbStr::eventLocation()))) { - if (!data.isObject()) - break; - - QJsonObject existing = object->value(name).toObject(); - if (existing.isEmpty()) { - object->insert(name, data); - } else { - // combining the existing value and the value from the extended detail - QJsonObject::const_iterator i = existing.constBegin(); - QJsonObject newExtendedDetailProperty = data.toObject(); - while (i != existing.constEnd()) { - newExtendedDetailProperty.insert(i.key(), i.value()); - ++i; - } - object->insert(name, newExtendedDetailProperty); - } - break; - } - - - object->insert(name, data); - break; - } - - case QOrganizerItemDetail::TypeGuid: - // GUID has already been generated in QOrganizerJsonDbRequestThread::handleItemSaveRequest() if needed - object->insert(QOrganizerJsonDbStr::itemGuid(), details.at(i).value(QOrganizerItemGuid::FieldGuid).toString()); - break; - - case QOrganizerItemDetail::TypeLocation: { - // in JsonDb, only events can have locations - if (itemType != QOrganizerItemType::TypeEvent && itemType != QOrganizerItemType::TypeEventOccurrence) - break; - QJsonObject jsonDbLocation; - locationDetailToJsonDbObject(details.at(i), &jsonDbLocation); - if (!jsonDbLocation.isEmpty()) { - // check for possible custom fields - QJsonObject location = object->value(QOrganizerJsonDbStr::eventLocation()).toObject(); - if (location.isEmpty()) { - object->insert(QOrganizerJsonDbStr::eventLocation(), jsonDbLocation); - } else { - QJsonObject::const_iterator i = jsonDbLocation.constBegin(); - while (i != jsonDbLocation.constEnd()) { - location.insert(i.key(), i.value()); - ++i; - } - object->insert(QOrganizerJsonDbStr::eventLocation(), location); - } - } - break; - } - - case QOrganizerItemDetail::TypePriority: { - if (!details.at(i).isEmpty()) { - object->insert(QOrganizerJsonDbStr::itemPriority(), - enumToString(organizerPriorityEnumMap(), - static_cast<QOrganizerItemPriority::Priority>(details.at(i).value(QOrganizerItemPriority::FieldPriority).toInt()))); - } - break; - } - - case QOrganizerItemDetail::TypeRecurrence: { - if (itemType != QOrganizerItemType::TypeEvent && itemType != QOrganizerItemType::TypeTodo) - break; - const QMap<int, QVariant> values = details.at(i).values(); - QMap<int, QVariant>::const_iterator j = values.constBegin(); - while (j != values.constEnd()) { - switch (j.key()) { - case QOrganizerItemRecurrence::FieldExceptionDates: { - QJsonArray exceptionDates; - QSet<QDate> dates = j.value().value<QSet<QDate> >(); - foreach (const QDate &date, dates) { - if (date.isValid()) - exceptionDates.append(date.toString(Qt::ISODate)); - } - if (!exceptionDates.isEmpty()) - object->insert(QOrganizerJsonDbStr::itemExceptionDates(), exceptionDates); - break; - } - case QOrganizerItemRecurrence::FieldRecurrenceDates: { - QJsonArray recurrenceDates; - QSet<QDate> dates = j.value().value<QSet<QDate> >(); - foreach (const QDate &date, dates) { - if (date.isValid()) - recurrenceDates.append(date.toString(Qt::ISODate)); - } - if (!recurrenceDates.isEmpty()) - object->insert(QOrganizerJsonDbStr::itemRecurrenceDates(), recurrenceDates); - break; - } - case QOrganizerItemRecurrence::FieldExceptionRules: { - QJsonArray exceptionRules; - QSet<QOrganizerRecurrenceRule> rules = j.value().value<QSet<QOrganizerRecurrenceRule> >(); - foreach (const QOrganizerRecurrenceRule &rule, rules) { - QJsonObject exceptionRuleObject; - recurrenceRuleToJsonDbObject(rule, &exceptionRuleObject); - if (!exceptionRuleObject.isEmpty()) - exceptionRules.append(exceptionRuleObject); - } - if (!exceptionRules.isEmpty()) - object->insert(QOrganizerJsonDbStr::itemExceptionRules(), exceptionRules); - break; - } - case QOrganizerItemRecurrence::FieldRecurrenceRules: { - QJsonArray recurrenceRules; - QSet<QOrganizerRecurrenceRule> rules = j.value().value<QSet<QOrganizerRecurrenceRule> >(); - foreach (const QOrganizerRecurrenceRule &rule, rules) { - QJsonObject recurrenceRuleObject; - recurrenceRuleToJsonDbObject(rule, &recurrenceRuleObject); - if (!recurrenceRuleObject.isEmpty()) - recurrenceRules.append(recurrenceRuleObject); - } - if (!recurrenceRules.isEmpty()) - object->insert(QOrganizerJsonDbStr::itemRecurrenceRules(), recurrenceRules); - break; - } - default: - break; - } - ++j; - } - break; - } - - case QOrganizerItemDetail::TypeTag: { - QString tag = details.at(i).value(QOrganizerItemTag::FieldTag).toString(); - if (!tag.isEmpty()) - tags.append(tag); - break; - } - - case QOrganizerItemDetail::TypeAudibleReminder: { - QJsonObject jsonDbAudibleReminder; - audibleReminderDetailToJsonDbObject(details.at(i), &jsonDbAudibleReminder); - if (!jsonDbAudibleReminder.isEmpty()) { - // check for possible custom fields - QJsonObject reminder = object->value(QOrganizerJsonDbStr::itemReminder()).toObject(); - if (reminder.isEmpty()) { - object->insert(QOrganizerJsonDbStr::itemReminder(), jsonDbAudibleReminder); - } else { - QJsonObject::const_iterator i = jsonDbAudibleReminder.constBegin(); - while (i != jsonDbAudibleReminder.constEnd()) { - reminder.insert(i.key(), i.value()); - ++i; - } - object->insert(QOrganizerJsonDbStr::itemReminder(), reminder); - } - } - break; - } - - case QOrganizerItemDetail::TypeVersion: { - QString jsonDbVersion; - itemVersionToJsonDbVersion(details.at(i), &jsonDbVersion); - if (!jsonDbVersion.isEmpty()) - object->insert(QOrganizerJsonDbStr::jsonDbVersion(), jsonDbVersion); - break; - } - - case QOrganizerItemDetail::TypeEventAttendee: { - if (itemType != QOrganizerItemType::TypeEvent && itemType != QOrganizerItemType::TypeEventOccurrence) - break; - QJsonObject jsonDbAttendee; - attendeeDetailToJsonDbObject(details.at(i), &jsonDbAttendee); - if (!jsonDbAttendee.isEmpty()) - attendees.append(jsonDbAttendee); - break; - } - - case QOrganizerItemDetail::TypeEventRsvp: { - if (itemType != QOrganizerItemType::TypeEvent && itemType != QOrganizerItemType::TypeEventOccurrence) - break; - QJsonObject jsonDbRsvp; - rsvpDetailToJsonDbObject(details.at(i), &jsonDbRsvp); - if (!jsonDbRsvp.isEmpty()) { - // check for possible custom fields - QJsonObject rsvp = object->value(QOrganizerJsonDbStr::eventRsvp()).toObject(); - if (rsvp.isEmpty()) { - object->insert(QOrganizerJsonDbStr::eventRsvp(), jsonDbRsvp); - } else { - QJsonObject::const_iterator i = jsonDbRsvp.constBegin(); - while (i != jsonDbRsvp.constEnd()) { - rsvp.insert(i.key(), i.value()); - ++i; - } - object->insert(QOrganizerJsonDbStr::eventRsvp(), rsvp); - } - } - break; - } - - case QOrganizerItemDetail::TypeParent: { - if (itemType != QOrganizerItemType::TypeEventOccurrence && itemType != QOrganizerItemType::TypeTodoOccurrence) - break; - const QMap<int, QVariant> values = details.at(i).values(); - QMap<int, QVariant>::const_iterator j = values.constBegin(); - while (j != values.constEnd()) { - switch (j.key()) { - case QOrganizerItemParent::FieldParentId: { - QOrganizerItemId parentId = j.value().value<QOrganizerItemId>(); - if (!parentId.isNull()) { - object->insert(QOrganizerJsonDbStr::itemOccurrenceParent(), QOrganizerManagerEngine::engineItemId(parentId)->toString()); - break; - } - } - case QOrganizerItemParent::FieldOriginalDate: { - QDate originalDate = j.value().toDate(); - if (originalDate.isValid()) - object->insert(QOrganizerJsonDbStr::itemOccurrenceOriginalDate(), originalDate.toString(Qt::ISODate)); - break; - } - default: - break; - } - ++j; - } - break; - } - - case QOrganizerItemDetail::TypeEventTime: { - if (itemType != QOrganizerItemType::TypeEvent && itemType != QOrganizerItemType::TypeEventOccurrence) - break; - const QMap<int, QVariant> values = details.at(i).values(); - QMap<int, QVariant>::const_iterator j = values.constBegin(); - while (j != values.constEnd()) { - switch (j.key()) { - case QOrganizerEventTime::FieldStartDateTime: { - QDateTime startDateTime = j.value().toDateTime(); - if (startDateTime.isValid()) - object->insert(QOrganizerJsonDbStr::eventStartDateTime(), startDateTime.toUTC().toString(Qt::ISODate)); - break; - } - case QOrganizerEventTime::FieldEndDateTime: { - QDateTime endDateTime = j.value().toDateTime(); - if (endDateTime.isValid()) - object->insert(QOrganizerJsonDbStr::eventEndDateTime(), endDateTime.toUTC().toString(Qt::ISODate)); - break; - } - case QOrganizerEventTime::FieldAllDay: { - QVariant isAllDay = j.value(); - if (isAllDay.canConvert(QVariant::Bool)) - object->insert(QOrganizerJsonDbStr::eventIsAllDay(), isAllDay.toBool()); - break; - } - default: - break; - } - ++j; - } - break; - } - - case QOrganizerItemDetail::TypeTodoTime: { - if (itemType != QOrganizerItemType::TypeTodo && itemType != QOrganizerItemType::TypeTodoOccurrence) - break; - const QMap<int, QVariant> values = details.at(i).values(); - QMap<int, QVariant>::const_iterator j = values.constBegin(); - while (j != values.constEnd()) { - switch (j.key()) { - case QOrganizerTodoTime::FieldStartDateTime: { - QDateTime startDateTime = j.value().toDateTime(); - if (startDateTime.isValid()) - object->insert(QOrganizerJsonDbStr::todoStartDateTime(), startDateTime.toUTC().toString(Qt::ISODate)); - break; - } - case QOrganizerTodoTime::FieldDueDateTime: { - QDateTime dueDateTime = j.value().toDateTime(); - if (dueDateTime.isValid()) - object->insert(QOrganizerJsonDbStr::todoDueDateTime(), dueDateTime.toUTC().toString(Qt::ISODate)); - break; - } - case QOrganizerTodoTime::FieldAllDay: { - QVariant isAllDay = j.value(); - if (isAllDay.canConvert(QVariant::Bool)) - object->insert(QOrganizerJsonDbStr::todoIsAllDay(), isAllDay.toBool()); - break; - } - default: - break; - } - ++j; - } - break; - } - - case QOrganizerItemDetail::TypeTodoProgress: { - if (itemType != QOrganizerItemType::TypeTodo && itemType != QOrganizerItemType::TypeTodoOccurrence) - break;const QMap<int, QVariant> values = details.at(i).values(); - QMap<int, QVariant>::const_iterator j = values.constBegin(); - while (j != values.constEnd()) { - switch (j.key()) { - case QOrganizerTodoProgress::FieldFinishedDateTime: { - QDateTime finishedDateTime = j.value().toDateTime(); - if (finishedDateTime.isValid()) - object->insert(QOrganizerJsonDbStr::todoFinishedDateTime(), finishedDateTime.toUTC().toString(Qt::ISODate)); - break; - } - case QOrganizerTodoProgress::FieldPercentageComplete: { - int percentageComplete = j.value().toInt(); - if (percentageComplete >= 0 && percentageComplete <= 100) - object->insert(QOrganizerJsonDbStr::todoProgressPercentage(), percentageComplete); - break; - } - case QOrganizerTodoProgress::FieldStatus: { - object->insert(QOrganizerJsonDbStr::todoStatus(), - enumToString(organizerTodoStatusMap(), j.value().toInt())); - break; - } - default: - break; - } - ++j; - } - break; - } - -// case QOrganizerItemDetail::TypeUndefined: -// case QOrganizerItemDetail::TypeClassification: -// case QOrganizerItemDetail::TypeItemType: -// case QOrganizerItemDetail::TypeTimestamp: -// case QOrganizerItemDetail::TypeReminder: -// case QOrganizerItemDetail::TypeEmailReminder: -// case QOrganizerItemDetail::TypeVisualReminder: -// case QOrganizerItemDetail::TypeJournalTime: - default: - break; - } - } - - if (!comments.isEmpty()) - object->insert(QOrganizerJsonDbStr::itemComments(), comments); - - if (!tags.isEmpty()) - object->insert(QOrganizerJsonDbStr::itemTags(), tags); - - if (!attendees.isEmpty()) - object->insert(QOrganizerJsonDbStr::eventAttendees(), attendees); - - return true; -} - -void QOrganizerJsonDbConverter::attendeeDetailToJsonDbObject(const QOrganizerEventAttendee &attendeeDetail, QJsonObject *object) const -{ - const QMap<int, QVariant> detailValues = attendeeDetail.values(); - QMap<int, QVariant>::const_iterator i = detailValues.constBegin(); - while (i != detailValues.constEnd()) { - if (i.key() == QOrganizerEventAttendee::FieldName) { - QString name = i.value().toString(); - if (!name.isEmpty()) - object->insert(QOrganizerJsonDbStr::eventAttendeeName(), name); - } else if (i.key() == QOrganizerEventAttendee::FieldEmailAddress) { - QString email = i.value().toString(); - if (!email.isEmpty()) - object->insert(QOrganizerJsonDbStr::eventAttendeeEmailAddress(), email); - } else if (i.key() == QOrganizerEventAttendee::FieldAttendeeId) { - QString id = i.value().toString(); - if (!id.isEmpty()) - object->insert(QOrganizerJsonDbStr::eventAttendeeUuid(), id); - } else if (i.key() == QOrganizerEventAttendee::FieldParticipationRole) { - object->insert(QOrganizerJsonDbStr::eventAttendeeParticipationRole(), - enumToString(organizerParticipationRoleMap(), i.value().toInt())); - } else if (i.key() == QOrganizerEventAttendee::FieldParticipationStatus) { - object->insert(QOrganizerJsonDbStr::eventAttendeeParticipationStatus(), - enumToString(organizerParticipationStatusMap(), i.value().toInt())); - } - ++i; - } -} - -void QOrganizerJsonDbConverter::jsonDbObjectToAttendeeDetail(const QJsonObject &object, QOrganizerEventAttendee *attendeeDetail) const -{ - QJsonObject::const_iterator i = object.constBegin(); - QString value; - while (i != object.constEnd()) { - if (i.key() == QOrganizerJsonDbStr::eventAttendeeName()) { - value = i.value().toString(); - if (!value.isEmpty()) - attendeeDetail->setName(value); - } else if (i.key() == QOrganizerJsonDbStr::eventAttendeeEmailAddress()) { - value = i.value().toString(); - if (!value.isEmpty()) - attendeeDetail->setEmailAddress(value); - } else if (i.key() == QOrganizerJsonDbStr::eventAttendeeUuid()) { - value = i.value().toString(); - if (!value.isEmpty()) - attendeeDetail->setAttendeeId(value); - } else if (i.key() == QOrganizerJsonDbStr::eventAttendeeParticipationRole()) { - int intValue = stringToEnum(organizerParticipationRoleMap(), i.value().toString()); - attendeeDetail->setParticipationRole(static_cast<QOrganizerEventAttendee::ParticipationRole>(intValue)); - } else if (i.key() == QOrganizerJsonDbStr::eventAttendeeParticipationStatus()) { - int intValue = stringToEnum(organizerParticipationStatusMap(), i.value().toString()); - attendeeDetail->setParticipationStatus(static_cast<QOrganizerEventAttendee::ParticipationStatus>(intValue)); - } - ++i; - } -} - -void QOrganizerJsonDbConverter::rsvpDetailToJsonDbObject(const QOrganizerEventRsvp &rsvpDetail, QJsonObject *object) const -{ - const QMap<int, QVariant> rsvpValues = rsvpDetail.values(); - QMap<int, QVariant>::const_iterator i = rsvpValues.constBegin(); - while (i != rsvpValues.constEnd()) { - if (i.key() == QOrganizerEventRsvp::FieldOrganizerName) { - QString organizerName = i.value().toString(); - if (!organizerName.isEmpty()) - object->insert(QOrganizerJsonDbStr::eventRsvpOrganizerName(), organizerName); - } else if (i.key() == QOrganizerEventRsvp::FieldOrganizerEmail) { - QString organizerEmail = i.value().toString(); - if (!organizerEmail.isEmpty()) - object->insert(QOrganizerJsonDbStr::eventRsvpOrganizerEmail(), organizerEmail); - } else if (i.key() == QOrganizerEventRsvp::FieldResponseDeadline) { - QDate responseDeadline = i.value().toDate(); - if (responseDeadline.isValid()) - object->insert(QOrganizerJsonDbStr::eventRsvpResponseDeadline(), responseDeadline.toString(Qt::ISODate)); - } else if (i.key() == QOrganizerEventRsvp::FieldResponseDate) { - QDate responseDate = i.value().toDate(); - if (responseDate.isValid()) - object->insert(QOrganizerJsonDbStr::eventRsvpResponseDate(), responseDate.toString(Qt::ISODate)); - } else if (i.key() == QOrganizerEventRsvp::FieldParticipationRole) { - object->insert(QOrganizerJsonDbStr::eventRsvpParticipationRole(), - enumToString(organizerParticipationRoleMap(), i.value().toInt())); - } else if (i.key() == QOrganizerEventRsvp::FieldParticipationStatus) { - object->insert(QOrganizerJsonDbStr::eventRsvpParticipationStatus(), - enumToString(organizerParticipationStatusMap(), i.value().toInt())); - } else if (i.key() == QOrganizerEventRsvp::FieldResponseRequirement) { - object->insert(QOrganizerJsonDbStr::eventRsvpResponseRequirement(), - enumToString(organizerResponseRequirementMap(), i.value().toInt())); - } - ++i; - } -} - -void QOrganizerJsonDbConverter::jsonDbObjectToRsvpDetail(const QJsonObject &object, QOrganizerEventRsvp *rsvpDetail, - QOrganizerItemExtendedDetail *extendedDetail) const -{ - QJsonObject::const_iterator i = object.constBegin(); - QVariantMap customFields; - while (i != object.constEnd()) { - if (i.key() == QOrganizerJsonDbStr::eventRsvpOrganizerName()) { - QString value = i.value().toString(); - if (!value.isEmpty()) - rsvpDetail->setOrganizerName(value); - } else if (i.key() == QOrganizerJsonDbStr::eventRsvpOrganizerEmail()) { - QString value = i.value().toString(); - if (!value.isEmpty()) - rsvpDetail->setOrganizerEmail(value); - } else if (i.key() == QOrganizerJsonDbStr::eventRsvpResponseDeadline()) { - QDate date = QDate::fromString(i.value().toString(), Qt::ISODate); - if (date.isValid()) - rsvpDetail->setResponseDeadline(date); - } else if (i.key() == QOrganizerJsonDbStr::eventRsvpResponseDate()) { - QDate date = QDate::fromString(i.value().toString(), Qt::ISODate); - if (date.isValid()) - rsvpDetail->setResponseDate(date); - } else if (i.key() == QOrganizerJsonDbStr::eventRsvpParticipationRole()) { - int intValue = stringToEnum(organizerParticipationRoleMap(), i.value().toString()); - rsvpDetail->setParticipationRole(static_cast<QOrganizerEventAttendee::ParticipationRole>(intValue)); - } else if (i.key() == QOrganizerJsonDbStr::eventRsvpParticipationStatus()) { - int intValue = stringToEnum(organizerParticipationStatusMap(), i.value().toString()); - rsvpDetail->setParticipationStatus(static_cast<QOrganizerEventAttendee::ParticipationStatus>(intValue)); - } else if (i.key() == QOrganizerJsonDbStr::eventRsvpResponseRequirement()) { - int intValue = stringToEnum(organizerResponseRequirementMap(), i.value().toString()); - rsvpDetail->setResponseRequirement(static_cast<QOrganizerEventRsvp::ResponseRequirement>(intValue)); - } else { - customFields.insert(i.key(), i.value().toVariant()); - } - ++i; - } - if (!customFields.isEmpty()) { - extendedDetail->setName(QOrganizerJsonDbStr::eventRsvp()); - extendedDetail->setData(customFields); - } -} - -void QOrganizerJsonDbConverter::locationDetailToJsonDbObject(const QOrganizerItemLocation &locationDetail, QJsonObject *object) const -{ - const QMap<int, QVariant> values = locationDetail.values(); - QMap<int, QVariant>::const_iterator i = values.constBegin(); - QJsonObject jsonDbGeo; - while (i != values.constEnd()) { - switch (i.key()) { - case QOrganizerItemLocation::FieldLabel: { - QString label = i.value().toString(); - if (!label.isEmpty()) - object->insert(QOrganizerJsonDbStr::eventLocationDisplayName(), label); - break; - } - case QOrganizerItemLocation::FieldLatitude: { - QVariant latitude = i.value(); - if (latitude.canConvert(QVariant::Double)) - jsonDbGeo.insert(QOrganizerJsonDbStr::eventLocationGeoLatitude(), latitude.toDouble()); - break; - } - case QOrganizerItemLocation::FieldLongitude: { - QVariant longitude = i.value(); - if (longitude.canConvert(QVariant::Double)) - jsonDbGeo.insert(QOrganizerJsonDbStr::eventLocationGeoLongitude(), longitude.toDouble()); - break; - } - default: - break; - } - ++i; - } - if (!jsonDbGeo.isEmpty()) - object->insert(QOrganizerJsonDbStr::eventLocationGeo(), jsonDbGeo); -} - -void QOrganizerJsonDbConverter::jsonDbObjectToLocationDetail(const QJsonObject &object, QOrganizerItemLocation *locationDetail, - QOrganizerItemExtendedDetail *extendedDetail) const -{ - QJsonObject::const_iterator i = object.constBegin(); - QVariantMap customFields; - while (i != object.constEnd()) { - if (i.key() == QOrganizerJsonDbStr::eventLocationDisplayName()) { - QString label = i.value().toString(); - if (!label.isEmpty()) - locationDetail->setLabel(label); - } else if (i.key() == QOrganizerJsonDbStr::eventLocationGeo()) { - QJsonObject jsonDbGeo = i.value().toObject(); - QJsonObject::const_iterator j = jsonDbGeo.constBegin(); - while (j != jsonDbGeo.constEnd()) { - if (j.key() == QOrganizerJsonDbStr::eventLocationGeoLatitude()) { - if (j.value().isDouble()) - locationDetail->setLatitude(j.value().toDouble()); - } else if (j.key() == QOrganizerJsonDbStr::eventLocationGeoLongitude()) { - if (j.value().isDouble()) - locationDetail->setLongitude(j.value().toDouble()); - } - - ++j; - } - } else { - customFields.insert(i.key(), i.value().toVariant()); - } - - ++i; - } - if (!customFields.isEmpty()) { - extendedDetail->setName(QOrganizerJsonDbStr::eventLocation()); - extendedDetail->setData(customFields); - } -} - -bool QOrganizerJsonDbConverter::jsonDbObjectToCollection(const QJsonObject &object, QOrganizerCollection *collection, bool *isDefaultCollection, QOrganizerJsonDbEngine::StorageLocation storageLocation) const -{ - bool hasCollectionId(false); - - QVariantMap extendedMetaData; - QJsonObject::const_iterator i = object.constBegin(); - while (i != object.constEnd()) { - if (i.key() == QOrganizerJsonDbStr::jsonDbUuid()) { - QString jsonUuid = i.value().toString(); - if (jsonUuid.isEmpty()) - return false; - QOrganizerJsonDbCollectionId *jsondbCollectionId = new QOrganizerJsonDbCollectionId(); - jsondbCollectionId->setJsonDbUuid(jsonUuid); - jsondbCollectionId->setStorageLocation(storageLocation); - collection->setId(QOrganizerCollectionId(jsondbCollectionId)); - hasCollectionId = true; - } else if (i.key() == QOrganizerJsonDbStr::collectionDisplayName()) { - QString name = i.value().toString(); - if (!name.isEmpty()) - collection->setMetaData(QOrganizerCollection::KeyName, name); - } else if (i.key() == QOrganizerJsonDbStr::collectionDescription()) { - QString description = i.value().toString(); - if (!description.isEmpty()) - collection->setMetaData(QOrganizerCollection::KeyDescription, description); - } else if (i.key() == QOrganizerJsonDbStr::collectionColor()) { - QString color = i.value().toString(); - if (!color.isEmpty()) - collection->setMetaData(QOrganizerCollection::KeyColor, color); - } else if (i.key() == QOrganizerJsonDbStr::collectionImageUrl()) { - QString image = i.value().toString(); - if (!image.isEmpty()) - collection->setMetaData(QOrganizerCollection::KeyImage, image); - } else if (i.key() == QOrganizerJsonDbStr::collectionDefaultFlag()) { - if (i.value().isBool()) - *isDefaultCollection = i.value().toBool(); - } else { - // custom meta data - if (i.key().at(0) != QChar('_') && !i.key().isEmpty() && !i.value().isNull()) - extendedMetaData.insert(i.key(), i.value().toVariant()); - } - - ++i; - } - - if (!extendedMetaData.isEmpty()) - collection->setMetaData(QOrganizerCollection::KeyExtended, extendedMetaData); - - return hasCollectionId; -} - -bool QOrganizerJsonDbConverter::collectionToJsonDbObject(const QOrganizerCollection &collection, bool isDefaultCollection, QJsonObject *object) const -{ - QOrganizerCollectionId collectionId = collection.id(); - if (!collectionId.isNull()) { - object->insert(QOrganizerJsonDbStr::jsonDbUuid(), QOrganizerJsonDbCollectionId(collectionId.toString()).jsondbUuid()); - } - - object->insert(QOrganizerJsonDbStr::jsonDbType(), QOrganizerJsonDbStr::jsonDbCollectionType()); - - if (isDefaultCollection) - object->insert(QOrganizerJsonDbStr::collectionDefaultFlag(), isDefaultCollection); - - QMap<QOrganizerCollection::MetaDataKey, QVariant> metaData = collection.metaData(); - QMap<QOrganizerCollection::MetaDataKey, QVariant>::const_iterator i = metaData.constBegin(); - while (i != metaData.constEnd()) { - if (i.key() == QOrganizerCollection::KeyColor) { - QString colorString = i.value().toString(); - if (!colorString.isEmpty()) - object->insert(QOrganizerJsonDbStr::collectionColor(), colorString); - } else if (i.key() == QOrganizerCollection::KeyDescription) { - QString descriptionString = i.value().toString(); - if (!descriptionString.isEmpty()) - object->insert(QOrganizerJsonDbStr::collectionDescription(), descriptionString); - } else if (i.key() == QOrganizerCollection::KeyImage) { - QString imageString = i.value().toString(); - if (!imageString.isEmpty()) - object->insert(QOrganizerJsonDbStr::collectionImageUrl(), imageString); - } else if (i.key() == QOrganizerCollection::KeyName) { - QString displayNameString = i.value().toString(); - if (!displayNameString.isEmpty()) - object->insert(QOrganizerJsonDbStr::collectionDisplayName(), displayNameString); - } else if (i.key() == QOrganizerCollection::KeyExtended) { - QVariantMap variantMap = i.value().toMap(); - if (!variantMap.isEmpty()) { - QVariantMap::const_iterator j = variantMap.constBegin(); - while (j != variantMap.constEnd()) { - QString valueString = j.value().toString(); - if (!j.key().isEmpty() && !valueString.isEmpty() - && (j.key().at(0) != QChar('_') || j.key() == QOrganizerJsonDbStr::jsonDbVersion()) - && j.key() != QOrganizerJsonDbStr::collectionDefaultFlag()) { - // XXX Should we allow complex data structure, i.e. list or map, for custom meta data? - object->insert(j.key(), valueString); - } - ++j; - } - } - } - - ++i; - } - - return true; -} - -void QOrganizerJsonDbConverter::jsonDbVersionToItemVersion(const QString &jsonDbVersion, QOrganizerItemVersion *itemVersion) const -{ - QStringList jsonDbVersions = jsonDbVersion.split(QLatin1Char('-')); - if (jsonDbVersions.size() != 2) - return; - int version = jsonDbVersions.at(0).toInt(); - - if (version > 0) { - itemVersion->setVersion(version); - itemVersion->setExtendedVersion(jsonDbVersions.at(1).toLatin1()); - } -} - -const QStringList QOrganizerJsonDbConverter::storageLocationsFlagToStrings(const QOrganizerJsonDbEngine::StorageLocations storageLocationsFlag) -{ - QStringList storageLocations; - - if (QOrganizerJsonDbEngine::UserDataStorage & storageLocationsFlag) - storageLocations.append(enumToString(organizerStorageLocationMap(), QOrganizerJsonDbEngine::UserDataStorage)); - if (QOrganizerJsonDbEngine::SystemStorage & storageLocationsFlag) - storageLocations.append(enumToString(organizerStorageLocationMap(), QOrganizerJsonDbEngine::SystemStorage)); - - return storageLocations; -} - -QOrganizerJsonDbEngine::StorageLocation QOrganizerJsonDbConverter::storageLocationStringToEnum(const QString &storageLocation) -{ - return QOrganizerJsonDbEngine::StorageLocation(stringToEnum(organizerStorageLocationMap(), storageLocation)); -} - -QOrganizerJsonDbEngine::StorageLocations QOrganizerJsonDbConverter::storageLocationListToFlag(const QList<QOrganizerJsonDbEngine::StorageLocation> storageLocationsList) -{ - QOrganizerJsonDbEngine::StorageLocations locationsFlag(0); - foreach (QOrganizerJsonDbEngine::StorageLocation location, storageLocationsList) { - locationsFlag |= location; - } - return locationsFlag; -} - -void QOrganizerJsonDbConverter::itemVersionToJsonDbVersion(const QOrganizerItemVersion &itemVersion, QString *jsonDbVersion) const -{ - int version = itemVersion.version(); - QByteArray extendedVersion = itemVersion.extendedVersion(); - - if (version > 0) { - *jsonDbVersion = QString::number(version) + QStringLiteral("-") + QString::fromLatin1(extendedVersion.constData()); - } -} - -void QOrganizerJsonDbConverter::jsonDbObjectToRecurrenceRule(const QJsonObject &object, QOrganizerRecurrenceRule *rule) const -{ - QJsonObject::const_iterator i = object.constBegin(); - while (i != object.constEnd()) { - if (i.key() == QOrganizerJsonDbStr::itemRecurrenceRuleFrequency()) { - QString frequency = i.value().toString(); - if (!frequency.isEmpty()) - rule->setFrequency(static_cast<QOrganizerRecurrenceRule::Frequency>(stringToEnum(organizerFrequencyEnumMap(), frequency))); - } else if (i.key() == QOrganizerJsonDbStr::itemRecurrenceRuleInterval()) { - int interval = i.value().toDouble(); - if (interval >= 0) - rule->setInterval(interval); - } else if (i.key() == QOrganizerJsonDbStr::itemRecurrenceRuleLimitCount()) { - int limitCount = i.value().toDouble(); - if (limitCount >= 0) - rule->setLimit(limitCount); - } else if (i.key() == QOrganizerJsonDbStr::itemRecurrenceRuleLimitDate()) { - QDate limitDate = QDate::fromString(i.value().toString(), Qt::ISODate); - if (limitDate.isValid()) - rule->setLimit(limitDate); - } else if (i.key() == QOrganizerJsonDbStr::itemRecurrenceRuleFirstDayOfWeek()) { - QString firstDayOfWeek = i.value().toString(); - if (!firstDayOfWeek.isEmpty()) - rule->setFirstDayOfWeek(static_cast<Qt::DayOfWeek>(stringToEnum(organizerDayEnumMap(), firstDayOfWeek))); - } else if (i.key() == QOrganizerJsonDbStr::itemRecurrenceRulePositions()) { - QJsonArray jsonDbPositions = i.value().toArray(); - if (!jsonDbPositions.isEmpty()) { - QSet<int> positionsSet; - foreach (const QJsonValue &jsonDbPosition, jsonDbPositions) - positionsSet.insert(jsonDbPosition.toDouble()); - rule->setPositions(positionsSet); - } - } else if (i.key() == QOrganizerJsonDbStr::itemRecurrenceRuleDaysOfWeek()) { - QJsonArray jsonDbDaysOfWeek = i.value().toArray(); - if (!jsonDbDaysOfWeek.isEmpty()) { - QSet<Qt::DayOfWeek> daysOfWeek; - foreach (const QJsonValue &jsonDbDayOfWeek, jsonDbDaysOfWeek) - daysOfWeek.insert(static_cast<Qt::DayOfWeek>(stringToEnum(organizerDayEnumMap(), jsonDbDayOfWeek.toString()))); - rule->setDaysOfWeek(daysOfWeek); - } - } else if (i.key() == QOrganizerJsonDbStr::itemRecurrenceRuleDaysOfMonth()) { - QJsonArray jsonDbDaysOfMonth = i.value().toArray(); - if (!jsonDbDaysOfMonth.isEmpty()) { - QSet<int> daysOfMonth; - foreach (const QJsonValue &jsonDbDayOfMonth, jsonDbDaysOfMonth) - daysOfMonth.insert(jsonDbDayOfMonth.toDouble()); - rule->setDaysOfMonth(daysOfMonth); - } - } else if (i.key() == QOrganizerJsonDbStr::itemRecurrenceRuleDaysOfYear()) { - QJsonArray jsonDbDaysOfYear = i.value().toArray(); - if (!jsonDbDaysOfYear.isEmpty()) { - QSet<int> daysOfYear; - foreach (const QJsonValue &jsonDbDayOfYear, jsonDbDaysOfYear) - daysOfYear.insert(jsonDbDayOfYear.toDouble()); - rule->setDaysOfYear(daysOfYear); - } - } else if (i.key() == QOrganizerJsonDbStr::itemRecurrenceRuleWeeksOfYear()) { - QJsonArray jsonDbWeeksOfYear = i.value().toArray(); - if (!jsonDbWeeksOfYear.isEmpty()) { - QSet<int> weeksOfYear; - foreach (const QJsonValue &jsonDbWeekOfYear, jsonDbWeeksOfYear) - weeksOfYear.insert(jsonDbWeekOfYear.toDouble()); - rule->setWeeksOfYear(weeksOfYear); - } - } else if (i.key() == QOrganizerJsonDbStr::itemRecurrenceRuleMonthsOfYear()) { - QJsonArray jsonDbMonthsOfYear = i.value().toArray(); - if (!jsonDbMonthsOfYear.isEmpty()) { - QSet<QOrganizerRecurrenceRule::Month> monthsOfYear; - foreach (const QJsonValue &jsonDbMonthOfYear, jsonDbMonthsOfYear) - monthsOfYear.insert(static_cast<QOrganizerRecurrenceRule::Month>(stringToEnum(organizerMonthEnumMap(), jsonDbMonthOfYear.toString()))); - rule->setMonthsOfYear(monthsOfYear); - } - } - - ++i; - } -} - -void QOrganizerJsonDbConverter::recurrenceRuleToJsonDbObject(const QOrganizerRecurrenceRule &rule, QJsonObject *object) const -{ - // Invalid is the default value, so no need to save - QOrganizerRecurrenceRule::Frequency frequency = rule.frequency(); - if (frequency != QOrganizerRecurrenceRule::Invalid) - object->insert(QOrganizerJsonDbStr::itemRecurrenceRuleFrequency(), enumToString(organizerFrequencyEnumMap(), frequency)); - - // 1 is the default value, so no need to save - int interval = rule.interval(); - if (interval > 1) - object->insert(QOrganizerJsonDbStr::itemRecurrenceRuleInterval(), rule.interval()); - - // only saves the limit value if it's used - QOrganizerRecurrenceRule::LimitType limitType = rule.limitType(); - if (limitType == QOrganizerRecurrenceRule::CountLimit) - object->insert(QOrganizerJsonDbStr::itemRecurrenceRuleLimitCount(), rule.limitCount()); - else if (limitType == QOrganizerRecurrenceRule::DateLimit) - object->insert(QOrganizerJsonDbStr::itemRecurrenceRuleLimitDate(), rule.limitDate().toString(Qt::ISODate)); - - // Monday is the default value, so no need to save - Qt::DayOfWeek firstDayOfWeek = rule.firstDayOfWeek(); - if (firstDayOfWeek != Qt::Monday) - object->insert(QOrganizerJsonDbStr::itemRecurrenceRuleFirstDayOfWeek(), enumToString(organizerDayEnumMap(), firstDayOfWeek)); - - QSet<int> positions = rule.positions(); - if (!positions.isEmpty()) { - QJsonArray positionsList; - foreach (int position, positions) - positionsList.append(position); - object->insert(QOrganizerJsonDbStr::itemRecurrenceRulePositions(), positionsList); - } - - QSet<Qt::DayOfWeek> daysOfWeek = rule.daysOfWeek(); - if (!daysOfWeek.isEmpty()) { - QJsonArray daysOfWeekList; - foreach (Qt::DayOfWeek day, daysOfWeek) - daysOfWeekList.append(enumToString(organizerDayEnumMap(), day)); - object->insert(QOrganizerJsonDbStr::itemRecurrenceRuleDaysOfWeek(), daysOfWeekList); - } - - QSet<int> daysOfMonth = rule.daysOfMonth(); - if (!daysOfMonth.isEmpty()) { - QJsonArray daysOfMonthList; - foreach (int day, daysOfMonth) - daysOfMonthList.append(day); - object->insert(QOrganizerJsonDbStr::itemRecurrenceRuleDaysOfMonth(), daysOfMonthList); - } - - QSet<int> daysOfYear = rule.daysOfYear(); - if (!daysOfYear.isEmpty()) { - QJsonArray daysOfYearList; - foreach (int day, daysOfYear) - daysOfYearList.append(day); - object->insert(QOrganizerJsonDbStr::itemRecurrenceRuleDaysOfYear(), daysOfYearList); - } - - QSet<int> weeksOfYear = rule.weeksOfYear(); - if (!weeksOfYear.isEmpty()) { - QJsonArray weeksOfYearList; - foreach (int week, weeksOfYear) - weeksOfYearList.append(week); - object->insert(QOrganizerJsonDbStr::itemRecurrenceRuleWeeksOfYear(), weeksOfYearList); - } - - QSet<QOrganizerRecurrenceRule::Month> monthsOfYear = rule.monthsOfYear(); - if (!monthsOfYear.isEmpty()) { - QJsonArray monthsOfYearList; - foreach (QOrganizerRecurrenceRule::Month month, monthsOfYear) - monthsOfYearList.append(enumToString(organizerMonthEnumMap(), month)); - object->insert(QOrganizerJsonDbStr::itemRecurrenceRuleMonthsOfYear(), monthsOfYearList); - } -} - -void QOrganizerJsonDbConverter::audibleReminderDetailToJsonDbObject(const QOrganizerItemAudibleReminder &itemReminder, QJsonObject *object) const -{ - const QMap<int, QVariant> reminderValues = itemReminder.values(); - QMap<int, QVariant>::const_iterator i = reminderValues.constBegin(); - while (i != reminderValues.constEnd()) { - if (i.key() == QOrganizerItemAudibleReminder::FieldSecondsBeforeStart) { - int secondsBeforeStart = i.value().toInt(); - if (secondsBeforeStart >= 0) - object->insert(QOrganizerJsonDbStr::itemReminderSecBeforeStart(), secondsBeforeStart); - } else if (i.key() == QOrganizerItemAudibleReminder::FieldRepetitionCount) { - int repetitionCount = i.value().toInt(); - if (repetitionCount > 0) - object->insert(QOrganizerJsonDbStr::itemReminderRepetitionCount(), repetitionCount); - } else if (i.key() == QOrganizerItemAudibleReminder::FieldRepetitionDelay) { - int repetitionDelay = i.value().toInt(); - if (repetitionDelay > 0) - object->insert(QOrganizerJsonDbStr::itemReminderRepetitionDelay(), repetitionDelay); - } else if (i.key() == QOrganizerItemAudibleReminder::FieldDataUrl) { - if (i.value().toUrl().isValid()) - object->insert(QOrganizerJsonDbStr::itemReminderDataUrl(), i.value().toString()); - } - ++i; - } -} - -void QOrganizerJsonDbConverter::jsonDbObjectToAudibleReminderDetail(const QJsonObject &object, QOrganizerItemAudibleReminder *itemReminder, - QOrganizerItemExtendedDetail *extendedDetail) const -{ - QJsonObject::const_iterator i = object.constBegin(); - QVariantMap customFields; - while (i != object.constEnd()) { - if (i.key() == QOrganizerJsonDbStr::itemReminderSecBeforeStart()) { - int seconds = i.value().toDouble(); - if (seconds >= 0) - itemReminder->setValue(QOrganizerItemAudibleReminder::FieldSecondsBeforeStart, seconds); - } else if (i.key() == QOrganizerJsonDbStr::itemReminderRepetitionCount()) { - int repetitionCount = i.value().toDouble(); - if (repetitionCount > 0) - itemReminder->setValue(QOrganizerItemAudibleReminder::FieldRepetitionCount, repetitionCount); - } else if (i.key() == QOrganizerJsonDbStr::itemReminderRepetitionDelay()) { - int repetitionDelay = i.value().toDouble(); - if (repetitionDelay > 0) - itemReminder->setValue(QOrganizerItemAudibleReminder::FieldRepetitionDelay, repetitionDelay); - } else if (i.key() == QOrganizerJsonDbStr::itemReminderDataUrl()) { - QUrl url(i.value().toString()); - if (url.isValid()) - itemReminder->setValue(QOrganizerItemAudibleReminder::FieldDataUrl, url); - } else { - customFields.insert(i.key(), i.value().toVariant()); - } - ++i; - } - if (!customFields.isEmpty()) { - extendedDetail->setName(QOrganizerJsonDbStr::itemReminder()); - extendedDetail->setData(customFields); - } -} - -int QOrganizerJsonDbConverter::stringToEnum(const QOrganizerJsonDbEnumConversionData* const conversionData, const QString &enumStr) const -{ - int i = 0; - while (conversionData[i].enumValue != enumMapEnd) { - if (conversionData[i].enumStr == enumStr) - return conversionData[i].enumValue; - i++; - } - // first index contains default values - return conversionData[0].enumValue; -} - -QString QOrganizerJsonDbConverter::enumToString(const QOrganizerJsonDbEnumConversionData* const conversionData, int enumValue) const -{ - int i = 0; - while (conversionData[i].enumValue != enumMapEnd) { - if (conversionData[i].enumValue == enumValue) - return conversionData[i].enumStr; - i++; - } - // first index contains default values - return conversionData[0].enumStr; -} - -bool QOrganizerJsonDbConverter::compoundFilterToJsondbQuery(const QOrganizerItemFilter &filter, QString *jsonDbQueryStr, int *typeFilterFlag) const -{ - bool isValidFilter = true; - switch (filter.type()) { - case QOrganizerItemFilter::IntersectionFilter: { - const QOrganizerItemIntersectionFilter isf(filter); - const QList<QOrganizerItemFilter> filterList = isf.filters(); - foreach (const QOrganizerItemFilter &filter, filterList){ - //query filter1 filter2 filter3 ... - //query [?definition="value"][?definition="value"][?definition="value"] - QString filterStr; - int subtypeFilterFlag = supportedItemTypeFlag(); - if (compoundFilterToJsondbQuery(filter, &filterStr, &subtypeFilterFlag)) { - *jsonDbQueryStr += filterStr; - *typeFilterFlag = *typeFilterFlag & subtypeFilterFlag; - } else {//For intersection filter, single filter invalid means empty result from jsondb query - isValidFilter = false; - } - } - return isValidFilter; - } - case QOrganizerItemFilter::UnionFilter: { - const QOrganizerItemUnionFilter uf(filter); - const QList<QOrganizerItemFilter> filterList = uf.filters(); - int validFilterCount = 0; - *typeFilterFlag = 0; - foreach (const QOrganizerItemFilter &filter, filterList){ - //query filter1 filter2 filter3 ... - //query [?definition="value" | definition="value" | definition="value"] - QString filterStr; - int subtypeFilterFlag = supportedItemTypeFlag(); - if (compoundFilterToJsondbQuery(filter, &filterStr, &subtypeFilterFlag)) { - *jsonDbQueryStr += filterStr; - validFilterCount ++; - *typeFilterFlag = *typeFilterFlag | subtypeFilterFlag; - } else {//For union filter, single filter invalid means we could skip this filter - continue; - } - } - if (validFilterCount > 0) - jsonDbQueryStr->replace(QStringLiteral("][?"), QStringLiteral(" | ")); //replace the "][?" to " | " - else //no valid filter means empty item list from jsondb - isValidFilter = false; - return isValidFilter; - } - default: - isValidFilter = singleFilterToJsondbQuery(filter, jsonDbQueryStr, typeFilterFlag); - break; - } - - if (!isValidFilter) - jsonDbQueryStr->clear(); - - return isValidFilter; -} - -bool QOrganizerJsonDbConverter::singleFilterToJsondbQuery(const QOrganizerItemFilter& filter, QString *jsonDbQueryStr, int *typeFilterFlag) const -{ - bool isValidFilter = true; - switch (filter.type()) { - case QOrganizerItemFilter::CollectionFilter: - isValidFilter = collectionFilterToJsondbQuery(filter, jsonDbQueryStr); - break; - case QOrganizerItemFilter::IdFilter: - isValidFilter = idFilterToJsondbQuery(filter, jsonDbQueryStr); - break; - case QOrganizerItemFilter::DetailFieldFilter: - isValidFilter = detailFieldFilterToJsondbQuery(filter, jsonDbQueryStr, typeFilterFlag); - break; - case QOrganizerItemFilter::DetailFilter: - isValidFilter = detailFilterToJsondbQuery(filter, jsonDbQueryStr, typeFilterFlag); - break; - default: - break; - } - - return isValidFilter; -} - -QString QOrganizerJsonDbConverter::jsonDbNotificationObjectToOrganizerType(const QJsonObject &object) const -{ - return object.value(QOrganizerJsonDbStr::jsonDbType()).toString(); -} - -QOrganizerItemId QOrganizerJsonDbConverter::jsonDbNotificationObjectToItemId(const QJsonObject &object, QOrganizerJsonDbEngine::StorageLocation storageLocation) const -{ - QString jsonDbUuid = object.value(QOrganizerJsonDbStr::jsonDbUuid()).toString(); - if (jsonDbUuid.isEmpty()) { - return QOrganizerItemId(); - } else { - QOrganizerJsonDbItemId *jsondbItemId = new QOrganizerJsonDbItemId(); - jsondbItemId->setJsonDbUuid(jsonDbUuid); - jsondbItemId->setStorageLocation(storageLocation); - return QOrganizerItemId(jsondbItemId); - } -} - -QOrganizerCollectionId QOrganizerJsonDbConverter::jsonDbNotificationObjectToCollectionId(const QJsonObject &object, QOrganizerJsonDbEngine::StorageLocation storageLocation) const -{ - QString jsonUuid = object.value(QOrganizerJsonDbStr::jsonDbUuid()).toString(); - if (jsonUuid.isEmpty()) { - return QOrganizerCollectionId(); - } else { - QOrganizerJsonDbCollectionId *jsondbCollectionId = new QOrganizerJsonDbCollectionId(); - jsondbCollectionId->setJsonDbUuid(jsonUuid); - jsondbCollectionId->setStorageLocation(storageLocation); - return QOrganizerCollectionId(jsondbCollectionId); - } -} - -bool QOrganizerJsonDbConverter::collectionFilterToJsondbQuery(const QOrganizerItemFilter &filter, QString *jsonDbQueryStr) const -{ - bool isValidFilter = true; - const QOrganizerItemCollectionFilter cf(filter); - const QSet<QOrganizerCollectionId>& ids = cf.collectionIds(); - if (!ids.empty()) { - const QString idTemplate(QStringLiteral("\"%1\",")); - QString query; - foreach (const QOrganizerCollectionId &id, ids) { - if (!id.isNull()) - query += idTemplate.arg(QOrganizerJsonDbCollectionId(id.toString()).jsondbUuid()); - } - if (!query.isEmpty()) { - query.truncate(query.length() - 1); - *jsonDbQueryStr = QOrganizerJsonDbStr::jsonDbQueryCollectionUuidsTemplate().arg(query); - } else { - isValidFilter = false; - } - } else { - isValidFilter = false; - } - return isValidFilter; -} - -bool QOrganizerJsonDbConverter::idFilterToJsondbQuery(const QOrganizerItemFilter &filter, QString *jsonDbQueryStr) const -{ - bool isValidFilter = true; - const QOrganizerItemIdFilter idf(filter); - const QList<QOrganizerItemId>& ids = idf.ids(); - if (!ids.empty()) { - const QString uuidTemplate(QStringLiteral("\"%1\",")); - QString query; - foreach (const QOrganizerItemId &id, ids) { - if (!id.isNull()) - query += uuidTemplate.arg(QOrganizerJsonDbItemId(id.toString()).jsondbUuid()); - } - if (!query.isEmpty()) { - query.truncate(query.length() - 1); - *jsonDbQueryStr = QOrganizerJsonDbStr::jsonDbQueryUuidsTemplate().arg(query); - } else { - isValidFilter = false; - } - } else { - isValidFilter = false; - } - return isValidFilter; -} - -bool QOrganizerJsonDbConverter::isSupportedDetailFieldFilter( - const QVariant &fieldValue, QOrganizerItemDetail::DetailType detailType, int detailFieldName, QOrganizerItemFilter::MatchFlags matchFlags) const -{ - bool isValidFilter = true; - - if (detailType == QOrganizerItemDetail::TypeUndefined && detailFieldName == -1 && fieldValue.toString().isEmpty()) { - // no support when any of the fields is empty - isValidFilter = false; - } else if (QOrganizerItemDetail::TypeJournalTime == detailType - || QOrganizerItemDetail::TypeReminder == detailType - || QOrganizerItemDetail::TypeAudibleReminder == detailType - || QOrganizerItemDetail::TypeVisualReminder == detailType - || QOrganizerItemDetail::TypeEmailReminder == detailType - || QOrganizerItemDetail::TypeRecurrence == detailType - || QOrganizerItemDetail::TypeTimestamp == detailType - || QOrganizerItemDetail::TypeEventAttendee == detailType) { - // filtering certain details/definitions are currently not supported - isValidFilter = false; - } else if (QOrganizerItemFilter::MatchExactly != matchFlags - && (QOrganizerItemDetail::TypeEventTime == detailType - || QOrganizerItemDetail::TypeTodoTime == detailType - || QOrganizerItemDetail::TypeTodoProgress == detailType - || QOrganizerItemDetail::TypeComment == detailType - || (QOrganizerItemDetail::TypeLocation == detailType && (QOrganizerItemLocation::FieldLatitude == detailFieldName || QOrganizerItemLocation::FieldLongitude == detailFieldName)) - || QOrganizerItemDetail::TypePriority == detailType - || QOrganizerItemDetail::TypeItemType == detailType - || QOrganizerItemDetail::TypeTag == detailType - || QOrganizerItemDetail::TypeExtendedDetail == detailType - || (QOrganizerItemDetail::TypeEventRsvp == detailType && (QOrganizerEventRsvp::FieldParticipationStatus == detailFieldName - || QOrganizerEventRsvp::FieldParticipationRole == detailFieldName - || QOrganizerEventRsvp::FieldResponseRequirement == detailFieldName - || QOrganizerEventRsvp::FieldResponseDeadline == detailFieldName - || QOrganizerEventRsvp::FieldResponseDate == detailFieldName)) - || QOrganizerItemDetail::TypeParent == detailType)) { - // filtering matchflags are not supported for all the types - isValidFilter = false; - } else if (QVariant::String == fieldValue.type() - && !(QOrganizerItemDetail::TypeComment == detailType - || QOrganizerItemDetail::TypeDescription == detailType - || QOrganizerItemDetail::TypeDisplayLabel == detailType - || QOrganizerItemDetail::TypeGuid == detailType - || (QOrganizerItemDetail::TypeLocation == detailType && QOrganizerItemLocation::FieldLabel == detailFieldName) - || QOrganizerItemDetail::TypeTag == detailType - || QOrganizerItemDetail::TypeExtendedDetail == detailType - || QOrganizerItemDetail::TypeItemType == detailType - || (QOrganizerItemDetail::TypeEventRsvp == detailType && (QOrganizerEventRsvp::FieldOrganizerEmail == detailFieldName - || QOrganizerEventRsvp::FieldOrganizerName == detailFieldName)))) { - // filtering with QString needs extra attention, not allowed for all the types - isValidFilter = false; - } - return isValidFilter; -} - -bool QOrganizerJsonDbConverter::detailFilterToJsondbQuery(const QOrganizerItemFilter &filter, QString *jsonDbQueryStr, int *typeFilterFlag) const -{ - const QOrganizerItemDetailFilter df(filter); - const QOrganizerItemDetail detail(df.detail()); - const QOrganizerItemDetail::DetailType detailType (detail.type()); - - //We do not currently support detailFilter on Comment or Tag details - if ( (detailType == QOrganizerItemDetail::TypeComment) || - (detailType == QOrganizerItemDetail::TypeTag) || - (detail.values().isEmpty()) ) - return false; - - if (detailType == QOrganizerItemDetail::TypeExtendedDetail) { - if (detail.values().size() != 2) { - //Both Name and Data fields should be present, otherwise filter is invalid - return false; - } else { - QVariant extDetailDataValue = detail.value(QOrganizerItemExtendedDetail::FieldData); - QString extDetailValueString = extDetailDataValue.toString(); - QJsonValue jsonVal = QJsonValue::fromVariant(extDetailDataValue); - if ( jsonVal.isString()) - extDetailValueString = QString(QStringLiteral("\"%1\"").arg(extDetailValueString)); - jsonDbQueryStr->append(QStringLiteral("[?%1=%2]") - .arg(detail.value(QOrganizerItemExtendedDetail::FieldName).toString()) - .arg(extDetailValueString)); - return true; - } - } - - QVariant fieldValue; - foreach (int field, QOrganizerJsonDbEngine::supportedDetailFields(detailType)) { - if (detail.hasValue(field)) { - fieldValue = detail.value(field); - if (isSupportedDetailFieldFilter(fieldValue, detailType, field, QOrganizerItemFilter::MatchExactly)) { - addFieldToFilterQuery(detailType, field, - fieldValue, jsonDbQueryStr, - QOrganizerItemFilter::MatchExactly, - typeFilterFlag); - } else { - return false; - } - } else { - jsonDbQueryStr->append(QStringLiteral("[?%1 notExists]").arg(filterablePropertyNames().value(field))); - } - } - return true; -} - -bool QOrganizerJsonDbConverter::detailFieldFilterToJsondbQuery(const QOrganizerItemFilter &filter, QString *jsonDbQueryStr, int *typeFilterFlag) const -{ - /* - Jsondb backend specific notes related to OrganizerItemDetailFieldFilter - - Detail specific: - - Currently supported details; EventTime, TodoTime, Comment, Description, DisplayLabel, - Gui, Location, Priority, Type, Tag, Parent and Customized(ExtendedDetail). - - Type-detail is mapped from enum to string, since the C++ side is using strings. - - Comment- and Tag-details can only be filtered with MatchExactly. No wildcards supported. - - Customized(ExtendedDetail)-detail can only be used to filter the custom field name, not the data value. - Used custom field names should be simple and clear, no spaces or special characters. Matchflags - are not supported either, only exact matching works. - - No support to filter based only on detail-type without any value. Like filter everything which has Priority-field - regardless of the value of the field. - - Matchflags: - - MatchExactly: - -Works with all the supported detail types/fields (above) - -Only same object type supported for filtering, ie strings as Dates are not supported - - MatchFixedString - - Ignores any wildcard flags as filters as exact string - - MatchContains, MatchEndsWith, MatchStartsWith, MatchCaseSensitive - - These are supported only for details having string as a value type - - Works only if MatchExactly or MatchFixedString are not set - */ - - const QOrganizerItemDetailFieldFilter dff(filter); - const QOrganizerItemDetail::DetailType detailType(dff.detailType()); - const int detailField(dff.detailField()); - - if (isSupportedDetailFieldFilter(dff.value(), detailType, detailField, dff.matchFlags())) { - addFieldToFilterQuery(detailType, detailField, dff.value(), jsonDbQueryStr, dff.matchFlags(), typeFilterFlag); - return true; - } else { - return false; - } -} - -void QOrganizerJsonDbConverter::addFieldToFilterQuery(QOrganizerItemDetail::DetailType detailType, - int detailField, const QVariant &fieldValue, - QString *jsonDbQueryStr, - QOrganizerItemFilter::MatchFlags matchFlags, - int *typeFilterFlag) const -{ - const QString equalsQueryTemplate(QStringLiteral("[?%1=\"%2\"]")); - const QString equalsQueryTemplate2(QStringLiteral("[?%1=%2]")); - const QString equalsQueryTemplate3(QStringLiteral("[?%1.%2.%3=%4]")); - const QString containsQueryTemplate(QStringLiteral("[?%1 contains \"%2\"]")); - const QString matchFlagQueryTemplate(QStringLiteral("[?%1%2\"]")); - const QString matchFlagQueryTemplate2(QStringLiteral("[?%1.%2%3\"]")); - const QString existsQueryTemplate(QStringLiteral("[?%1 exists]")); - const QString valueString(fieldValue.toString()); - - if (QOrganizerItemDetail::TypeEventTime == detailType) { - if (QOrganizerEventTime::FieldStartDateTime == detailField) { - jsonDbQueryStr->append(equalsQueryTemplate - .arg(QOrganizerJsonDbStr::eventStartDateTime()).arg(fieldValue.toDateTime().toUTC().toString(Qt::ISODate))); - } else if (QOrganizerEventTime::FieldEndDateTime == detailField) { - jsonDbQueryStr->append(equalsQueryTemplate - .arg(QOrganizerJsonDbStr::eventEndDateTime()).arg(fieldValue.toDateTime().toUTC().toString(Qt::ISODate))); - } else if (QOrganizerEventTime::FieldAllDay == detailField) { - jsonDbQueryStr->append(equalsQueryTemplate2 - .arg(QOrganizerJsonDbStr::eventIsAllDay()).arg(valueString)); - } - - } else if (QOrganizerItemDetail::TypeTodoTime == detailType) { - if (QOrganizerTodoTime::FieldStartDateTime == detailField) { - jsonDbQueryStr->append(equalsQueryTemplate - .arg(QOrganizerJsonDbStr::todoStartDateTime()).arg(fieldValue.toDateTime().toUTC().toString(Qt::ISODate))); - } else if (QOrganizerTodoTime::FieldDueDateTime == detailField) { - jsonDbQueryStr->append(equalsQueryTemplate - .arg(QOrganizerJsonDbStr::todoDueDateTime()).arg(fieldValue.toDateTime().toUTC().toString(Qt::ISODate))); - } else if (QOrganizerTodoTime::FieldAllDay == detailField) { - jsonDbQueryStr->append(equalsQueryTemplate2 - .arg(QOrganizerJsonDbStr::todoIsAllDay()).arg(valueString)); - } - - } else if (QOrganizerItemDetail::TypeTodoProgress == detailType) { - if (QOrganizerTodoProgress::FieldFinishedDateTime == detailField) { - jsonDbQueryStr->append(equalsQueryTemplate - .arg(QOrganizerJsonDbStr::todoFinishedDateTime()) - .arg(fieldValue.toDateTime().toUTC().toString(Qt::ISODate))); - } else if (QOrganizerTodoProgress::FieldPercentageComplete == detailField) { - jsonDbQueryStr->append(equalsQueryTemplate2 - .arg(QOrganizerJsonDbStr::todoProgressPercentage()) - .arg(fieldValue.toInt())); - } else if (QOrganizerTodoProgress::FieldStatus == detailField) { - jsonDbQueryStr->append(equalsQueryTemplate - .arg(QOrganizerJsonDbStr::todoStatus()) - .arg(enumToString(organizerTodoStatusMap(), fieldValue.toInt()))); - } - - } else if (QOrganizerItemDetail::TypeComment == detailType - && QOrganizerItemComment::FieldComment == detailField) { - jsonDbQueryStr->append(containsQueryTemplate.arg(QOrganizerJsonDbStr::itemComments()).arg(valueString)); - - } else if (QOrganizerItemDetail::TypeDescription == detailType - && QOrganizerItemDescription::FieldDescription == detailField) { - jsonDbQueryStr->append(matchFlagQueryTemplate - .arg(QOrganizerJsonDbStr::itemDescription()).arg(createMatchFlagQuery(valueString, matchFlags))); - - } else if (QOrganizerItemDetail::TypeDisplayLabel == detailType - && QOrganizerItemDisplayLabel::FieldLabel == detailField) { - jsonDbQueryStr->append(matchFlagQueryTemplate - .arg(QOrganizerJsonDbStr::itemDisplayName()) - .arg(createMatchFlagQuery(valueString, matchFlags))); - - } else if (QOrganizerItemDetail::TypeGuid == detailType - && QOrganizerItemGuid::FieldGuid == detailField) { - jsonDbQueryStr->append(matchFlagQueryTemplate - .arg(QOrganizerJsonDbStr::itemGuid()) - .arg(createMatchFlagQuery(valueString, matchFlags))); - - } else if (QOrganizerItemDetail::TypeLocation == detailType) { - if (QOrganizerItemLocation::FieldLabel == detailField) { - jsonDbQueryStr->append(matchFlagQueryTemplate2 - .arg(QOrganizerJsonDbStr::eventLocation()) - .arg(QOrganizerJsonDbStr::eventLocationDisplayName()) - .arg(createMatchFlagQuery(valueString, matchFlags))); - } else if (QOrganizerItemLocation::FieldLongitude == detailField) { - jsonDbQueryStr->append(equalsQueryTemplate3 - .arg(QOrganizerJsonDbStr::eventLocation()) - .arg(QOrganizerJsonDbStr::eventLocationGeo()) - .arg(QOrganizerJsonDbStr::eventLocationGeoLongitude()) - .arg(valueString)); - } else if (QOrganizerItemLocation::FieldLatitude == detailField) { - jsonDbQueryStr->append(equalsQueryTemplate3 - .arg(QOrganizerJsonDbStr::eventLocation()) - .arg(QOrganizerJsonDbStr::eventLocationGeo()) - .arg(QOrganizerJsonDbStr::eventLocationGeoLatitude()) - .arg(valueString)); - } - - } else if (QOrganizerItemDetail::TypePriority == detailType - && QOrganizerItemPriority::FieldPriority == detailField) { - jsonDbQueryStr->append(equalsQueryTemplate - .arg(QOrganizerJsonDbStr::itemPriority()) - .arg(enumToString(organizerPriorityEnumMap(), fieldValue.toInt()))); - - } else if (QOrganizerItemDetail::TypeItemType == detailType - && QOrganizerItemType::FieldType == detailField) { - jsonDbQueryStr->append(equalsQueryTemplate - .arg(QOrganizerJsonDbStr::jsonDbType()) - .arg(QOrganizerJsonDbStr::jsonDbSchemaPrefix() + enumToString(organizerItemTypeMap(), fieldValue.toInt()))); - *typeFilterFlag = 0x01 << (fieldValue.toInt() - QOrganizerItemType::TypeUndefined); - - } else if (QOrganizerItemDetail::TypeTag == detailType - && QOrganizerItemTag::FieldTag == detailField) { - jsonDbQueryStr->append(containsQueryTemplate.arg(QOrganizerJsonDbStr::itemTags()).arg(valueString)); - - } else if (QOrganizerItemDetail::TypeParent == detailType) { - if (QOrganizerItemParent::FieldParentId == detailField) { - const QOrganizerItemEngineId *itemIdPtr = QOrganizerManagerEngine::engineItemId(fieldValue.value<QOrganizerItemId>()); - if (itemIdPtr) { - jsonDbQueryStr->append(equalsQueryTemplate - .arg(QOrganizerJsonDbStr::itemOccurrenceParent()) - .arg(itemIdPtr->toString())); - } - } else if (QOrganizerItemParent::FieldOriginalDate == detailField) { - jsonDbQueryStr->append(equalsQueryTemplate - .arg(QOrganizerJsonDbStr::itemOccurrenceOriginalDate()).arg(fieldValue.toDate().toString(Qt::ISODate))); - } - } else if (QOrganizerItemDetail::TypeExtendedDetail == detailType - && QOrganizerItemExtendedDetail::FieldName == detailField) { - jsonDbQueryStr->append(existsQueryTemplate.arg(valueString)); - - } else if (QOrganizerItemDetail::TypeEventRsvp == detailType) { - if (QOrganizerEventRsvp::FieldParticipationStatus == detailField) { - jsonDbQueryStr->append(matchFlagQueryTemplate2 - .arg(QOrganizerJsonDbStr::eventRsvp()) - .arg(QOrganizerJsonDbStr::eventRsvpParticipationStatus()) - .arg(createMatchFlagQuery(enumToString(organizerParticipationStatusMap(), fieldValue.toInt()), matchFlags))); - } else if (QOrganizerEventRsvp::FieldParticipationRole == detailField) { - jsonDbQueryStr->append(matchFlagQueryTemplate2 - .arg(QOrganizerJsonDbStr::eventRsvp()) - .arg(QOrganizerJsonDbStr::eventRsvpParticipationRole()) - .arg(createMatchFlagQuery(enumToString(organizerParticipationRoleMap(), fieldValue.toInt()), matchFlags))); - } else if (QOrganizerEventRsvp::FieldResponseRequirement == detailField) { - jsonDbQueryStr->append(matchFlagQueryTemplate2 - .arg(QOrganizerJsonDbStr::eventRsvp()) - .arg(QOrganizerJsonDbStr::eventRsvpResponseRequirement()) - .arg(createMatchFlagQuery(enumToString(organizerResponseRequirementMap(), fieldValue.toInt()), matchFlags))); - } else if (QOrganizerEventRsvp::FieldResponseDeadline == detailField) { - jsonDbQueryStr->append(matchFlagQueryTemplate2 - .arg(QOrganizerJsonDbStr::eventRsvp()) - .arg(QOrganizerJsonDbStr::eventRsvpResponseDeadline()) - .arg(createMatchFlagQuery(fieldValue.toDate().toString(Qt::ISODate), matchFlags))); - } else if (QOrganizerEventRsvp::FieldResponseDate == detailField) { - jsonDbQueryStr->append(matchFlagQueryTemplate2 - .arg(QOrganizerJsonDbStr::eventRsvp()) - .arg(QOrganizerJsonDbStr::eventRsvpResponseDate()) - .arg(createMatchFlagQuery(fieldValue.toDate().toString(Qt::ISODate), matchFlags))); - } else if (QOrganizerEventRsvp::FieldOrganizerName == detailField) { - jsonDbQueryStr->append(matchFlagQueryTemplate2 - .arg(QOrganizerJsonDbStr::eventRsvp()) - .arg(QOrganizerJsonDbStr::eventRsvpOrganizerName()) - .arg(createMatchFlagQuery(valueString, matchFlags))); - } else if (QOrganizerEventRsvp::FieldOrganizerEmail == detailField) { - jsonDbQueryStr->append(matchFlagQueryTemplate2 - .arg(QOrganizerJsonDbStr::eventRsvp()) - .arg(QOrganizerJsonDbStr::eventRsvpOrganizerEmail()) - .arg(createMatchFlagQuery(valueString, matchFlags))); - } - } -} - -QString QOrganizerJsonDbConverter::createMatchFlagQuery(const QString &value, QOrganizerItemFilter::MatchFlags flags) const -{ - // with current enumeration, 3 means both MatchContains and MatchEndsWith (QTBUG-20035) - const uint realMatchType = flags & 0x0F; - QString queryWithWildCards; - if (QOrganizerItemFilter::MatchExactly == flags) - queryWithWildCards = QStringLiteral("=\""); - else - queryWithWildCards = QStringLiteral("=~\"/"); - - if (QOrganizerItemFilter::MatchContains == realMatchType || QOrganizerItemFilter::MatchEndsWith == realMatchType) - queryWithWildCards += QStringLiteral("*"); - - queryWithWildCards += value; - - if (QOrganizerItemFilter::MatchContains == realMatchType || QOrganizerItemFilter::MatchStartsWith == realMatchType) - queryWithWildCards += QStringLiteral("*"); - - if (QOrganizerItemFilter::MatchExactly != flags && !(QOrganizerItemFilter::MatchFixedString & flags)) { - queryWithWildCards += QStringLiteral("/w"); - if (!(QOrganizerItemFilter::MatchCaseSensitive & flags)) - queryWithWildCards += QStringLiteral("i"); - } - return queryWithWildCards; -} - -int QOrganizerJsonDbConverter::supportedItemTypeFlag() const -{ -// int typeFilterFlag = 0x01 << QOrganizerItemType::TypeUndefined - QOrganizerItemType::TypeUndefined -// + 0x01 << (QOrganizerItemType::TypeEvent - QOrganizerItemType::TypeUndefined) -// + 0x01 << (QOrganizerItemType::TypeEventOccurrence - QOrganizerItemType::TypeUndefined); -// + 0x01 << (QOrganizerItemType::TypeTodo - QOrganizerItemType::TypeUndefined); -// + 0x01 << (QOrganizerItemType::TypeTodoOccurrence - QOrganizerItemType::TypeUndefined); - return 0xf1;//typeFilterFlag; -} - -bool QOrganizerJsonDbConverter::itemTypeFlagToJsonDbEventQuery(const int &flag, QString *jsonDbQueryStr) -{ - if (!flag) - return false; - if (supportedItemTypeFlag() == flag) - *jsonDbQueryStr = QOrganizerJsonDbStr::jsonDbQueryAllEventItems() + *jsonDbQueryStr; - else if (!((flag >> (QOrganizerItemType::TypeEvent - QOrganizerItemType::TypeUndefined)) & 0x01) - && !((flag >> (QOrganizerItemType::TypeEventOccurrence - QOrganizerItemType::TypeUndefined)) & 0x01)) { - return false; - } - return true; -} - -bool QOrganizerJsonDbConverter::itemTypeFlagToJsonDbTodoQuery(const int &flag, QString *jsonDbQueryStr) -{ - if (!flag) - return false; - if (supportedItemTypeFlag() == flag) - *jsonDbQueryStr = QOrganizerJsonDbStr::jsonDbQueryAllTodoItems() + *jsonDbQueryStr; - else if (!((flag >> (QOrganizerItemType::TypeTodo - QOrganizerItemType::TypeUndefined)) & 0x01) - && !((flag >> (QOrganizerItemType::TypeTodoOccurrence - QOrganizerItemType::TypeUndefined)) & 0x01)) { - return false; - } - return true; -} - -bool QOrganizerJsonDbConverter::createJsonDbQuery(const QOrganizerItemFilter &filter, const QDateTime &startTime, const QDateTime &endTime, QList<QString> *jsonDbQueryList) -{ - QString filterString; - int typeFilterFlag = supportedItemTypeFlag(); - if (compoundFilterToJsondbQuery(filter, &filterString, &typeFilterFlag)) { - if (startTime.isValid() || endTime.isValid()) { - QString eventJsonDbQuery; - if (itemTypeFlagToJsonDbEventQuery(typeFilterFlag, &eventJsonDbQuery)) { - eventJsonDbQuery += filterString; - if (startTime.isValid()) - eventJsonDbQuery += QOrganizerJsonDbStr::jsonDbQueryEventEndDateTimeTemplate().arg(startTime.toUTC().toString(Qt::ISODate)); - if (endTime.isValid()) - eventJsonDbQuery += QOrganizerJsonDbStr::jsonDbQueryEventStartDateTimeTemplate().arg(endTime.toUTC().toString(Qt::ISODate)); - jsonDbQueryList->append(eventJsonDbQuery); - } - - if (itemTypeFlagToJsonDbTodoQuery(typeFilterFlag, &filterString)) - jsonDbQueryList->append(filterString); - } else { - //No time period terms and create one request for both todo and event - if (supportedItemTypeFlag() == typeFilterFlag) - filterString = QOrganizerJsonDbStr::jsonDbQueryAllItems() + filterString; - jsonDbQueryList->append(filterString); - } - return true; - } - return false; -} - -QT_END_NAMESPACE_ORGANIZER diff --git a/src/plugins/organizer/jsondb/qorganizerjsondbconverter.h b/src/plugins/organizer/jsondb/qorganizerjsondbconverter.h deleted file mode 100644 index f99b1b628..000000000 --- a/src/plugins/organizer/jsondb/qorganizerjsondbconverter.h +++ /dev/null @@ -1,172 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtOrganizer module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QORGANIZERJSONDBCONVERTER_H -#define QORGANIZERJSONDBCONVERTER_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtOrganizer/qorganizerabstractrequest.h> -#include <QtOrganizer/qorganizermanager.h> -#include <QtOrganizer/qorganizeritemdetails.h> -#include <QtOrganizer/qorganizeritemdetailfilter.h> -#include <QtOrganizer/qorganizeritemdetailfieldfilter.h> - -#include <QtJsonDb/qjsondbconnection.h> -#include <QtJsonDb/qjsondbreadrequest.h> -#include <QtJsonDb/qjsondbwriterequest.h> - -#include "qorganizerjsondbengine.h" - -QT_USE_NAMESPACE_JSONDB - -QT_BEGIN_NAMESPACE_ORGANIZER - -struct QOrganizerJsonDbEnumConversionData -{ - int enumValue; - const QString enumStr; -}; - -class QOrganizerJsonDbConverter -{ -public: - QOrganizerJsonDbConverter(); - - QOrganizerManager::Error jsonDbConnectionErrorToOrganizerError(QJsonDbConnection::ErrorCode error) const; - QOrganizerManager::Error jsonDbRequestErrorToOrganizerError(QJsonDbRequest::ErrorCode error) const; - - bool jsonDbObjectToItem(const QJsonObject &object, QOrganizerItem *item, QOrganizerJsonDbEngine::StorageLocation storageLocation) const; - bool itemToJsonDbObject(const QOrganizerItem &item, QJsonObject *object) const; - - bool jsonDbObjectToCollection(const QJsonObject &object, QOrganizerCollection *collection, bool *isDefaultCollection, QOrganizerJsonDbEngine::StorageLocation storageLocation) const; - bool collectionToJsonDbObject(const QOrganizerCollection &collection, bool isDefaultCollection, QJsonObject *object) const; - - // filter handling - bool singleFilterToJsondbQuery(const QOrganizerItemFilter &filter, QString *jsonDbQueryStr, int *typeFilterFlag) const; - bool compoundFilterToJsondbQuery(const QOrganizerItemFilter &filter, QString *jsonDbQueryStr, int *typeFilterFlag) const; - - // notification handling - QString jsonDbNotificationObjectToOrganizerType(const QJsonObject &object) const; - QOrganizerItemId jsonDbNotificationObjectToItemId(const QJsonObject &object, QOrganizerJsonDbEngine::StorageLocation storageLocation) const; - QOrganizerCollectionId jsonDbNotificationObjectToCollectionId(const QJsonObject &object, QOrganizerJsonDbEngine::StorageLocation storageLocation) const; - - void jsonDbVersionToItemVersion(const QString &jsonDbVersion, QOrganizerItemVersion *itemVersion) const; - - // storage location handling - const QStringList storageLocationsFlagToStrings(const QOrganizerJsonDbEngine::StorageLocations storageLocationsFlag); - QOrganizerJsonDbEngine::StorageLocation storageLocationStringToEnum(const QString &storageLocation); - QOrganizerJsonDbEngine::StorageLocations storageLocationListToFlag(const QList<QOrganizerJsonDbEngine::StorageLocation> storageLocationsList); - - int supportedItemTypeFlag() const; - bool itemTypeFlagToJsonDbEventQuery(const int &flag, QString *jsonDbQueryStr); - bool itemTypeFlagToJsonDbTodoQuery(const int &flag, QString *jsonDbQueryStr); - - bool createJsonDbQuery(const QOrganizerItemFilter &filter, const QDateTime &startTime, const QDateTime &endTime, QList<QString> *jsonDbQueryList); - -private: - void itemVersionToJsonDbVersion(const QOrganizerItemVersion &itemVersion, QString *jsonDbVersion) const; - - void jsonDbObjectToRecurrenceRule(const QJsonObject &object, QOrganizerRecurrenceRule *rule) const; - void recurrenceRuleToJsonDbObject(const QOrganizerRecurrenceRule &rule, QJsonObject *object) const; - - void audibleReminderDetailToJsonDbObject(const QOrganizerItemAudibleReminder &itemReminder, QJsonObject *object) const; - void jsonDbObjectToAudibleReminderDetail(const QJsonObject &object, QOrganizerItemAudibleReminder *itemReminder, - QOrganizerItemExtendedDetail *extendedDetail) const; - - int stringToEnum(const QOrganizerJsonDbEnumConversionData *const conversionData, const QString &enumStr) const; - QString enumToString(const QOrganizerJsonDbEnumConversionData *const conversionData, int enumValue) const; - - void attendeeDetailToJsonDbObject(const QOrganizerEventAttendee &attendeeDetail, QJsonObject *object) const; - void jsonDbObjectToAttendeeDetail(const QJsonObject &object, QOrganizerEventAttendee *attendeeDetail) const; - - void rsvpDetailToJsonDbObject(const QOrganizerEventRsvp &rsvpDetail, QJsonObject *object) const; - void jsonDbObjectToRsvpDetail(const QJsonObject &object, QOrganizerEventRsvp *rsvpDetail, - QOrganizerItemExtendedDetail *extendedDetail) const; - - void locationDetailToJsonDbObject(const QOrganizerItemLocation &locationDetail, QJsonObject *object) const; - void jsonDbObjectToLocationDetail(const QJsonObject &object, QOrganizerItemLocation *locationDetail, - QOrganizerItemExtendedDetail *extendedDetail) const; - - // separate filter type specific handling - bool collectionFilterToJsondbQuery(const QOrganizerItemFilter &filter, QString *jsonDbQueryStr) const; - bool idFilterToJsondbQuery(const QOrganizerItemFilter &filter, QString *jsonDbQueryStr) const; - bool detailFilterToJsondbQuery(const QOrganizerItemFilter &filter, QString *jsonDbQueryStr, int *typeFilterFlag) const; - bool detailFieldFilterToJsondbQuery(const QOrganizerItemFilter &filter, QString *jsonDbQueryStr, int *typeFilterFlag) const; - bool isSupportedDetailFieldFilter(const QVariant &fieldValue, - QOrganizerItemDetail::DetailType detailType, - int detailFieldName, - QOrganizerItemFilter::MatchFlags matchFlags) const; - QString createMatchFlagQuery(const QString &value, QOrganizerItemFilter::MatchFlags flags) const; - void addFieldToFilterQuery(QOrganizerItemDetail::DetailType detailType, - int detailField, - const QVariant &fieldValue, - QString *jsonDbQueryStr, - QOrganizerItemFilter::MatchFlags matchFlags, - int *typeFilterFlag) const; - - static const int enumMapEnd; - static const QMap<int, QString> filterablePropertyNames(); - static const QOrganizerJsonDbEnumConversionData *organizerPriorityEnumMap(); - static const QOrganizerJsonDbEnumConversionData *organizerFrequencyEnumMap(); - static const QOrganizerJsonDbEnumConversionData *organizerDayEnumMap(); - static const QOrganizerJsonDbEnumConversionData *organizerMonthEnumMap(); - static const QOrganizerJsonDbEnumConversionData *organizerParticipationStatusMap(); - static const QOrganizerJsonDbEnumConversionData *organizerParticipationRoleMap(); - static const QOrganizerJsonDbEnumConversionData *organizerResponseRequirementMap(); - static const QOrganizerJsonDbEnumConversionData *organizerItemTypeMap(); - static const QOrganizerJsonDbEnumConversionData *organizerTodoStatusMap(); - static const QOrganizerJsonDbEnumConversionData *organizerStorageLocationMap(); - -}; - -QT_END_NAMESPACE_ORGANIZER - -#endif // QORGANIZERJSONDBCONVERTER_H diff --git a/src/plugins/organizer/jsondb/qorganizerjsondbdatastorage.cpp b/src/plugins/organizer/jsondb/qorganizerjsondbdatastorage.cpp deleted file mode 100644 index 9094dfdee..000000000 --- a/src/plugins/organizer/jsondb/qorganizerjsondbdatastorage.cpp +++ /dev/null @@ -1,957 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtOrganizer module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qorganizerjsondbdatastorage.h" - -#include <QtCore/qdebug.h> -#include <QtCore/qmutex.h> - -#include <QtOrganizer/qorganizeritemcollectionfilter.h> -#include <QtOrganizer/qorganizermanagerengine.h> - -#include "qorganizerjsondbid.h" -#include "qorganizerjsondbstring.h" - -QT_BEGIN_NAMESPACE_ORGANIZER - -QOrganizerJsonDbDataStorage::QOrganizerJsonDbDataStorage() - : m_waitMutex(0) - , m_jsonDbConnection(0) - , m_mandatoryStorageLocationMissing(false) -{ - m_availableStorageLocations<<QOrganizerJsonDbEngine::UserDataStorage<<QOrganizerJsonDbEngine::SystemStorage; - m_availableStorageLocationsFlag = m_converter.storageLocationListToFlag(m_availableStorageLocations); - clearRequestData(); -} - -QOrganizerJsonDbDataStorage::~QOrganizerJsonDbDataStorage() -{ - delete m_waitMutex; -} - -void QOrganizerJsonDbDataStorage::saveItems(QMap<int, QOrganizerItem>* items, QMap<int, QOrganizerManager::Error>* errorMap, QOrganizerManager::Error* error, QOrganizerJsonDbEngine::StorageLocation storageLocation) -{ - if (items->isEmpty()) - return; - initRequestData(SaveItems, errorMap, error); - m_saveToStorageLocation = storageLocation; - m_resultItems = items; - processRequest(); - clearRequestData(); -} - -QList<QOrganizerItem> QOrganizerJsonDbDataStorage::items(const QDateTime &startDate, const QDateTime &endDate, const QOrganizerItemFilter &filter, - const QList<QOrganizerItemSortOrder> &sortOrders, const QOrganizerItemFetchHint &fetchHint, - QOrganizerManager::Error *error, QOrganizerJsonDbEngine::StorageLocations storageLocations, - FetchType type, const QOrganizerItemId &parentId) -{ - Q_UNUSED(sortOrders); - Q_UNUSED(fetchHint); - initRequestData(Items, 0, error); - m_start = startDate; - m_end = endDate; - m_filter = filter; - if (type == FetchItemOccurrences) - m_parentItemId = parentId; - m_fetchType = type; - m_fetchFromStorageLocations = storageLocations; - processRequest(); - QList<QOrganizerItem> fetchedItems = m_items; - clearRequestData(); - return fetchedItems; -} - -QList<QOrganizerItem> QOrganizerJsonDbDataStorage::itemsById(const QList<QOrganizerItemId>& itemIds, QMap<int, QOrganizerManager::Error>* errorMap, - QOrganizerManager::Error *error, QOrganizerJsonDbEngine::StorageLocations storageLocations) -{ - if (itemIds.isEmpty()) - return QList<QOrganizerItem>(); - initRequestData(ItemsById, errorMap, error); - m_itemIds = itemIds; - m_fetchFromStorageLocations = storageLocations; - processRequest(); - QList<QOrganizerItem> fetchedItems = m_items; - clearRequestData(); - return fetchedItems; -} - -void QOrganizerJsonDbDataStorage::removeItems(const QList<QOrganizerItemId>& itemIds, QMap<int, QOrganizerManager::Error>* errorMap, QOrganizerManager::Error* error) -{ - if (itemIds.isEmpty()) - return; - initRequestData(RemoveItems, errorMap, error); - m_itemIds = itemIds; - processRequest(); - clearRequestData(); -} - -void QOrganizerJsonDbDataStorage::saveCollections(QMap<int, QOrganizerCollection>* collections, QMap<int, QOrganizerManager::Error>* errorMap, QOrganizerManager::Error* error, QOrganizerJsonDbEngine::StorageLocation storageLocation) -{ - if (collections->isEmpty()) - return; - initRequestData(SaveCollections, errorMap, error); - m_resultCollections = collections; - m_isDefaultCollection = false; - m_saveToStorageLocation = storageLocation; - processRequest(); - clearRequestData(); -} - -QList<QOrganizerCollection> QOrganizerJsonDbDataStorage::collections(QOrganizerManager::Error *error, QOrganizerJsonDbEngine::StorageLocations storageLocations) -{ - initRequestData(Collections, 0, error); - m_fetchFromStorageLocations = storageLocations; - processRequest(); - QList<QOrganizerCollection> fetchedCollections; - if (*error == QOrganizerManager::NoError) - fetchedCollections = m_collections; - clearRequestData(); - return fetchedCollections; -} - -void QOrganizerJsonDbDataStorage::removeCollections(const QMap<int, QOrganizerCollectionId>& collectionIds, QMap<int, QOrganizerManager::Error>* errorMap, QOrganizerManager::Error* error) -{ - if (collectionIds.isEmpty()) - return; - initRequestData(RemoveCollections, errorMap, error); - m_removeCollectionIds = collectionIds; - processRequest(); - clearRequestData(); -} - -void QOrganizerJsonDbDataStorage::createDefaultCollection(QOrganizerCollection* defaultCollection, QOrganizerManager::Error* error) -{ - QMap<int, QOrganizerManager::Error> errorMap; - initRequestData(SaveCollections, &errorMap, error); - QMap<int, QOrganizerCollection> collections; - collections.insert(0, *defaultCollection); - m_resultCollections = &collections; - m_isDefaultCollection = true; - m_saveToStorageLocation = QOrganizerJsonDbEngine::UserDataStorage; - processRequest(); - *defaultCollection = m_resultCollections->value(0); - m_defaultCollection = *defaultCollection; - clearRequestData(); -} - -QOrganizerCollection QOrganizerJsonDbDataStorage::defaultCollection() -{ - // Fetching collections is the first operation done with the backend - // and the availability of storage locations is also checked. - if (m_defaultCollection.id().isNull()) { - // m_defaultCollection is updated every time collections are fetched - QOrganizerManager::Error error; - collections(&error, m_converter.storageLocationListToFlag(m_availableStorageLocations)); - } - return m_defaultCollection; -} - -QSet<QOrganizerCollectionId> QOrganizerJsonDbDataStorage::collectionIds() -{ - if (m_collectionIds.isEmpty()) { - // m_collectionIds is updated every time collections are fetched - QOrganizerManager::Error error; - collections(&error, m_converter.storageLocationListToFlag(m_availableStorageLocations)); - } - return m_collectionIds; -} - -QOrganizerJsonDbEngine::StorageLocations QOrganizerJsonDbDataStorage::availableStorageLocationsFlag() const -{ - return m_availableStorageLocationsFlag; -} - -void QOrganizerJsonDbDataStorage::run() -{ - m_waitMutex = new QMutex(); - - m_jsonDbConnection = new QJsonDbConnection(this); - connect(m_jsonDbConnection, SIGNAL(error(QtJsonDb::QJsonDbConnection::ErrorCode,QString)), - this, SLOT(onJsonDbConnectionError(QtJsonDb::QJsonDbConnection::ErrorCode,QString))); - m_jsonDbConnection->connectToServer(); - - registerForNotifications(); - - connect(this, SIGNAL(requestInitialized()), this, SLOT(handleRequest())); - - emit threadInitialized(); - QThread::run(); -} - -//////////////////////////////////////////////////////////////////////////////// -// These functions are run in the context of QOrganizerJsonDbDataStorage thread -//////////////////////////////////////////////////////////////////////////////// - -void QOrganizerJsonDbDataStorage::registerForNotifications() -{ - const QStringList storageLocations = m_converter.storageLocationsFlagToStrings( - QOrganizerJsonDbEngine::UserDataStorage | QOrganizerJsonDbEngine::SystemStorage); - - const int count = storageLocations.count(); - QJsonDbWatcher *watcher; - for (int i=0;i<count;i++) { - watcher = new QJsonDbWatcher(this); - watcher->setWatchedActions(QJsonDbWatcher::All); - watcher->setQuery(QOrganizerJsonDbStr::jsonDbNotificationQuery()); - watcher->setPartition(storageLocations.at(i)); - connect(watcher, SIGNAL(error(QtJsonDb::QJsonDbWatcher::ErrorCode,QString)), - this, SLOT(onJsonDbWatcherError(QtJsonDb::QJsonDbWatcher::ErrorCode,QString))); - connect(watcher, SIGNAL(notificationsAvailable(int)), - this, SLOT(onJsonDbWatcherNotificationsAvailable())); - m_jsonDbConnection->addWatcher(watcher); - m_watchers.append(watcher); - } -} - -void QOrganizerJsonDbDataStorage::onJsonDbConnectionError(QtJsonDb::QJsonDbConnection::ErrorCode error, const QString &message) -{ - Q_UNUSED(error) - Q_UNUSED(message) - - // currently there's no real errors from JsonDb - Q_ASSERT(m_converter.jsonDbConnectionErrorToOrganizerError(error) == QOrganizerManager::NoError); -} - -void QOrganizerJsonDbDataStorage::onJsonDbRequestError(QtJsonDb::QJsonDbRequest::ErrorCode error, const QString &message) -{ - Q_UNUSED(message) - - // if the error() signal is emitted, the finished() signal won't be emitted, so need to call handleResponse() - QJsonDbRequest *request = qobject_cast<QJsonDbRequest *>(sender()); - if (request) { - QOrganizerManager::Error organizerError = m_converter.jsonDbRequestErrorToOrganizerError(error); - // check first the storage location - if (QOrganizerManager::UnspecifiedError == organizerError && !m_mandatoryStorageLocationMissing) { - const QOrganizerJsonDbEngine::StorageLocation requestStorageLocation = m_converter.storageLocationStringToEnum(request->partition()); - m_availableStorageLocations.removeOne(requestStorageLocation); - m_availableStorageLocationsFlag = m_converter.storageLocationListToFlag(m_availableStorageLocations); - if (QOrganizerJsonDbEngine::UserDataStorage == requestStorageLocation) { - qCritical("Organizer - JsonDb backend does not work without UserDataStorage!"); - m_mandatoryStorageLocationMissing = true; - organizerError = QOrganizerManager::UnspecifiedError; - } - } - handleResponse(organizerError, request); - } -} - -void QOrganizerJsonDbDataStorage::onJsonDbRequestFinished() -{ - QJsonDbRequest *request = qobject_cast<QJsonDbRequest *>(sender()); - if (request) - handleResponse(QOrganizerManager::NoError, request); -} - -void QOrganizerJsonDbDataStorage::onJsonDbWatcherError(QtJsonDb::QJsonDbWatcher::ErrorCode error, const QString &message) -{ - if (QJsonDbWatcher::NoError != error) { - QJsonDbWatcher *watcher = qobject_cast<QJsonDbWatcher *>(sender()); - if (watcher) { - qCritical("Organizer - Not able to register for jsondb-notifications on '%s'!", qPrintable(watcher->partition())); - qCritical("Organizer - Error: '%s'.", qPrintable(message)); - m_watchers.removeOne(watcher); - watcher->deleteLater(); - } - } -} - -void QOrganizerJsonDbDataStorage::onJsonDbWatcherNotificationsAvailable() -{ - // no mutex is needed since this slot doesn't touch any member variables - QJsonDbWatcher *watcher = qobject_cast<QJsonDbWatcher *>(sender()); - if (watcher) { - const QList<QJsonDbNotification> ¬ifications = watcher->takeNotifications(); - for (int i = 0; i < notifications.size(); ++i) { - QJsonObject jsonDbObject = notifications.at(i).object(); - QString jsonDbType = m_converter.jsonDbNotificationObjectToOrganizerType(jsonDbObject); - const QOrganizerJsonDbEngine::StorageLocation storageLocation = m_converter.storageLocationStringToEnum(watcher->partition()); - if (jsonDbType == QOrganizerJsonDbStr::jsonDbEventType() - || jsonDbType == QOrganizerJsonDbStr::jsonDbEventViewType() - || jsonDbType == QOrganizerJsonDbStr::jsonDbEventOccurrenceType() - || jsonDbType == QOrganizerJsonDbStr::jsonDbTodoType() - || jsonDbType == QOrganizerJsonDbStr::jsonDbTodoOccurrenceType()) { - switch (notifications.at(i).action()) { - case QJsonDbWatcher::Created: - emit itemAdded(m_converter.jsonDbNotificationObjectToItemId(jsonDbObject, storageLocation)); - break; - case QJsonDbWatcher::Updated: - emit itemChanged(m_converter.jsonDbNotificationObjectToItemId(jsonDbObject, storageLocation)); - break; - case QJsonDbWatcher::Removed: - emit itemRemoved(m_converter.jsonDbNotificationObjectToItemId(jsonDbObject, storageLocation)); - break; - default: - break; - } - } else if (jsonDbType == QOrganizerJsonDbStr::jsonDbCollectionType()) { - switch (notifications.at(i).action()) { - case QJsonDbWatcher::Created: { - QOrganizerCollectionId newlyAddedId = m_converter.jsonDbNotificationObjectToCollectionId(jsonDbObject, storageLocation); - m_collectionIds.insert(newlyAddedId); - emit collectionAdded(newlyAddedId); - break; - } - case QJsonDbWatcher::Updated: { - emit collectionChanged(m_converter.jsonDbNotificationObjectToCollectionId(jsonDbObject, storageLocation)); - break; - } - case QJsonDbWatcher::Removed: { - QOrganizerCollectionId removedId = m_converter.jsonDbNotificationObjectToCollectionId(jsonDbObject, storageLocation); - m_collectionIds.remove(removedId); - emit collectionRemoved(removedId); - break; - } - default: - break; - } - } - } - } -} - -void QOrganizerJsonDbDataStorage::handleRequest() -{ - switch (m_requestType) { - case SaveItems: - handleSaveItemsRequest(); - break; - case Items: - handleItemsRequest(); - break; - case ItemsById: - handleItemsByIdRequest(); - break; - case RemoveItems: - handleRemoveItemsRequest(); - break; - case SaveCollections: - handleSaveCollectionsRequest(); - break; - case Collections: - handleCollectionsRequest(); - break; - case RemoveCollections: - handleRemoveCollectionsRequest(); - break; - default: - break; - } -} - -void QOrganizerJsonDbDataStorage::handleResponse(QOrganizerManager::Error error, QJsonDbRequest *request) -{ - int index = -1; - QMap<QJsonDbRequest *, int>::iterator i = m_requestIndexMap.find(request); - if (i != m_requestIndexMap.end()) { - index = i.value(); - m_requestIndexMap.erase(i); - } else { - // It might fall here if handling of some request was stopped due to timeout, - // then remaining responses may come when no request is processed and m_requestIndexMap - // has been cleared. In such cases, do nothing. - return; - } - - switch (m_requestType) { - case SaveItems: - handleSaveItemsResponse(index, error, request); - break; - case Items: - handleItemsResponse(error, request); - break; - case ItemsById: - handleItemsByIdResponse(error, request); - break; - case RemoveItems: - handleRemoveItemsResponse(index, error); - break; - case SaveCollections: - handleSaveCollectionsResponse(index, error, request); - break; - case Collections: - handleCollectionsResponse(error, request); - break; - case RemoveCollections: - handleRemoveCollectionsResponse(error); - break; - case Invalid: - // no active request at the moment, internal variables have been cleared and some pointers have - // NULL value, so response is just ignored - default: - break; - } - - delete request; -} - -void QOrganizerJsonDbDataStorage::handleSaveItemsRequest() -{ - bool requestSent = false; - QMap<int, QOrganizerItem>::const_iterator i = m_resultItems->begin(); - while (i != m_resultItems->end()) { - QOrganizerItemId itemId = i.value().id(); - bool itemIsNew = itemId.isNull(); - - QJsonObject jsonDbItem; - if (m_converter.itemToJsonDbObject(i.value(), &jsonDbItem)) { - JsonDbRequestType requestType; - QOrganizerJsonDbEngine::StorageLocation storageLocation(QOrganizerJsonDbEngine::UserDataStorage); - if (itemIsNew) { - requestType = JsonDbCreateRequest; - // first save, storage location given in request. if not, by default store to UserData. - storageLocation = m_saveToStorageLocation ? m_saveToStorageLocation : QOrganizerJsonDbEngine::UserDataStorage; - } else { - requestType = JsonDbUpdateRequest; - const QOrganizerJsonDbItemId *itemIdPtr = static_cast<const QOrganizerJsonDbItemId *>(QOrganizerManagerEngine::engineItemId(itemId)); - if (!itemIdPtr) { - *m_error = QOrganizerManager::UnspecifiedError; - m_errorMap->insert(i.key(), *m_error); - } else { - // item has already been saved before, use location from id - storageLocation = itemIdPtr->storageLocation(); - } - } - if (makeJsonDbRequest(requestType, i.key(), storageLocation, QString(), QList<QJsonObject>() << jsonDbItem)) - requestSent = true; - } else { - *m_error = QOrganizerManager::InvalidItemTypeError; - m_errorMap->insert(i.key(), *m_error); - } - - ++i; - } - if (!requestSent) - m_syncWaitCondition.wakeAll(); -} - -void QOrganizerJsonDbDataStorage::handleSaveItemsResponse(int index, QOrganizerManager::Error error, QJsonDbRequest *request) -{ - if (error == QOrganizerManager::NoError) { - QList<QJsonObject> results = request->takeResults(); - if (results.size() > 0) { - QOrganizerItem item = m_resultItems->value(index); - QJsonObject jsonDbItem = results.at(0); - bool gotUuid = !item.id().isNull(); - bool gotVersion = false; - QJsonObject::const_iterator i = jsonDbItem.constBegin(); - while (i != jsonDbItem.constEnd()) { - if (!gotUuid && i.key() == QOrganizerJsonDbStr::jsonDbUuid()) { - // it's a new item, and we need to set the item ID - gotUuid = true; - QString jsonDbUuid = i.value().toString(); - if (!jsonDbUuid.isEmpty()) { - QOrganizerJsonDbItemId* itemId = new QOrganizerJsonDbItemId; - itemId->setJsonDbUuid(jsonDbUuid); - itemId->setStorageLocation(m_converter.storageLocationStringToEnum(request->partition())); - item.setId(QOrganizerItemId(itemId)); - } - } else if (!gotVersion && i.key() == QOrganizerJsonDbStr::jsonDbVersion()) { - gotVersion = true; - QString jsonDbVersion = i.value().toString(); - if (!jsonDbVersion.isEmpty()) { - QOrganizerItemVersion itemVersion = item.detail(QOrganizerItemDetail::TypeVersion); - m_converter.jsonDbVersionToItemVersion(jsonDbVersion, &itemVersion); - item.saveDetail(&itemVersion); - } - } - if (gotUuid && gotVersion) - break; - ++i; - } - - m_resultItems->insert(index, item); - } - } else { - *m_error = error; - m_errorMap->insert(index, *m_error); - } - if (m_requestIndexMap.isEmpty()) { - // All transactions have been handled, request has been completed - m_syncWaitCondition.wakeAll(); - } -} - -void QOrganizerJsonDbDataStorage::handleItemsRequest() -{ - QString jsonDbQuery; - - switch (m_fetchType) { - case FetchItems: - // break; - case FetchItemIds: - { - // TODO: it would be enough to get just a list of uuids from db - // For now we fetch the whole item, even though more optimal would be to fetch - // only uuid, startdate and enddate fields - - // for now, this is common for FetchItems and FetchItemIds - // Apply Filter and get jsondb query expression - QList<QString> jsonDbQueryList; - if (m_converter.createJsonDbQuery(m_filter, m_start, m_end, &jsonDbQueryList)) { - foreach (const QString &jsonDbQuery, jsonDbQueryList) { - foreach (QOrganizerJsonDbEngine::StorageLocation location, m_availableStorageLocations) { - if (m_fetchFromStorageLocations & location) - makeJsonDbRequest(JsonDbReadRequest, 0, location, jsonDbQuery); - } - } - } else { - *m_error = QOrganizerManager::BadArgumentError; - } - break; - } - case FetchParents: - { - // This is used for fetching all parent items - foreach (QOrganizerJsonDbEngine::StorageLocation location, m_availableStorageLocations) { - if (m_fetchFromStorageLocations & location) { - if (makeJsonDbRequest(JsonDbReadRequest, 0, location, QOrganizerJsonDbStr::jsonDbQueryParentItems())) { - if (location == QOrganizerJsonDbEngine::SystemStorage) { - // can't query normal object and view object at the same time - // TODO only query view objects for when needed - makeJsonDbRequest(JsonDbReadRequest, 0, location, QOrganizerJsonDbStr::jsonDbQueryEventViewParentItems()); - } - } - } - } - break; - } - case FetchItemOccurrences: - { - const QOrganizerItemEngineId *itemIdPtr = QOrganizerManagerEngine::engineItemId(m_parentItemId); - if (itemIdPtr) { - jsonDbQuery = QOrganizerJsonDbStr::jsonDbQueryOccurrenceItemsByParent() - .arg(itemIdPtr->toString()); - foreach (QOrganizerJsonDbEngine::StorageLocation location, m_availableStorageLocations) { - if (m_fetchFromStorageLocations & location) - makeJsonDbRequest(JsonDbReadRequest, 0, location, jsonDbQuery); - } - } - break; - } - default: - break; - } - - if (m_requestIndexMap.isEmpty()) - m_syncWaitCondition.wakeAll(); -} - -void QOrganizerJsonDbDataStorage::handleItemsResponse(QOrganizerManager::Error error, QJsonDbRequest *request) -{ - if (error == QOrganizerManager::NoError) { - QList<QJsonObject> results = request->takeResults(); - for (int i = 0; i < results.size(); ++i) { - QOrganizerItem item; - if (m_converter.jsonDbObjectToItem(results.at(i), &item, m_converter.storageLocationStringToEnum(request->partition()))) { - if (m_start.isValid() || m_end.isValid()) { - QOrganizerItemType::ItemType itemType = item.type(); - if ((QOrganizerItemType::TypeTodo == itemType || QOrganizerItemType::TypeTodoOccurrence == itemType) - && !QOrganizerManagerEngine::isItemBetweenDates(item, m_start, m_end)) { - continue; - } - } - // if m_fetchType is FetchParents, items are always added to m_items, because m_start and m_end - // are default constructed QDateTimes - m_items.append(item); - } - } - } else { - *m_error = error; - } - - // when querying view objects, 2 queries are fired, so need to check - if (m_requestIndexMap.isEmpty()) - m_syncWaitCondition.wakeAll(); -} - -void QOrganizerJsonDbDataStorage::handleItemsByIdRequest() -{ - const QString uuidTemplate(QStringLiteral("\"%1\",")); - QString itemQuery; - for (int i = 0; i < m_itemIds.size(); ++i) - itemQuery += uuidTemplate.arg(m_itemIds.at(i).isNull() ? - QString() : QOrganizerJsonDbItemId(m_itemIds.at(i).toString()).jsondbUuid()); - - // remove the last "," - itemQuery.truncate(itemQuery.length() - 1); - - QString newJsonDbQuery(QOrganizerJsonDbStr::jsonDbQueryAllItems()); - newJsonDbQuery.append(QOrganizerJsonDbStr::jsonDbQueryUuidsTemplate().arg(itemQuery)); - - QString viewObjectJsonDbQuery(QOrganizerJsonDbStr::jsonDbQueryEventViews()); - viewObjectJsonDbQuery.append(QOrganizerJsonDbStr::jsonDbQueryUuidsTemplate().arg(itemQuery)); - - foreach (QOrganizerJsonDbEngine::StorageLocation location, m_availableStorageLocations) { - if (m_fetchFromStorageLocations & location) { - makeJsonDbRequest(JsonDbReadRequest, 0, location, newJsonDbQuery); - if (location == QOrganizerJsonDbEngine::SystemStorage) - makeJsonDbRequest(JsonDbReadRequest, 0, location, viewObjectJsonDbQuery); - } - } - - if (m_requestIndexMap.isEmpty()) - m_syncWaitCondition.wakeAll(); -} - -void QOrganizerJsonDbDataStorage::handleItemsByIdResponse(QOrganizerManager::Error error, QJsonDbRequest *request) -{ - if (error == QOrganizerManager::NoError) { - QList<QJsonObject> results = request->takeResults(); - for (int i = 0; i < results.size(); ++i) { - QOrganizerItem *item = new QOrganizerItem; - if (m_converter.jsonDbObjectToItem(results.at(i), item, m_converter.storageLocationStringToEnum(request->partition()))) { - m_idItemMap.insert(item->id(), *item); - } - } - } else { - *m_error = error; - } - - if (m_requestIndexMap.isEmpty()) { - // All transactions have been handled, request has been completed - - for (int i = 0; i < m_itemIds.size(); ++i) { - QOrganizerItem item = m_idItemMap.value(m_itemIds[i], QOrganizerItem()); - m_items.append(item); - if (item.id().isNull()) { - *m_error = QOrganizerManager::DoesNotExistError; - m_errorMap->insert(i, *m_error); - } - } - - m_syncWaitCondition.wakeAll(); - } -} - -void QOrganizerJsonDbDataStorage::handleRemoveItemsRequest() -{ - bool requestSent = false; - for (int i = 0; i < m_itemIds.size(); ++i) { - QJsonObject jsonDbItem; - if (m_itemIds.at(i).isNull()) { - *m_error = QOrganizerManager::DoesNotExistError; - m_errorMap->insert(i, QOrganizerManager::DoesNotExistError); - continue; - } - const QOrganizerJsonDbItemId jsondbItemId(m_itemIds.at(i).toString()); - jsonDbItem.insert(QOrganizerJsonDbStr::jsonDbUuid(), jsondbItemId.jsondbUuid()); - if (makeJsonDbRequest(JsonDbRemoveRequest, i, jsondbItemId.storageLocation(), QString(), QList<QJsonObject>() << jsonDbItem)) - requestSent = true; - } - if (!requestSent) - m_syncWaitCondition.wakeAll(); -} - -void QOrganizerJsonDbDataStorage::handleRemoveItemsResponse(int index, QOrganizerManager::Error error) -{ - if (error != QOrganizerManager::NoError) { - *m_error = error; - m_errorMap->insert(index, *m_error); - } - if (m_requestIndexMap.isEmpty()) { - // All transactions have been handled, request has been completed - m_syncWaitCondition.wakeAll(); - } -} - -void QOrganizerJsonDbDataStorage::handleSaveCollectionsRequest() -{ - bool requestSent = false; - QMap<int, QOrganizerCollection>::const_iterator i = m_resultCollections->constBegin(); - while (i != m_resultCollections->constEnd()) { - QOrganizerCollection collection = i.value(); - bool collectionIsNew = collection.id().isNull(); - - // check whether this is a default collection - // if we are creating a new default collection, then m_isDefaultCollection is true - // if we are modifying an existing default collection, then collection id should be the same - // as m_defaultCollection id. - - // ignore storageLocation on request, if collection is updated (it has been saved already atleast once) - - bool convertToDefaultCollection; - QOrganizerJsonDbEngine::StorageLocation storageLocation(QOrganizerJsonDbEngine::UserDataStorage); - if (collectionIsNew) { - convertToDefaultCollection = m_isDefaultCollection; - // first save, storage location given in request. if not, by default store to UserData. - storageLocation = m_saveToStorageLocation ? m_saveToStorageLocation : QOrganizerJsonDbEngine::UserDataStorage; - } else { - const QOrganizerJsonDbCollectionId *collectionIdPtr = static_cast<const QOrganizerJsonDbCollectionId *>(QOrganizerManagerEngine::engineCollectionId(collection.id())); - if (collectionIdPtr) { - convertToDefaultCollection = (collection.id() == m_defaultCollection.id()); - // collection has already been saved before, so we get storage location from id - storageLocation = collectionIdPtr->storageLocation(); - } - } - - QJsonObject jsonDbCollection; - if (m_converter.collectionToJsonDbObject(collection, convertToDefaultCollection, &jsonDbCollection)) { - JsonDbRequestType requestType; - if (collectionIsNew) - requestType = JsonDbCreateRequest; - else - requestType = JsonDbUpdateRequest; - if (makeJsonDbRequest(requestType, i.key(), storageLocation, QString(), QList<QJsonObject>() << jsonDbCollection)) - requestSent = true; - } else { - *m_error = QOrganizerManager::InvalidCollectionError; - m_errorMap->insert(i.key(), *m_error); - } - ++i; - } - if (!requestSent) - m_syncWaitCondition.wakeAll(); -} - -void QOrganizerJsonDbDataStorage::handleSaveCollectionsResponse(int index, QOrganizerManager::Error error, QJsonDbRequest *request) -{ - if (error == QOrganizerManager::NoError) { - QOrganizerCollection collection = m_resultCollections->value(index); - if (collection.id().isNull()) { - QList<QJsonObject> results = request->takeResults(); - if (results.size() > 0) { - QString jsonUuid = results.at(0).value(QOrganizerJsonDbStr::jsonDbUuid()).toString(); - if (!jsonUuid.isEmpty()) { - QOrganizerJsonDbCollectionId *collectionId = new QOrganizerJsonDbCollectionId; - collectionId->setJsonDbUuid(jsonUuid); - collectionId->setStorageLocation(m_converter.storageLocationStringToEnum(request->partition())); - collection.setId(QOrganizerCollectionId(collectionId)); - m_collectionIds.insert(collection.id()); - // have we modified default collection - if (collection.id() == m_defaultCollection.id()) - m_defaultCollection = collection; - } - } - m_resultCollections->insert(index, collection); - } - } else { - *m_error = error; - m_errorMap->insert(index, *m_error); - } - if (m_requestIndexMap.isEmpty()) { - // All transactions have been handled, request has been completed - m_syncWaitCondition.wakeAll(); - } -} - -void QOrganizerJsonDbDataStorage::handleCollectionsRequest() -{ - foreach (QOrganizerJsonDbEngine::StorageLocation location, m_availableStorageLocations) { - if (m_fetchFromStorageLocations & location) - makeJsonDbRequest(JsonDbReadRequest, 0, location, QOrganizerJsonDbStr::jsonDbQueryAllCollections()); - } - - if (m_requestIndexMap.isEmpty()) - m_syncWaitCondition.wakeAll(); -} - -void QOrganizerJsonDbDataStorage::handleCollectionsResponse(QOrganizerManager::Error error, QJsonDbRequest *request) -{ - if (error == QOrganizerManager::NoError) { - QList<QJsonObject> results = request->takeResults(); - for (int i = 0; i < results.size(); ++i) { - QOrganizerCollection collection; - bool isDefaultCollection(false); - if (m_converter.jsonDbObjectToCollection(results.at(i), &collection, &isDefaultCollection, m_converter.storageLocationStringToEnum(request->partition()))) { - if (isDefaultCollection) - m_defaultCollection = collection; - m_collections.append(collection); - m_collectionIds.insert(collection.id()); - } - } - } else { - *m_error = error; - } - - if (m_requestIndexMap.isEmpty()) { - // All transactions have been handled, request has been completed - m_syncWaitCondition.wakeAll(); - } -} - -void QOrganizerJsonDbDataStorage::handleRemoveCollectionsRequest() -{ - QMap<int, QOrganizerCollectionId>::const_iterator i = m_removeCollectionIds.constBegin(); - while (i != m_removeCollectionIds.constEnd()) { - QJsonObject jsonDbObject; - const QOrganizerCollectionEngineId *collectionIdPtr = QOrganizerManagerEngine::engineCollectionId(i.value()); - if (collectionIdPtr) { - QOrganizerJsonDbCollectionId jsondbCollectionId(collectionIdPtr->toString()); - jsonDbObject.insert(QOrganizerJsonDbStr::jsonDbUuid(), jsondbCollectionId.jsondbUuid()); - makeJsonDbRequest(JsonDbRemoveRequest, 0, jsondbCollectionId.storageLocation(), QString(), QList<QJsonObject>() << jsonDbObject); - } - ++i; - } - - if (m_requestIndexMap.isEmpty()) - m_syncWaitCondition.wakeAll(); -} - -void QOrganizerJsonDbDataStorage::handleRemoveCollectionsResponse(QOrganizerManager::Error error) -{ - if (error == QOrganizerManager::NoError) { - QMap<int, QOrganizerCollectionId>::const_iterator i = m_removeCollectionIds.constBegin(); - while (i != m_removeCollectionIds.constEnd()) { - m_collectionIds.remove(i.value()); - ++i; - } - } else { - *m_error = error; - QMap<int, QOrganizerCollectionId>::const_iterator i = m_removeCollectionIds.constBegin(); - while (i != m_removeCollectionIds.constEnd()) { - m_errorMap->insert(i.key(), error); - ++i; - } - } - m_syncWaitCondition.wakeAll(); -} - -bool QOrganizerJsonDbDataStorage::makeJsonDbRequest( - JsonDbRequestType jsonDbRequestType, int index, QOrganizerJsonDbEngine::StorageLocation storageLocation, const QString &query, const QList<QJsonObject> &objects) -{ - QJsonDbRequest *request = 0; - switch (jsonDbRequestType) { - case JsonDbReadRequest: - request = new QJsonDbReadRequest(query, this); - break; - case JsonDbCreateRequest: - request = new QJsonDbCreateRequest(objects, this); - break; - case JsonDbUpdateRequest: - request = new QJsonDbUpdateRequest(objects, this); - break; - case JsonDbRemoveRequest: - request = new QJsonDbRemoveRequest(objects, this); - break; - default: - return false; - } - QJsonDbWriteRequest *writeRequest = qobject_cast<QJsonDbWriteRequest*>(request); - if (writeRequest) - writeRequest->setConflictResolutionMode(QJsonDbWriteRequest::Replace); - const QStringList storageLocationStrings = m_converter.storageLocationsFlagToStrings(storageLocation); - request->setPartition(storageLocationStrings.isEmpty() ? - m_converter.storageLocationsFlagToStrings(QOrganizerJsonDbEngine::UserDataStorage).first() : - storageLocationStrings.first()); - - connect(request, SIGNAL(error(QtJsonDb::QJsonDbRequest::ErrorCode,QString)), - this, SLOT(onJsonDbRequestError(QtJsonDb::QJsonDbRequest::ErrorCode,QString))); - connect(request, SIGNAL(finished()), this, SLOT(onJsonDbRequestFinished())); - - if (m_jsonDbConnection->send(request)) { - m_requestIndexMap.insert(request, index); - return true; - } else { - delete request; - *m_error = QOrganizerManager::UnspecifiedError; - if (m_errorMap) - m_errorMap->insert(index, QOrganizerManager::UnspecifiedError); - } - return false; -} - -void QOrganizerJsonDbDataStorage::processRequest() -{ - // storage location related checks - if (m_mandatoryStorageLocationMissing) { - *m_error = QOrganizerManager::UnspecifiedError; - return; - } - - emit requestInitialized(); - QMutexLocker locker(m_waitMutex); - int msecs = 10000; // TODO: handle timeout nicely - bool requestFinished = m_syncWaitCondition.wait(m_waitMutex, msecs); - if (!requestFinished) { - qWarning() << "Timeout, no response received!!!"; - // timeout TODO: check which items have completed and update error map accordingly... - } -} - -void QOrganizerJsonDbDataStorage::initRequestData(RequestType requestType, QMap<int, QOrganizerManager::Error>* errorMap, QOrganizerManager::Error* error) -{ - m_requestType = requestType; - m_errorMap = errorMap; - m_error = error; - m_requestIndexMap.clear(); - m_resultItems = 0; - m_resultCollections = 0; - m_idItemMap.clear(); - m_items.clear(); - QOrganizerItemId tmpId; - m_parentItemId = tmpId; - m_fetchType = NoFetch; - m_itemIds.clear(); - m_collections.clear(); - m_removeItemCollectionIds.clear(); - m_removeItemParentIds.clear(); - m_removeCollectionIds.clear(); - m_isDefaultCollection = false; - m_saveToStorageLocation = QOrganizerJsonDbEngine::UserDataStorage; - m_fetchFromStorageLocations = 0; -} - -void QOrganizerJsonDbDataStorage::clearRequestData() -{ - m_requestType = Invalid; - m_errorMap = 0; - m_error = 0; - m_requestIndexMap.clear(); - m_resultItems = 0; - m_resultCollections = 0; - m_idItemMap.clear(); - m_items.clear(); - QOrganizerItemId tmpId; - m_parentItemId = tmpId; - m_fetchType = NoFetch; - m_itemIds.clear(); - m_collections.clear(); - m_removeItemCollectionIds.clear(); - m_removeItemParentIds.clear(); - m_removeCollectionIds.clear(); - m_isDefaultCollection = false; - m_saveToStorageLocation = QOrganizerJsonDbEngine::UserDataStorage; - m_fetchFromStorageLocations = 0; -} - -#include "moc_qorganizerjsondbdatastorage.cpp" - -QT_END_NAMESPACE_ORGANIZER diff --git a/src/plugins/organizer/jsondb/qorganizerjsondbdatastorage.h b/src/plugins/organizer/jsondb/qorganizerjsondbdatastorage.h deleted file mode 100644 index 0e9161741..000000000 --- a/src/plugins/organizer/jsondb/qorganizerjsondbdatastorage.h +++ /dev/null @@ -1,243 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtOrganizer module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QORGANIZERJSONDBDATASTORAGE_H -#define QORGANIZERJSONDBDATASTORAGE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/qthread.h> -#include <QtCore/qwaitcondition.h> - -#include <QtJsonDb/qjsondbconnection.h> -#include <QtJsonDb/qjsondbwatcher.h> - -#include "qorganizerjsondbconverter.h" - -QT_USE_NAMESPACE_JSONDB - -QT_BEGIN_NAMESPACE_ORGANIZER - -// The purpose of this class is to provide synchronous access to jsondb and also hide jsondb -// specific details such as filter creation and object conversions. -// All public methods of this class are called from the thread of the caller. The functions store -// their parameters to member variables, emit request signal and start to wait until the request has -// been completed. The request signal is handled in the separate thread. Handler functions typically -// start jsondb requests. When responses are received from jsondb, results are stored to member variables -// and waiting caller thread is woken up. - - -class QOrganizerJsonDbDataStorage: public QThread -{ - Q_OBJECT - -public: - enum FetchType { - NoFetch, - FetchItems, - FetchItemIds, - FetchItemOccurrences, - FetchParents - }; - - QOrganizerJsonDbDataStorage(); - ~QOrganizerJsonDbDataStorage(); - - void saveItems(QMap<int, QOrganizerItem>* items, QMap<int, QOrganizerManager::Error>* errorMap, QOrganizerManager::Error* error, QOrganizerJsonDbEngine::StorageLocation storageLocation); - QList<QOrganizerItem> items(const QDateTime& startDate, const QDateTime& endDate, const QOrganizerItemFilter& filter, const QList<QOrganizerItemSortOrder>& sortOrders, - const QOrganizerItemFetchHint& fetchHint, QOrganizerManager::Error* error, QOrganizerJsonDbEngine::StorageLocations storageLocations, FetchType type = FetchItems, const QOrganizerItemId &parentId = QOrganizerItemId()); - QList<QOrganizerItem> itemsById(const QList<QOrganizerItemId>& itemIds, QMap<int, QOrganizerManager::Error>* errorMap, QOrganizerManager::Error* error, QOrganizerJsonDbEngine::StorageLocations storageLocations); - void removeItems(const QList<QOrganizerItemId>& itemIds, QMap<int, QOrganizerManager::Error>* errorMap, QOrganizerManager::Error* error); - - void saveCollections(QMap<int, QOrganizerCollection>* collections, QMap<int, QOrganizerManager::Error>* errorMap, QOrganizerManager::Error* error, QOrganizerJsonDbEngine::StorageLocation storageLocation); - QList<QOrganizerCollection> collections(QOrganizerManager::Error* error, QOrganizerJsonDbEngine::StorageLocations storageLocations); - void removeCollections(const QMap<int, QOrganizerCollectionId>& collectionIds, QMap<int, QOrganizerManager::Error>* errorMap, QOrganizerManager::Error* error); - - void createDefaultCollection(QOrganizerCollection* defaultCollection, QOrganizerManager::Error* error); - QOrganizerCollection defaultCollection(); - QSet<QOrganizerCollectionId> collectionIds(); - - QOrganizerJsonDbEngine::StorageLocations availableStorageLocationsFlag() const; - -signals: - void threadInitialized(); - void requestInitialized(); - - void itemAdded(const QOrganizerItemId &itemId); - void itemChanged(const QOrganizerItemId &itemId); - void itemRemoved(const QOrganizerItemId &itemId); - void collectionAdded(const QOrganizerCollectionId &collectionId); - void collectionChanged(const QOrganizerCollectionId &collectionId); - void collectionRemoved(const QOrganizerCollectionId &collectionId); - -protected: - virtual void run(); - -private slots: - void handleRequest(); - - void onJsonDbConnectionError(QtJsonDb::QJsonDbConnection::ErrorCode error, const QString &message); - void onJsonDbRequestError(QtJsonDb::QJsonDbRequest::ErrorCode error, const QString &message); - void onJsonDbRequestFinished(); - void onJsonDbWatcherError(QtJsonDb::QJsonDbWatcher::ErrorCode error, const QString &message); - void onJsonDbWatcherNotificationsAvailable(); - -private: - enum RequestType { - Invalid, - SaveItems, - Items, - ItemsById, - RemoveItems, - SaveCollections, - Collections, - RemoveCollections - }; - - void handleResponse(QOrganizerManager::Error error, QJsonDbRequest *request); - void handleSaveItemsRequest(); - void handleSaveItemsResponse(int index, QOrganizerManager::Error error, QJsonDbRequest *request); - void handleItemsRequest(); - void handleItemsResponse(QOrganizerManager::Error error, QJsonDbRequest *request); - void handleItemsByIdRequest(); - void handleItemsByIdResponse(QOrganizerManager::Error error, QJsonDbRequest *request); - void handleRemoveItemsRequest(); - void handleRemoveItemsResponse(int index, QOrganizerManager::Error error); - void handleSaveCollectionsRequest(); - void handleSaveCollectionsResponse(int index, QOrganizerManager::Error error, QJsonDbRequest *request); - void handleCollectionsRequest(); - void handleCollectionsResponse(QOrganizerManager::Error error, QJsonDbRequest *request); - void handleRemoveCollectionsRequest(); - void handleRemoveCollectionsResponse(QOrganizerManager::Error error); - void handleSaveAlarmRequest(); - void handleSaveAlarmResponse(QOrganizerManager::Error error); - void handleAlarmIdRequest(); - void handleAlarmIdResponse(QOrganizerManager::Error error, QJsonDbRequest *request); - void handleRemoveAlarmRequest(); - void handleRemoveAlarmResponse(QOrganizerManager::Error error); - - enum JsonDbRequestType { - JsonDbReadRequest = 0, - JsonDbCreateRequest, - JsonDbUpdateRequest, - JsonDbRemoveRequest - }; - bool makeJsonDbRequest(JsonDbRequestType jsonDbRequestType, int index, QOrganizerJsonDbEngine::StorageLocation storageLocation, const QString &query = QString(), const QList<QJsonObject> &objects = QList<QJsonObject>()); - - void processRequest(); - void initRequestData(RequestType requestType, QMap<int, QOrganizerManager::Error>* errorMap, QOrganizerManager::Error* error); - void clearRequestData(); - void registerForNotifications(); - - QMutex* m_waitMutex; - QWaitCondition m_syncWaitCondition; - - QOrganizerJsonDbConverter m_converter; - QJsonDbConnection *m_jsonDbConnection; - - // "collection cache" - QSet<QOrganizerCollectionId> m_collectionIds; - QOrganizerCollection m_defaultCollection; - - QString m_notificationObjectUuid; - QList<QJsonDbWatcher*> m_watchers; - - // request data - - // common - RequestType m_requestType; - QMap<QJsonDbRequest *, int> m_requestIndexMap; // map from request to item / collection index - QMap<int, QOrganizerManager::Error>* m_errorMap; - QOrganizerManager::Error* m_error; - - // storage location - QList<QOrganizerJsonDbEngine::StorageLocation> m_availableStorageLocations; - QOrganizerJsonDbEngine::StorageLocations m_availableStorageLocationsFlag; - QOrganizerJsonDbEngine::StorageLocation m_saveToStorageLocation; - QOrganizerJsonDbEngine::StorageLocations m_fetchFromStorageLocations; - bool m_mandatoryStorageLocationMissing; - - // SaveItems - QMap<int, QOrganizerItem>* m_resultItems; // map from item index to item - - // Items - QList<QOrganizerItem> m_items; - QDateTime m_start; - QDateTime m_end; - QOrganizerItemFilter m_filter; -// QList<QOrganizerItemSortOrder> m_sortOrders; -// QOrganizerItemFetchHint m_fetchHint; - FetchType m_fetchType; - QOrganizerItemId m_parentItemId; - QHash<QOrganizerItemId, QOrganizerItem> m_idItemMap; - - // RemoveItems (itemsById) - QList<QOrganizerItemId> m_itemIds; - - // RemoveItemsByCollectionId - QList<QOrganizerCollectionId> m_removeItemCollectionIds; - - // RemoveItemsByParentId - QList<QOrganizerItemId> m_removeItemParentIds; - - // SaveCollection - QMap<int, QOrganizerCollection>* m_resultCollections; // map from collection index to collection - bool m_isDefaultCollection; - - // Collections - QList<QOrganizerCollection> m_collections; - - // RemoveCollections - QMap<int, QOrganizerCollectionId> m_removeCollectionIds; -}; - -QT_END_NAMESPACE_ORGANIZER - -#endif // QORGANIZERJSONDBDATASTORAGE_H diff --git a/src/plugins/organizer/jsondb/qorganizerjsondbengine.cpp b/src/plugins/organizer/jsondb/qorganizerjsondbengine.cpp deleted file mode 100644 index 5cd1d86e8..000000000 --- a/src/plugins/organizer/jsondb/qorganizerjsondbengine.cpp +++ /dev/null @@ -1,611 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtOrganizer module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qorganizerjsondbengine.h" - -#include <QtCore/qeventloop.h> - -#include <QtNetwork/qabstractsocket.h> - -#include <QtOrganizer/qorganizeritemdetails.h> - -#include "qorganizerjsondbrequestthread.h" -#include "qorganizerjsondbstring.h" - -QT_BEGIN_NAMESPACE_ORGANIZER - -QOrganizerJsonDbEngine::QOrganizerJsonDbEngine(QOrganizerManager::Error *error) - : m_requestHandlerThread(new QOrganizerJsonDbRequestThread) -{ - // Register types to be able to send them as parameters in cross-thread signals - qRegisterMetaType<QOrganizerAbstractRequest::State>("QOrganizerAbstractRequest::State"); - qRegisterMetaType<QList<QOrganizerItemId> >("QList<QOrganizerItemId>"); - qRegisterMetaType<QList<QOrganizerCollectionId> >("QList<QOrganizerCollectionId>"); - qRegisterMetaType<QAbstractSocket::SocketState>("QAbstractSocket::SocketState"); - qRegisterMetaType<QList<QPair<QOrganizerItemId, QOrganizerManager::Operation> > >("QList<QPair<QOrganizerItemId,QOrganizerManager::Operation> >"); - qRegisterMetaType<QList<QPair<QOrganizerCollectionId, QOrganizerManager::Operation> > >("QList<QPair<QOrganizerCollectionId,QOrganizerManager::Operation> >"); - qRegisterMetaType<QOrganizerItemId>("QOrganizerItemId"); - qRegisterMetaType<QOrganizerCollectionId>("QOrganizerCollectionId"); - - m_requestHandlerThread->moveToThread(m_requestHandlerThread); - // making sure that thread is started before exiting this function - QEventLoop loop; - connect(m_requestHandlerThread, SIGNAL(initialized()), &loop, SLOT(quit())); - m_requestHandlerThread->start(); - loop.exec(); - connect(this, SIGNAL(requestReceived(QOrganizerAbstractRequest*)), - m_requestHandlerThread, SLOT(handleRequest(QOrganizerAbstractRequest*))); - m_requestHandlerThread->setEngine(this); - - *error = QOrganizerManager::NoError; -} - -QOrganizerJsonDbEngine::~QOrganizerJsonDbEngine() -{ - if (m_requestHandlerThread) { - m_requestHandlerThread->exit(); - m_requestHandlerThread->wait(); - delete m_requestHandlerThread; - } -} - -QString QOrganizerJsonDbEngine::managerName() const -{ - return QOrganizerJsonDbStr::jsonDbManagerName(); -} - -QMap<QString, QString> QOrganizerJsonDbEngine::managerParameters() const -{ - /* TODO - in case you have any actual parameters that are relevant that you saved in the factory method, return them here */ - return QMap<QString, QString>(); -} - -QList<QOrganizerItem> QOrganizerJsonDbEngine::itemOccurrences(const QOrganizerItem &parentItem, - const QDateTime &startDateTime, - const QDateTime &endDateTime, int maxCount, - const QOrganizerItemFetchHint &fetchHint, - QOrganizerManager::Error *error) -{ - QOrganizerItemOccurrenceFetchRequest occurrenceFetchReq; - occurrenceFetchReq.setParentItem(parentItem); - occurrenceFetchReq.setStartDate(startDateTime); - occurrenceFetchReq.setEndDate(endDateTime); - occurrenceFetchReq.setMaxOccurrences(maxCount); - occurrenceFetchReq.setFetchHint(fetchHint); - *error = QOrganizerManager::NoError; - - startRequest(&occurrenceFetchReq); - if (waitForRequestFinished(&occurrenceFetchReq, 0)) { - *error = occurrenceFetchReq.error(); - return occurrenceFetchReq.itemOccurrences(); - } - return QList<QOrganizerItem>(); -} - -QList<QOrganizerItemId> QOrganizerJsonDbEngine::itemIds(const QOrganizerItemFilter &filter, - const QDateTime &startDateTime, const QDateTime &endDateTime, - const QList<QOrganizerItemSortOrder> &sortOrders, - QOrganizerManager::Error *error) -{ - QOrganizerItemIdFetchRequest idFetchReq; - idFetchReq.setStartDate(startDateTime); - idFetchReq.setEndDate(endDateTime); - idFetchReq.setFilter(filter); - idFetchReq.setSorting(sortOrders); - if (startRequest(&idFetchReq)) { - if (waitForRequestFinished(&idFetchReq, 0)) - *error = idFetchReq.error(); - else - *error = QOrganizerManager::TimeoutError; - return idFetchReq.itemIds(); - } else { - *error = QOrganizerManager::NotSupportedError; - return QList<QOrganizerItemId>(); - } -} - -QList<QOrganizerItem> QOrganizerJsonDbEngine::items(const QOrganizerItemFilter &filter, const QDateTime &startDateTime, - const QDateTime &endDateTime, int maxCount, - const QList<QOrganizerItemSortOrder> &sortOrders, - const QOrganizerItemFetchHint &fetchHint, QOrganizerManager::Error *error) -{ - QOrganizerItemFetchRequest request; - request.setFilter(filter); - request.setStartDate(startDateTime); - request.setEndDate(endDateTime); - request.setMaxCount(maxCount); - request.setSorting(sortOrders); - request.setFetchHint(fetchHint); - - if (startRequest(&request)) { - if (waitForRequestFinished(&request, 0)) - *error = request.error(); - else - *error = QOrganizerManager::TimeoutError; - return request.items(); - } else { - *error = QOrganizerManager::NotSupportedError; - return QList<QOrganizerItem>(); - } -} - -QList<QOrganizerItem> QOrganizerJsonDbEngine::itemsForExport(const QDateTime &startDateTime, - const QDateTime &endDateTime, - const QOrganizerItemFilter &filter, - const QList<QOrganizerItemSortOrder> &sortOrders, - const QOrganizerItemFetchHint &fetchHint, - QOrganizerManager::Error *error) -{ - QOrganizerItemFetchForExportRequest request; - request.setStartDate(startDateTime); - request.setEndDate(endDateTime); - request.setFilter(filter); - request.setSorting(sortOrders); - request.setFetchHint(fetchHint); - if (startRequest(&request)) { - if (waitForRequestFinished(&request, 0)) - *error = request.error(); - else - *error = QOrganizerManager::TimeoutError; - return request.items(); - } else { - *error = QOrganizerManager::NotSupportedError; - return QList<QOrganizerItem>(); - } -} - -QList<QOrganizerItem> QOrganizerJsonDbEngine::items(const QList<QOrganizerItemId> &itemIds, const QOrganizerItemFetchHint &fetchHint, - QMap<int, QOrganizerManager::Error> *errorMap, QOrganizerManager::Error *error) -{ - QOrganizerItemFetchByIdRequest fetchByIdReq; - fetchByIdReq.setIds(itemIds); - fetchByIdReq.setFetchHint(fetchHint); - if (startRequest(&fetchByIdReq)) { - if (waitForRequestFinished(&fetchByIdReq, 0)) { - *error = fetchByIdReq.error(); - *errorMap = fetchByIdReq.errorMap(); - } else { - *error = QOrganizerManager::TimeoutError; - } - return fetchByIdReq.items(); - } else { - *error = QOrganizerManager::NotSupportedError; - return QList<QOrganizerItem>(); - } -} - -bool QOrganizerJsonDbEngine::saveItems(QList<QOrganizerItem> *items, const QList<QOrganizerItemDetail::DetailType> &detailMask, - QMap<int, QOrganizerManager::Error> *errorMap, QOrganizerManager::Error *error) -{ - QOrganizerItemSaveRequest request; - request.setItems(*items); - request.setDetailMask(detailMask); - if (startRequest(&request)) { - if (waitForRequestFinished(&request, 0)) { - *error = request.error(); - *errorMap = request.errorMap(); - } else { - *error = QOrganizerManager::TimeoutError; - } - *items = request.items(); - return (*error == QOrganizerManager::NoError); - } else { - *error = QOrganizerManager::NotSupportedError; - return false; - } -} - -bool QOrganizerJsonDbEngine::removeItems(const QList<QOrganizerItemId> &itemIds, QMap<int, QOrganizerManager::Error> *errorMap, - QOrganizerManager::Error *error) -{ - QOrganizerItemRemoveByIdRequest removeByIdReq; - removeByIdReq.setItemIds(itemIds); - startRequest(&removeByIdReq); - - if (waitForRequestFinished(&removeByIdReq, 0)) { - *errorMap = removeByIdReq.errorMap(); - *error = removeByIdReq.error(); - } - return *error == QOrganizerManager::NoError; -} - -bool QOrganizerJsonDbEngine::removeItems(const QList<QOrganizerItem> *items, QMap<int, QOrganizerManager::Error>* errorMap, QOrganizerManager::Error* error) -{ - QOrganizerItemRemoveRequest removeReq; - removeReq.setItems(*items); - if (startRequest(&removeReq)) { - if (waitForRequestFinished(&removeReq, 0)) { - *errorMap = removeReq.errorMap(); - *error = removeReq.error(); - } else { - *error = QOrganizerManager::TimeoutError; - } - } else { - *error = QOrganizerManager::NotSupportedError; - } - return (*error == QOrganizerManager::NoError); -} - -QOrganizerCollection QOrganizerJsonDbEngine::defaultCollection(QOrganizerManager::Error* error) -{ - *error = QOrganizerManager::NoError; - return m_requestHandlerThread->defaultCollection(); -} - -QOrganizerCollection QOrganizerJsonDbEngine::collection(const QOrganizerCollectionId& collectionId, QOrganizerManager::Error* error) -{ - *error = QOrganizerManager::NoError; - QList<QOrganizerCollection> collectionList = collections(error); - for (int i = 0; i < collectionList.size(); i++) { - if (collectionList[i].id() == collectionId) - return collectionList[i]; - } - *error = QOrganizerManager::DoesNotExistError; - return QOrganizerCollection(); -} - -QList<QOrganizerCollection> QOrganizerJsonDbEngine::collections(QOrganizerManager::Error* error) -{ - QOrganizerCollectionFetchRequest collectionFetchReq; - if (startRequest(&collectionFetchReq)) { - if (waitForRequestFinished(&collectionFetchReq, 0)) - *error = collectionFetchReq.error(); - else - *error = QOrganizerManager::TimeoutError; - return collectionFetchReq.collections(); - } else { - *error = QOrganizerManager::NotSupportedError; - return QList<QOrganizerCollection>(); - } -} - -bool QOrganizerJsonDbEngine::saveCollection(QOrganizerCollection* collection, QOrganizerManager::Error* error) -{ - QOrganizerCollectionSaveRequest collectionSaveReq; - collectionSaveReq.setCollection(*collection); - if (startRequest(&collectionSaveReq)) { - if (waitForRequestFinished(&collectionSaveReq, 0)) - *error = collectionSaveReq.error(); - else - *error = QOrganizerManager::TimeoutError; - *collection = collectionSaveReq.collections().at(0); - return *error == QOrganizerManager::NoError; - } else { - *error = QOrganizerManager::NotSupportedError; - return false; - } -} - -bool QOrganizerJsonDbEngine::removeCollection(const QOrganizerCollectionId& collectionId, QOrganizerManager::Error* error) -{ - QOrganizerCollectionRemoveRequest collectionRemoveReq; - collectionRemoveReq.setCollectionId(collectionId); - if (startRequest(&collectionRemoveReq)) { - if (waitForRequestFinished(&collectionRemoveReq, 0)) - *error = collectionRemoveReq.error(); - else - *error = QOrganizerManager::TimeoutError; - return *error == QOrganizerManager::NoError; - } else { - *error = QOrganizerManager::NotSupportedError; - return false; - } -} - -bool QOrganizerJsonDbEngine::startRequest(QOrganizerAbstractRequest* req) -{ - QList<QOrganizerItem> itemList; - QList<QOrganizerItemId> idList; - QList<QOrganizerCollection> collectionList; - QOrganizerManager::Error error = QOrganizerManager::NoError; - QMap<int, QOrganizerManager::Error> errorMap; - m_requestHandlerThread->addRequest(req); - - switch (req->type()) { - case QOrganizerAbstractRequest::ItemFetchRequest: { - QOrganizerManagerEngine::updateItemFetchRequest(static_cast<QOrganizerItemFetchRequest*>(req), - itemList, error, QOrganizerAbstractRequest::ActiveState); - break; - } - case QOrganizerAbstractRequest::ItemIdFetchRequest: { - QOrganizerManagerEngine::updateItemIdFetchRequest(static_cast<QOrganizerItemIdFetchRequest*>(req), - idList, error, QOrganizerAbstractRequest::ActiveState); - break; - } - case QOrganizerAbstractRequest::ItemFetchByIdRequest: { - QOrganizerManagerEngine:: updateItemFetchByIdRequest(static_cast<QOrganizerItemFetchByIdRequest*>(req), - itemList, error, errorMap, QOrganizerAbstractRequest::ActiveState); - break; - } - case QOrganizerAbstractRequest::ItemFetchForExportRequest: { - QOrganizerManagerEngine::updateItemFetchForExportRequest(static_cast<QOrganizerItemFetchForExportRequest*>(req), - itemList, error, QOrganizerAbstractRequest::ActiveState); - break; - } - case QOrganizerAbstractRequest::ItemOccurrenceFetchRequest: { - QOrganizerManagerEngine::updateItemOccurrenceFetchRequest(static_cast<QOrganizerItemOccurrenceFetchRequest*>(req), - itemList, error, QOrganizerAbstractRequest::ActiveState); - break; - } - case QOrganizerAbstractRequest::ItemSaveRequest: { - QOrganizerItemSaveRequest* saveReq = static_cast<QOrganizerItemSaveRequest*>(req); - itemList = saveReq->items(); - QOrganizerManagerEngine::updateItemSaveRequest(saveReq, itemList, error, errorMap, QOrganizerAbstractRequest::ActiveState); - break; - } - case QOrganizerAbstractRequest::ItemRemoveRequest: { - QOrganizerManagerEngine::updateItemRemoveRequest(static_cast<QOrganizerItemRemoveRequest*>(req), - error, errorMap, QOrganizerAbstractRequest::ActiveState); - break; - } - case QOrganizerAbstractRequest::ItemRemoveByIdRequest: { - QOrganizerManagerEngine::updateItemRemoveByIdRequest(static_cast<QOrganizerItemRemoveByIdRequest*>(req), - error, errorMap, QOrganizerAbstractRequest::ActiveState); - break; - } - case QOrganizerAbstractRequest::CollectionFetchRequest: { - QOrganizerManagerEngine::updateCollectionFetchRequest(static_cast<QOrganizerCollectionFetchRequest*>(req), - collectionList, error, QOrganizerAbstractRequest::ActiveState); - break; - } - case QOrganizerAbstractRequest::CollectionSaveRequest: { - QOrganizerCollectionSaveRequest* collectionSaveReq = static_cast<QOrganizerCollectionSaveRequest*>(req); - collectionList = collectionSaveReq->collections(); - QOrganizerManagerEngine::updateCollectionSaveRequest(collectionSaveReq, collectionList, error, errorMap, QOrganizerAbstractRequest::ActiveState); - break; - } - case QOrganizerAbstractRequest::CollectionRemoveRequest: { - QOrganizerCollectionRemoveRequest* collectionRemoveReq = static_cast<QOrganizerCollectionRemoveRequest*>(req); - QOrganizerManagerEngine::updateCollectionRemoveRequest(collectionRemoveReq, error, errorMap, QOrganizerAbstractRequest::ActiveState); - break; - } - default: - return false; - } - - emit requestReceived(req); - return true; -} - -bool QOrganizerJsonDbEngine::cancelRequest(QOrganizerAbstractRequest* req) -{ - /* - TODO - - Cancel an in progress async request. If not possible, return false from here. - */ - return QOrganizerManagerEngine::cancelRequest(req); -} - -bool QOrganizerJsonDbEngine::waitForRequestFinished(QOrganizerAbstractRequest* req, int msecs) -{ - return m_requestHandlerThread->waitForRequestFinished(req, msecs); -} - -void QOrganizerJsonDbEngine::requestDestroyed(QOrganizerAbstractRequest* req) -{ - m_requestHandlerThread->requestDestroyed(req); -} - -QList<QOrganizerItemFilter::FilterType> QOrganizerJsonDbEngine::supportedFilters() const -{ - QList<QOrganizerItemFilter::FilterType> supported; - - supported << QOrganizerItemFilter::InvalidFilter - << QOrganizerItemFilter::DetailFilter - << QOrganizerItemFilter::DetailFieldFilter - << QOrganizerItemFilter::IntersectionFilter - << QOrganizerItemFilter::UnionFilter - << QOrganizerItemFilter::IdFilter - << QOrganizerItemFilter::CollectionFilter - << QOrganizerItemFilter::DefaultFilter; - - return supported; -} - -QList<QOrganizerItemDetail::DetailType> QOrganizerJsonDbEngine::supportedItemDetails(QOrganizerItemType::ItemType itemType) const -{ - QList<QOrganizerItemDetail::DetailType> supportedDetails; - supportedDetails << QOrganizerItemDetail::TypeItemType - << QOrganizerItemDetail::TypeGuid -// << QOrganizerItemDetail::TypeTimestamp - << QOrganizerItemDetail::TypeDisplayLabel - << QOrganizerItemDetail::TypeDescription - << QOrganizerItemDetail::TypeComment - << QOrganizerItemDetail::TypeTag - << QOrganizerItemDetail::TypeExtendedDetail - << QOrganizerItemDetail::TypeVersion; - - if (itemType == QOrganizerItemType::TypeEvent) { - supportedDetails << QOrganizerItemDetail::TypeRecurrence - << QOrganizerItemDetail::TypeEventTime - << QOrganizerItemDetail::TypePriority - << QOrganizerItemDetail::TypeLocation - << QOrganizerItemDetail::TypeReminder - << QOrganizerItemDetail::TypeAudibleReminder - << QOrganizerItemDetail::TypeEventAttendee - << QOrganizerItemDetail::TypeEventRsvp; - } else if (itemType == QOrganizerItemType::TypeTodo) { - supportedDetails << QOrganizerItemDetail::TypeRecurrence - << QOrganizerItemDetail::TypeTodoTime - << QOrganizerItemDetail::TypePriority - << QOrganizerItemDetail::TypeTodoProgress - << QOrganizerItemDetail::TypeReminder - << QOrganizerItemDetail::TypeAudibleReminder; - } else if (itemType == QOrganizerItemType::TypeEventOccurrence) { - supportedDetails << QOrganizerItemDetail::TypeParent - << QOrganizerItemDetail::TypeEventTime - << QOrganizerItemDetail::TypePriority - << QOrganizerItemDetail::TypeLocation - << QOrganizerItemDetail::TypeReminder - << QOrganizerItemDetail::TypeAudibleReminder - << QOrganizerItemDetail::TypeEventAttendee - << QOrganizerItemDetail::TypeEventRsvp; - } else if (itemType == QOrganizerItemType::TypeTodoOccurrence) { - supportedDetails << QOrganizerItemDetail::TypeParent - << QOrganizerItemDetail::TypeTodoTime - << QOrganizerItemDetail::TypePriority - << QOrganizerItemDetail::TypeTodoProgress - << QOrganizerItemDetail::TypeReminder - << QOrganizerItemDetail::TypeAudibleReminder; - } else { - // We don't support Journal and Note, yet ;) - supportedDetails.clear(); - } - - return supportedDetails; -} - -QList<QOrganizerItemType::ItemType> QOrganizerJsonDbEngine::supportedItemTypes() const -{ - QList<QOrganizerItemType::ItemType> ret; - - ret << QOrganizerItemType::TypeEvent; - ret << QOrganizerItemType::TypeEventOccurrence; -// ret << QOrganizerItemType::TypeJournal; -// ret << QOrganizerItemType::TypeNote; - ret << QOrganizerItemType::TypeTodo; - ret << QOrganizerItemType::TypeTodoOccurrence; - - return ret; -} - -const QList<int> QOrganizerJsonDbEngine::supportedDetailFields(QOrganizerItemDetail::DetailType detailType) -{ - static QMap<int, QList<int> > supportedFieldsByType; - if (supportedFieldsByType.isEmpty()) { - supportedFieldsByType.insert(QOrganizerItemDetail::TypeAudibleReminder, - QList<int>() << QOrganizerItemAudibleReminder::FieldDataUrl - << QOrganizerItemAudibleReminder::FieldRepetitionCount - << QOrganizerItemAudibleReminder::FieldRepetitionDelay - << QOrganizerItemAudibleReminder::FieldSecondsBeforeStart); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeClassification, - QList<int>() << QOrganizerItemClassification::FieldClassification); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeComment, - QList<int>() << QOrganizerItemComment::FieldComment); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeDescription, - QList<int>() << QOrganizerItemDescription::FieldDescription); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeDisplayLabel, - QList<int>() << QOrganizerItemDisplayLabel::FieldLabel); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeEmailReminder, - QList<int>() << QOrganizerItemEmailReminder::FieldAttachments - << QOrganizerItemEmailReminder::FieldBody - << QOrganizerItemEmailReminder::FieldRecipients - << QOrganizerItemEmailReminder::FieldRepetitionCount - << QOrganizerItemEmailReminder::FieldRepetitionDelay - << QOrganizerItemEmailReminder::FieldSecondsBeforeStart - << QOrganizerItemEmailReminder::FieldSubject); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeEventAttendee, - QList<int>() << QOrganizerEventAttendee::FieldAttendeeId - << QOrganizerEventAttendee::FieldEmailAddress - << QOrganizerEventAttendee::FieldName - << QOrganizerEventAttendee::FieldParticipationRole - << QOrganizerEventAttendee::FieldParticipationStatus); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeEventRsvp, - QList<int>() << QOrganizerEventRsvp::FieldOrganizerEmail - << QOrganizerEventRsvp::FieldOrganizerName - << QOrganizerEventRsvp::FieldParticipationRole - << QOrganizerEventRsvp::FieldParticipationStatus - << QOrganizerEventRsvp::FieldResponseDate - << QOrganizerEventRsvp::FieldResponseDeadline - << QOrganizerEventRsvp::FieldResponseRequirement); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeEventTime, - QList<int>() << QOrganizerEventTime::FieldAllDay - << QOrganizerEventTime::FieldEndDateTime - << QOrganizerEventTime::FieldStartDateTime); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeExtendedDetail, - QList<int>() << QOrganizerItemExtendedDetail::FieldData - << QOrganizerItemExtendedDetail::FieldName); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeGuid, - QList<int>() << QOrganizerItemGuid::FieldGuid); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeItemType, - QList<int>() << QOrganizerItemType::FieldType); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeJournalTime, - QList<int>() << QOrganizerJournalTime::FieldEntryDateTime); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeLocation, - QList<int>() << QOrganizerItemLocation::FieldLabel - << QOrganizerItemLocation::FieldLatitude - << QOrganizerItemLocation::FieldLongitude); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeParent, - QList<int>() << QOrganizerItemParent::FieldOriginalDate - << QOrganizerItemParent::FieldParentId); - supportedFieldsByType.insert(QOrganizerItemDetail::TypePriority, - QList<int>() << QOrganizerItemPriority::FieldPriority); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeRecurrence, - QList<int>() << QOrganizerItemRecurrence::FieldExceptionDates - << QOrganizerItemRecurrence::FieldExceptionRules - << QOrganizerItemRecurrence::FieldRecurrenceDates - << QOrganizerItemRecurrence::FieldRecurrenceRules); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeReminder, - QList<int>() << QOrganizerItemReminder::FieldRepetitionCount - << QOrganizerItemReminder::FieldRepetitionDelay - << QOrganizerItemReminder::FieldSecondsBeforeStart); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeTag, - QList<int>() << QOrganizerItemTag::FieldTag); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeTimestamp, - QList<int>() << QOrganizerItemTimestamp::FieldCreated - << QOrganizerItemTimestamp::FieldLastModified); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeTodoProgress, - QList<int>() << QOrganizerTodoProgress::FieldFinishedDateTime - << QOrganizerTodoProgress::FieldPercentageComplete - << QOrganizerTodoProgress::FieldStatus); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeTodoTime, - QList<int>() << QOrganizerTodoTime::FieldAllDay - << QOrganizerTodoTime::FieldDueDateTime - << QOrganizerTodoTime::FieldStartDateTime); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeUndefined, - QList<int>()); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeVersion, - QList<int>() << QOrganizerItemVersion::FieldExtendedVersion - << QOrganizerItemVersion::FieldVersion); - supportedFieldsByType.insert(QOrganizerItemDetail::TypeVisualReminder, - QList<int>() << QOrganizerItemVisualReminder::FieldDataUrl - << QOrganizerItemVisualReminder::FieldMessage - << QOrganizerItemVisualReminder::FieldRepetitionCount - << QOrganizerItemVisualReminder::FieldRepetitionDelay - << QOrganizerItemVisualReminder::FieldSecondsBeforeStart); - } - return supportedFieldsByType.value(detailType, QList<int>()); -} - -#include "moc_qorganizerjsondbengine.cpp" - -QT_END_NAMESPACE_ORGANIZER diff --git a/src/plugins/organizer/jsondb/qorganizerjsondbengine.h b/src/plugins/organizer/jsondb/qorganizerjsondbengine.h deleted file mode 100644 index d124b941e..000000000 --- a/src/plugins/organizer/jsondb/qorganizerjsondbengine.h +++ /dev/null @@ -1,186 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtOrganizer module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QORGANIZERJSONDBENGINE_H -#define QORGANIZERJSONDBENGINE_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtOrganizer/qorganizermanagerengine.h> - -QT_BEGIN_NAMESPACE_ORGANIZER - -/* - Organizer jsondb backend storage location related documentation - (will be moved later to proper location) - - Storage locations are locations where the organizer data can be stored. Currently there - are two locations; UserDataStorage and SystemStorage. These can be seen on the - QOrganizerAbstractRequest API's QOrganizerAbstractRequest::StorageLocation. - - Organizer jsondb backend engine requires storage locations (partitions in qtjsondb-module - terminology) to be present. If MissingPlatformRequirementsError is received from requests, - it means that the mandatory UserDataStorage storage location is missing or cannot be accessed due - to missing security access rights and Organizer jsondb backend cannot work properly. - InvalidStorageLocationError is returned in cases when the operation is targeted to non-mandatory, but not - accessible storage location. - - To create missing partitions, create a file named partitions.json having the following lines - in it: - [ - { "name" : "com.nokia.mt.User" }, - { "name" : "com.nokia.mt.System" } - ] - Then when starting the jsondb process on background, start it with path to partitions.json - -file defined like this -> jsondb -config-path /home/me/myjsondbfiles/ - - If you use QOrganizerManagerEngine APIs, please note that the QOrganizerJsonDbEngineData's - implementation directs all the operations to UserDataStorage storage location. If you want to - target operations to other storage locations, you need to use the asynchronous requests - instead. - - There are some restrictions with organizer data and storing it to storage locations: - - Once an item or collection is saved to one storage location, you cannot change it to - another storage location. The storage location parameter is ignored on the following updates. - - A collection and all the items it contains must also exist in the same storage location. - If not, InvalidCollectionError is returned when attempting to save the item. - - By default items and collections are stored in UserDataStorage storage location and fetched - from there. - - Storage location information is included in the engine item id syntax in following way: - [QOrganizerAbstractRequest::StorageLocation]/[jsondb uuid] -*/ - -class QOrganizerJsonDbRequestThread; - -class QOrganizerJsonDbEngine : public QOrganizerManagerEngine -{ - Q_OBJECT - -public: - enum StorageLocation { - UserDataStorage = 0x1, - SystemStorage = 0x2 - }; - Q_DECLARE_FLAGS(StorageLocations, StorageLocation) - - QOrganizerJsonDbEngine(QOrganizerManager::Error *error); - ~QOrganizerJsonDbEngine(); - - /* URI reporting */ - QString managerName() const; - QMap<QString, QString> managerParameters() const; - - // items - QList<QOrganizerItem> items(const QList<QOrganizerItemId> &itemIds, const QOrganizerItemFetchHint &fetchHint, - QMap<int, QOrganizerManager::Error> *errorMap, QOrganizerManager::Error *error); - - QList<QOrganizerItem> items(const QOrganizerItemFilter &filter, const QDateTime &startDateTime, - const QDateTime &endDateTime, int maxCount, - const QList<QOrganizerItemSortOrder> &sortOrders, - const QOrganizerItemFetchHint &fetchHint, QOrganizerManager::Error *error); - - QList<QOrganizerItemId> itemIds(const QOrganizerItemFilter &filter, const QDateTime &startDateTime, - const QDateTime &endDateTime, const QList<QOrganizerItemSortOrder> &sortOrders, - QOrganizerManager::Error *error); - - QList<QOrganizerItem> itemOccurrences(const QOrganizerItem &parentItem, const QDateTime &startDateTime, - const QDateTime &endDateTime, int maxCount, - const QOrganizerItemFetchHint &fetchHint, QOrganizerManager::Error *error); - - QList<QOrganizerItem> itemsForExport(const QDateTime &startDateTime, const QDateTime &endDateTime, - const QOrganizerItemFilter &filter, - const QList<QOrganizerItemSortOrder> &sortOrders, - const QOrganizerItemFetchHint &fetchHint, QOrganizerManager::Error *error); - - bool saveItems(QList<QOrganizerItem> *items, const QList<QOrganizerItemDetail::DetailType> &detailMask, - QMap<int, QOrganizerManager::Error> *errorMap, QOrganizerManager::Error *error); - - bool removeItems(const QList<QOrganizerItemId> &itemIds, QMap<int, QOrganizerManager::Error> *errorMap, - QOrganizerManager::Error *error); - - bool removeItems(const QList<QOrganizerItem> *items, QMap<int, QOrganizerManager::Error>* errorMap, - QOrganizerManager::Error* error); - - // collections - QOrganizerCollection defaultCollection(QOrganizerManager::Error* error); - QOrganizerCollection collection(const QOrganizerCollectionId& collectionId, QOrganizerManager::Error* error); - QList<QOrganizerCollection> collections(QOrganizerManager::Error* error); - bool saveCollection(QOrganizerCollection* collection, QOrganizerManager::Error* error); - bool removeCollection(const QOrganizerCollectionId& collectionId, QOrganizerManager::Error* error); - - /* Capabilities reporting */ - QList<QOrganizerItemFilter::FilterType> supportedFilters() const; - QList<QOrganizerItemDetail::DetailType> supportedItemDetails(QOrganizerItemType::ItemType itemType) const; - QList<QOrganizerItemType::ItemType> supportedItemTypes() const; - - /* Asynchronous Request Support */ - void requestDestroyed(QOrganizerAbstractRequest* req); - bool startRequest(QOrganizerAbstractRequest* req); - bool cancelRequest(QOrganizerAbstractRequest* req); - bool waitForRequestFinished(QOrganizerAbstractRequest* req, int msecs); - - /* JsonDb Engine internal capability reporting */ - static const QList<int> supportedDetailFields(QOrganizerItemDetail::DetailType detailType); - -signals: - void requestReceived(QOrganizerAbstractRequest* req); - -private: - friend class QOrganizerJsonDbEngineFactory; - QOrganizerJsonDbRequestThread *m_requestHandlerThread; -}; - -Q_DECLARE_OPERATORS_FOR_FLAGS(QOrganizerJsonDbEngine::StorageLocations) - -QT_END_NAMESPACE_ORGANIZER - -#endif // QORGANIZERJSONDBENGINE_H diff --git a/src/plugins/organizer/jsondb/qorganizerjsondbenginefactory.cpp b/src/plugins/organizer/jsondb/qorganizerjsondbenginefactory.cpp deleted file mode 100644 index cff391daf..000000000 --- a/src/plugins/organizer/jsondb/qorganizerjsondbenginefactory.cpp +++ /dev/null @@ -1,85 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtOrganizer module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qorganizerjsondbenginefactory.h" - -#include "qorganizerjsondbengine.h" -#include "qorganizerjsondbid.h" -#include "qorganizerjsondbstring.h" - -QT_BEGIN_NAMESPACE_ORGANIZER - -QOrganizerManagerEngine *QOrganizerJsonDbEngineFactory::engine(const QMap<QString, QString> ¶meters, QOrganizerManager::Error *error) -{ - Q_UNUSED(parameters) - - // manager takes ownership - return new QOrganizerJsonDbEngine(error); -} - -QOrganizerItemEngineId *QOrganizerJsonDbEngineFactory::createItemEngineId(const QMap<QString, QString> ¶meters, const QString &idString) const -{ - Q_UNUSED(parameters) - - QOrganizerJsonDbItemId *retn = new QOrganizerJsonDbItemId; - if (!idString.isEmpty()) - retn->setFullEngineId(idString); - return retn; -} - -QOrganizerCollectionEngineId *QOrganizerJsonDbEngineFactory::createCollectionEngineId(const QMap<QString, QString> ¶meters, const QString &idString) const -{ - Q_UNUSED(parameters) - - QOrganizerJsonDbCollectionId *retn = new QOrganizerJsonDbCollectionId; - if (!idString.isEmpty()) - retn->setFullEngineId(idString); - return retn; -} - -QString QOrganizerJsonDbEngineFactory::managerName() const -{ - return QOrganizerJsonDbStr::jsonDbManagerName(); -} - -#include "moc_qorganizerjsondbenginefactory.cpp" - -QT_END_NAMESPACE_ORGANIZER diff --git a/src/plugins/organizer/jsondb/qorganizerjsondbenginefactory.h b/src/plugins/organizer/jsondb/qorganizerjsondbenginefactory.h deleted file mode 100644 index 07daff854..000000000 --- a/src/plugins/organizer/jsondb/qorganizerjsondbenginefactory.h +++ /dev/null @@ -1,74 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtOrganizer module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QORGANIZERJSONDBENGINEFACTORY_H -#define QORGANIZERJSONDBENGINEFACTORY_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtOrganizer/qorganizermanagerenginefactory.h> - -QT_BEGIN_NAMESPACE_ORGANIZER - -class QOrganizerJsonDbEngineFactory : public QOrganizerManagerEngineFactory -{ - Q_OBJECT - Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QOrganizerManagerEngineFactoryInterface" FILE "jsondb.json") - -public: - QOrganizerManagerEngine *engine(const QMap<QString, QString> ¶meters, QOrganizerManager::Error *error); - QOrganizerItemEngineId *createItemEngineId(const QMap<QString, QString> ¶meters, const QString &idString) const; - QOrganizerCollectionEngineId *createCollectionEngineId(const QMap<QString, QString> ¶meters, const QString &idString) const; - QString managerName() const; -}; - -QT_END_NAMESPACE_ORGANIZER - -#endif // QORGANIZERJSONDBENGINEFACTORY_H diff --git a/src/plugins/organizer/jsondb/qorganizerjsondbid.cpp b/src/plugins/organizer/jsondb/qorganizerjsondbid.cpp deleted file mode 100644 index b3c0a2ac8..000000000 --- a/src/plugins/organizer/jsondb/qorganizerjsondbid.cpp +++ /dev/null @@ -1,262 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtOrganizer module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qorganizerjsondbid.h" - -#ifndef QT_NO_DEBUG_STREAM -#include <QtCore/qdebug.h> -#endif - -#include "qorganizerjsondbstring.h" - -QT_BEGIN_NAMESPACE_ORGANIZER - -QOrganizerJsonDbItemId::QOrganizerJsonDbItemId() - : QOrganizerItemEngineId() - , m_jsonDbUuid(QString()) - , m_storageLocation(QOrganizerJsonDbEngine::UserDataStorage) -{ -} - -QOrganizerJsonDbItemId::QOrganizerJsonDbItemId(const QString &fullEngineId) - : QOrganizerItemEngineId() -{ - splitId(fullEngineId, m_jsonDbUuid, m_storageLocation); -} - -QOrganizerJsonDbItemId::QOrganizerJsonDbItemId(const QOrganizerJsonDbItemId &other) - : QOrganizerItemEngineId(), - m_jsonDbUuid(other.m_jsonDbUuid), - m_storageLocation(other.m_storageLocation) -{ -} - -QOrganizerJsonDbItemId::~QOrganizerJsonDbItemId() -{ -} - -bool QOrganizerJsonDbItemId::isEqualTo(const QOrganizerItemEngineId *other) const -{ - const QOrganizerJsonDbItemId* id = static_cast<const QOrganizerJsonDbItemId *>(other); - return ((m_jsonDbUuid == id->m_jsonDbUuid) && (m_storageLocation == id->m_storageLocation)); -} - -bool QOrganizerJsonDbItemId::isLessThan(const QOrganizerItemEngineId *other) const -{ - const QOrganizerJsonDbItemId* id = static_cast<const QOrganizerJsonDbItemId *>(other); - if (m_storageLocation == id->m_storageLocation) - return (m_jsonDbUuid < id->m_jsonDbUuid); - else - return (m_storageLocation < id->m_storageLocation); -} - -QString QOrganizerJsonDbItemId::managerUri() const -{ - return QOrganizerJsonDbStr::jsonDbManagerUri(); -} - -QOrganizerItemEngineId *QOrganizerJsonDbItemId::clone() const -{ - QOrganizerJsonDbItemId *newId = new QOrganizerJsonDbItemId(); - newId->setJsonDbUuid(m_jsonDbUuid); - newId->setStorageLocation(m_storageLocation); - return newId; -} - -#ifndef QT_NO_DEBUG_STREAM -QDebug &QOrganizerJsonDbItemId::debugStreamOut(QDebug &dbg) const -{ - dbg.nospace() << "QOrganizerJsonDbItemId(" << toString() << ")"; - return dbg.maybeSpace(); -} -#endif - -QString QOrganizerJsonDbItemId::toString() const -{ - return QString("%1/%2").arg(m_storageLocation).arg(m_jsonDbUuid); -} - -uint QOrganizerJsonDbItemId::hash() const -{ - return QT_PREPEND_NAMESPACE(qHash)(this->toString()); -} - -void QOrganizerJsonDbItemId::setFullEngineId(const QString &fullEngineId) -{ - splitId(fullEngineId, m_jsonDbUuid, m_storageLocation); -} - -QString QOrganizerJsonDbItemId::jsondbUuid() const -{ - return m_jsonDbUuid; -} - -void QOrganizerJsonDbItemId::setJsonDbUuid(const QString &jsonDbUuid) -{ - m_jsonDbUuid = jsonDbUuid; -} - -QOrganizerJsonDbEngine::StorageLocation QOrganizerJsonDbItemId::storageLocation() const -{ - return m_storageLocation; -} - -void QOrganizerJsonDbItemId::setStorageLocation(QOrganizerJsonDbEngine::StorageLocation storageLocation) -{ - m_storageLocation = storageLocation; -} - -void QOrganizerJsonDbItemId::splitId(const QString &fullId, QString &jsondbUuid, QOrganizerJsonDbEngine::StorageLocation &storageLocation) -{ - // separate engine id part, if full id given - QString engineId = fullId.contains(":") ? fullId.mid(fullId.lastIndexOf(":")+1) : fullId; - // separate storagelocation and collection id from each other - const QStringList splittedEngineId = engineId.split(QStringLiteral("/")); - storageLocation = (QOrganizerJsonDbEngine::StorageLocation)splittedEngineId.first().toInt(); - jsondbUuid = splittedEngineId.last(); -} - -QOrganizerJsonDbCollectionId::QOrganizerJsonDbCollectionId() - : QOrganizerCollectionEngineId() - , m_jsonDbUuid(QString()) - , m_storageLocation(QOrganizerJsonDbEngine::UserDataStorage) -{ -} - -QOrganizerJsonDbCollectionId::QOrganizerJsonDbCollectionId(const QString &fullEngineId) - : QOrganizerCollectionEngineId() -{ - splitId(fullEngineId, m_jsonDbUuid, m_storageLocation); -} - -QOrganizerJsonDbCollectionId::QOrganizerJsonDbCollectionId(const QOrganizerJsonDbCollectionId &other) - : QOrganizerCollectionEngineId() - , m_jsonDbUuid(other.m_jsonDbUuid) - , m_storageLocation(other.m_storageLocation) -{ -} - -QOrganizerJsonDbCollectionId::~QOrganizerJsonDbCollectionId() -{ -} - -bool QOrganizerJsonDbCollectionId::isEqualTo(const QOrganizerCollectionEngineId *other) const -{ - const QOrganizerJsonDbCollectionId* collId = static_cast<const QOrganizerJsonDbCollectionId *>(other); - return ((m_jsonDbUuid == collId->m_jsonDbUuid) && (m_storageLocation == collId->m_storageLocation)); -} - -bool QOrganizerJsonDbCollectionId::isLessThan(const QOrganizerCollectionEngineId *other) const -{ - const QOrganizerJsonDbCollectionId* collId = static_cast<const QOrganizerJsonDbCollectionId *>(other); - if (m_storageLocation == collId->m_storageLocation) - return (m_jsonDbUuid < collId->m_jsonDbUuid); - else - return (m_storageLocation < collId->m_storageLocation); -} - -QString QOrganizerJsonDbCollectionId::managerUri() const -{ - return QOrganizerJsonDbStr::jsonDbManagerUri(); -} - -QOrganizerCollectionEngineId *QOrganizerJsonDbCollectionId::clone() const -{ - QOrganizerJsonDbCollectionId *newId = new QOrganizerJsonDbCollectionId(); - newId->setJsonDbUuid(m_jsonDbUuid); - newId->setStorageLocation(m_storageLocation); - return newId; -} - -#ifndef QT_NO_DEBUG_STREAM -QDebug &QOrganizerJsonDbCollectionId::debugStreamOut(QDebug &dbg) const -{ - dbg.nospace() << "QOrganizerJsonDbCollectionId(" << toString() << ")"; - return dbg.maybeSpace(); -} -#endif - -QString QOrganizerJsonDbCollectionId::toString() const -{ - return QString("%1/%2").arg(m_storageLocation).arg(m_jsonDbUuid); -} - -uint QOrganizerJsonDbCollectionId::hash() const -{ - return QT_PREPEND_NAMESPACE(qHash)(toString()); -} - -void QOrganizerJsonDbCollectionId::setFullEngineId(const QString &fullEngineId) -{ - splitId(fullEngineId, m_jsonDbUuid, m_storageLocation); -} - -QString QOrganizerJsonDbCollectionId::jsondbUuid() const -{ - return m_jsonDbUuid; -} - -void QOrganizerJsonDbCollectionId::setJsonDbUuid(const QString &jsonDbUuid) -{ - m_jsonDbUuid = jsonDbUuid; -} - -QOrganizerJsonDbEngine::StorageLocation QOrganizerJsonDbCollectionId::storageLocation() const -{ - return m_storageLocation; -} - -void QOrganizerJsonDbCollectionId::setStorageLocation(QOrganizerJsonDbEngine::StorageLocation storageLocation) -{ - m_storageLocation = storageLocation; -} - -void QOrganizerJsonDbCollectionId::splitId(const QString &fullId, QString &jsondbUuid, QOrganizerJsonDbEngine::StorageLocation &storageLocation) -{ - // separate engine id part, if full id given - QString engineId = fullId.contains(":") ? fullId.mid(fullId.lastIndexOf(":")+1) : fullId; - // separate storagelocation and collection id from each other - const QStringList splittedEngineId = engineId.split(QStringLiteral("/")); - storageLocation = QOrganizerJsonDbEngine::StorageLocation(splittedEngineId.first().toInt()); - jsondbUuid = splittedEngineId.last(); -} - -QT_END_NAMESPACE_ORGANIZER diff --git a/src/plugins/organizer/jsondb/qorganizerjsondbid.h b/src/plugins/organizer/jsondb/qorganizerjsondbid.h deleted file mode 100644 index 9552e6f82..000000000 --- a/src/plugins/organizer/jsondb/qorganizerjsondbid.h +++ /dev/null @@ -1,143 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtOrganizer module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QORGANIZERJSONDBID_H -#define QORGANIZERJSONDBID_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtOrganizer/qorganizerabstractrequest.h> -#include <QtOrganizer/qorganizeritemengineid.h> -#include <QtOrganizer/qorganizercollectionengineid.h> - -#include "qorganizerjsondbengine.h" - -QT_BEGIN_NAMESPACE_ORGANIZER - -class QOrganizerJsonDbItemId : public QOrganizerItemEngineId -{ -public: - QOrganizerJsonDbItemId(); - QOrganizerJsonDbItemId(const QString &fullEngineId); - ~QOrganizerJsonDbItemId(); - QOrganizerJsonDbItemId(const QOrganizerJsonDbItemId &other); - - bool isEqualTo(const QOrganizerItemEngineId *other) const; - bool isLessThan(const QOrganizerItemEngineId *other) const; - - QString managerUri() const; - QOrganizerItemEngineId *clone() const; - - QString toString() const; - -#ifndef QT_NO_DEBUG_STREAM - QDebug &debugStreamOut(QDebug &dbg) const; -#endif - - uint hash() const; - - void setFullEngineId(const QString &fullEngineId); - - QString jsondbUuid() const; - void setJsonDbUuid(const QString &jsonDbUuid); - - QOrganizerJsonDbEngine::StorageLocation storageLocation() const; - void setStorageLocation(QOrganizerJsonDbEngine::StorageLocation storageLocation); - -private: - void splitId(const QString &fullId, QString &jsondbUuid, QOrganizerJsonDbEngine::StorageLocation &storageLocation); - -private: - QString m_jsonDbUuid; - QOrganizerJsonDbEngine::StorageLocation m_storageLocation; -}; - - -class QOrganizerJsonDbCollectionId : public QOrganizerCollectionEngineId -{ -public: - QOrganizerJsonDbCollectionId(); - QOrganizerJsonDbCollectionId(const QString &fullEngineId); - ~QOrganizerJsonDbCollectionId(); - QOrganizerJsonDbCollectionId(const QOrganizerJsonDbCollectionId &other); - - bool isEqualTo(const QOrganizerCollectionEngineId *other) const; - bool isLessThan(const QOrganizerCollectionEngineId *other) const; - - QString managerUri() const; - QOrganizerCollectionEngineId *clone() const; - - QString toString() const; - -#ifndef QT_NO_DEBUG_STREAM - QDebug &debugStreamOut(QDebug &dbg) const; -#endif - - uint hash() const; - - void setFullEngineId(const QString &fullEngineId); - - QString jsondbUuid() const; - void setJsonDbUuid(const QString &jsonDbUuid); - - QOrganizerJsonDbEngine::StorageLocation storageLocation() const; - void setStorageLocation(QOrganizerJsonDbEngine::StorageLocation storageLocation); - -private: - void splitId(const QString &fullId, QString &jsondbUuid, QOrganizerJsonDbEngine::StorageLocation &storageLocation); - -private: - QString m_jsonDbUuid; - QOrganizerJsonDbEngine::StorageLocation m_storageLocation; -}; - -QT_END_NAMESPACE_ORGANIZER - -#endif // QORGANIZERJSONDBID_H diff --git a/src/plugins/organizer/jsondb/qorganizerjsondbrequestmanager.cpp b/src/plugins/organizer/jsondb/qorganizerjsondbrequestmanager.cpp deleted file mode 100644 index bb2f5b1fe..000000000 --- a/src/plugins/organizer/jsondb/qorganizerjsondbrequestmanager.cpp +++ /dev/null @@ -1,145 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtOrganizer module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qorganizerjsondbrequestmanager.h" - -#include <QtCore/qmutex.h> - -QT_BEGIN_NAMESPACE_ORGANIZER - -QOrganizerJsonDbRequestManager::QOrganizerJsonDbRequestManager() -{ - m_operationMutex = new QMutex(); -} - -QOrganizerJsonDbRequestManager::~QOrganizerJsonDbRequestManager() -{ - for (QMap<QOrganizerAbstractRequest *, QOrganizerJsonDbRequestData *>::const_iterator i = m_requests.begin(); i != m_requests.end(); ++i) - delete i.value(); - - delete m_operationMutex; -} - -void QOrganizerJsonDbRequestManager::addRequest(QOrganizerAbstractRequest *req) -{ - QMutexLocker locker(m_operationMutex); - - if (!m_requests.contains(req)) { - QOrganizerJsonDbRequestData *newData = new QOrganizerJsonDbRequestData(); - newData->m_status = QOrganizerJsonDbRequestManager::Inactive; - newData->m_waitCondition = 0; - m_requests.insert(req, newData); - } -} - -void QOrganizerJsonDbRequestManager::removeRequest(QOrganizerAbstractRequest *req) -{ - QMutexLocker locker(m_operationMutex); - - if (m_requests.contains(req)) { - delete m_requests.value(req); - m_requests.remove(req); - } -} - -bool QOrganizerJsonDbRequestManager::setActive(QOrganizerAbstractRequest *req) -{ - // This function is called from JsonDbEngine thread - QMutexLocker locker(m_operationMutex); - - if (m_requests.contains(req)) { - m_requests.value(req)->m_status = QOrganizerJsonDbRequestManager::Active; - return true; - } - return false; -} - -bool QOrganizerJsonDbRequestManager::setDeleted(QOrganizerAbstractRequest *req) -{ - // This function is called from JsonDbEngine thread - QMutexLocker locker(m_operationMutex); - - if (m_requests.contains(req)) { - m_requests.value(req)->m_status = QOrganizerJsonDbRequestManager::Deleted; - return true; - } - return false; -} - -bool QOrganizerJsonDbRequestManager::setWaitCondition(QOrganizerAbstractRequest *req, QWaitCondition *waitCondition) -{ - // This function is called from JsonDbEngine thread - QMutexLocker locker(m_operationMutex); - - if (m_requests.contains(req)) { - m_requests.value(req)->m_waitCondition = waitCondition; - return true; - } - return false; -} - -QWaitCondition *QOrganizerJsonDbRequestManager::waitCondition(QOrganizerAbstractRequest *req) -{ - QMutexLocker locker(m_operationMutex); - - if (m_requests.contains(req)) - return m_requests.value(req)->m_waitCondition; - return 0; -} - -void QOrganizerJsonDbRequestManager::removeWaitCondition(QOrganizerAbstractRequest *req) -{ - QMutexLocker locker(m_operationMutex); - - if (m_requests.contains(req)) - m_requests.value(req)->m_waitCondition = 0; -} - -QOrganizerJsonDbRequestManager::HandlingStatus QOrganizerJsonDbRequestManager::requestStatus(QOrganizerAbstractRequest *req) -{ - QMutexLocker locker(m_operationMutex); - - if (m_requests.contains(req)) - return m_requests.value(req)->m_status; - return QOrganizerJsonDbRequestManager::Invalid; -} - -QT_END_NAMESPACE_ORGANIZER diff --git a/src/plugins/organizer/jsondb/qorganizerjsondbrequestmanager.h b/src/plugins/organizer/jsondb/qorganizerjsondbrequestmanager.h deleted file mode 100644 index a79acc46a..000000000 --- a/src/plugins/organizer/jsondb/qorganizerjsondbrequestmanager.h +++ /dev/null @@ -1,106 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtOrganizer module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QORGANIZERJSONDBREQUESTMANAGER_H -#define QORGANIZERJSONDBREQUESTMANAGER_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/qwaitcondition.h> - -#include <QtOrganizer/qorganizerabstractrequest.h> - -QT_BEGIN_NAMESPACE_ORGANIZER - -class QOrganizerJsonDbRequestData; - -class QOrganizerJsonDbRequestManager -{ -public: - // HandlingStatus gives info about in which phase the handling of the request is. - // The status is not necessarily in sync with the request status (QOrganizerAbstractRequest::state()) - enum HandlingStatus { - Inactive = 0, // request handling not yet started - Active, // request handling started, not yet finished - Canceled, // request handling should be finished due to cancellation - Deleted, // request deleted - Invalid // status of a non-existing request - }; - - QOrganizerJsonDbRequestManager(); - ~QOrganizerJsonDbRequestManager(); - - void addRequest(QOrganizerAbstractRequest *req); - void removeRequest(QOrganizerAbstractRequest *req); - - bool setActive(QOrganizerAbstractRequest *req); - bool setDeleted(QOrganizerAbstractRequest *req); - QOrganizerJsonDbRequestManager::HandlingStatus requestStatus(QOrganizerAbstractRequest *req); - - bool setWaitCondition(QOrganizerAbstractRequest *req, QWaitCondition *waitCondition); - QWaitCondition *waitCondition(QOrganizerAbstractRequest *req); - void removeWaitCondition(QOrganizerAbstractRequest *req); - -private: - QMap<QOrganizerAbstractRequest *, QOrganizerJsonDbRequestData *> m_requests; - QMutex *m_operationMutex; -}; - -class QOrganizerJsonDbRequestData -{ -public: - QOrganizerJsonDbRequestData() {} - QWaitCondition *m_waitCondition; - QOrganizerJsonDbRequestManager::HandlingStatus m_status; -}; - -QT_END_NAMESPACE_ORGANIZER - -#endif // QORGANIZERJSONDBREQUESTMANAGER_H diff --git a/src/plugins/organizer/jsondb/qorganizerjsondbrequestthread.cpp b/src/plugins/organizer/jsondb/qorganizerjsondbrequestthread.cpp deleted file mode 100644 index 8a342ff5f..000000000 --- a/src/plugins/organizer/jsondb/qorganizerjsondbrequestthread.cpp +++ /dev/null @@ -1,1372 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtOrganizer module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qorganizerjsondbrequestthread.h" - -#include <QtCore/qdebug.h> -#include <QtCore/qeventloop.h> -#include <QtCore/qmutex.h> -#include <QtCore/qtimer.h> -#include <QtCore/quuid.h> - -#include <QtOrganizer/qorganizeritems.h> -#include <QtOrganizer/qorganizeritemcollectionfilter.h> -#include <QtOrganizer/qorganizeritemunionfilter.h> - -#include "qorganizerjsondbdatastorage.h" -#include "qorganizerjsondbid.h" -#include "qorganizerjsondbrequestmanager.h" -#include "qorganizerjsondbstring.h" - -QT_BEGIN_NAMESPACE_ORGANIZER - -const int QOrganizerJsonDbRequestThread::TIMEOUT_INTERVAL(100); -const int QOrganizerJsonDbRequestThread::DefaultTimePeriod(1461); -const int QOrganizerJsonDbRequestThread::MaxOccurrenceCount(50); - -QOrganizerJsonDbRequestThread::QOrganizerJsonDbRequestThread() - : m_engine(0) - , m_storage(0) - , m_requestMgr(0) - , m_reqStateMutex(0) - , m_timer(0) -{ -} - -QOrganizerJsonDbRequestThread::~QOrganizerJsonDbRequestThread() -{ - delete m_reqStateMutex; - m_reqStateMutex = 0; - delete m_requestMgr; - m_requestMgr = 0; - m_storage->exit(); - m_storage->wait(); - delete m_storage; - m_storage = 0; -} - -void QOrganizerJsonDbRequestThread::run() -{ - m_reqStateMutex = new QMutex(); - m_requestMgr = new QOrganizerJsonDbRequestManager(); - m_storage = new QOrganizerJsonDbDataStorage(); - m_storage->moveToThread(m_storage); - QEventLoop loop; - connect(m_storage, SIGNAL(threadInitialized()), &loop, SLOT(quit())); - m_storage->start(); - loop.exec(); - - connect(m_storage, SIGNAL(itemAdded(QOrganizerItemId)), this, SLOT(onItemAdded(QOrganizerItemId))); - connect(m_storage, SIGNAL(itemChanged(QOrganizerItemId)), this, SLOT(onItemChanged(QOrganizerItemId))); - connect(m_storage, SIGNAL(itemRemoved(QOrganizerItemId)), this, SLOT(onItemRemoved(QOrganizerItemId))); - connect(m_storage, SIGNAL(collectionAdded(QOrganizerCollectionId)), this, SLOT(onCollectionAdded(QOrganizerCollectionId))); - connect(m_storage, SIGNAL(collectionChanged(QOrganizerCollectionId)), this, SLOT(onCollectionChanged(QOrganizerCollectionId))); - connect(m_storage, SIGNAL(collectionRemoved(QOrganizerCollectionId)), this, SLOT(onCollectionRemoved(QOrganizerCollectionId))); - - initDefaultCollection(); - - emit initialized(); - QThread::run(); -} - -void QOrganizerJsonDbRequestThread::setEngine(QOrganizerJsonDbEngine *engine) -{ - // This function is called by the QOrganizerJsonDbEngine thread (main thread) - m_engine = engine; -} - -void QOrganizerJsonDbRequestThread::addRequest(QOrganizerAbstractRequest* req) -{ - // This function is called by the QOrganizerJsonDbEngine thread (main thread) - QMutexLocker locker(m_reqStateMutex); - m_requestMgr->addRequest(req); -} - -bool QOrganizerJsonDbRequestThread::waitForRequestFinished(QOrganizerAbstractRequest *req, int msecs) -{ - // This function is called by the QOrganizerJsonDbEngine thread (main thread) - - // TODO: timeout handling - Q_UNUSED(msecs); - - QMutexLocker locker(m_reqStateMutex); - QWaitCondition waitCondition; - - if (req->state() == QOrganizerAbstractRequest::FinishedState) - return true; - else if (req->state() == QOrganizerAbstractRequest::CanceledState) - return false; - - // Request might still be inactive if this function is called immediatelly after sending a signal to - // handleRequest slot. The signal goes to event loop and might be handled later than this function is executed. - m_requestMgr->setWaitCondition(req, &waitCondition); - bool requestFinished; - if (msecs <= 0) - requestFinished = waitCondition.wait(m_reqStateMutex); - else - requestFinished = waitCondition.wait(m_reqStateMutex, msecs); - - m_requestMgr->removeWaitCondition(req); - return requestFinished; -} - -void QOrganizerJsonDbRequestThread::requestDestroyed(QOrganizerAbstractRequest* req) -{ - // This function is called by the QOrganizerJsonDbEngine thread (main thread) - QMutexLocker locker(m_reqStateMutex); - m_requestMgr->setDeleted(req); -} - -QOrganizerCollection QOrganizerJsonDbRequestThread::defaultCollection() const -{ - // This function is called by the QOrganizerJsonDbEngine thread (main thread) - QMutexLocker locker(m_reqStateMutex); - return m_storage->defaultCollection(); -} - -bool QOrganizerJsonDbRequestThread::validRequest(QOrganizerAbstractRequest *req) -{ - QOrganizerJsonDbRequestManager::HandlingStatus status = m_requestMgr->requestStatus(req); - if (status == QOrganizerJsonDbRequestManager::Deleted) { - m_requestMgr->removeRequest(req); - return false; - } else if (status == QOrganizerJsonDbRequestManager::Invalid) { - return false; - } - return true; -} - -bool QOrganizerJsonDbRequestThread::validPlatform(QOrganizerAbstractRequest *req) -{ - if (!(QOrganizerJsonDbEngine::UserDataStorage & m_storage->availableStorageLocationsFlag())) { - // UserDataStorage not available is a fatal issue - qCritical("Organizer - JsonDb backend does not work without UserDataStorage!"); - finishRequest(*req, QOrganizerManager::UnspecifiedError, QMap<int, QOrganizerManager::Error>()); - return false; - } else { - return true; - } -} - -void QOrganizerJsonDbRequestThread::handleRequest(QOrganizerAbstractRequest *req) -{ - QMutexLocker locker(m_reqStateMutex); - - if (!validRequest(req)) - return; - if (!validPlatform(req)) - return; - - switch (req->type()) { - case QOrganizerAbstractRequest::ItemSaveRequest: - handleItemSaveRequest(static_cast<QOrganizerItemSaveRequest*>(req)); - break; - - case QOrganizerAbstractRequest::ItemFetchRequest: - handleItemFetchRequest(static_cast<QOrganizerItemFetchRequest*>(req)); - break; - - case QOrganizerAbstractRequest::ItemIdFetchRequest: - handleItemIdFetchRequest(static_cast<QOrganizerItemIdFetchRequest*>(req)); - break; - - case QOrganizerAbstractRequest::ItemFetchByIdRequest: - handleItemFetchByIdRequest(static_cast<QOrganizerItemFetchByIdRequest*>(req)); - break; - - case QOrganizerAbstractRequest::ItemFetchForExportRequest: - handleItemFetchForExportRequest(static_cast<QOrganizerItemFetchForExportRequest*>(req)); - break; - - case QOrganizerAbstractRequest::ItemOccurrenceFetchRequest: - handleItemOccurrenceFetchRequest(static_cast<QOrganizerItemOccurrenceFetchRequest*>(req)); - break; - - case QOrganizerAbstractRequest::ItemRemoveRequest: - handleItemRemoveRequest(static_cast <QOrganizerItemRemoveRequest *> (req)); - break; - - case QOrganizerAbstractRequest::ItemRemoveByIdRequest: - handleItemRemoveByIdRequest(static_cast <QOrganizerItemRemoveByIdRequest *> (req)); - break; - - case QOrganizerAbstractRequest::CollectionSaveRequest: - handleCollectionSaveRequest(static_cast <QOrganizerCollectionSaveRequest *> (req)); - break; - - case QOrganizerAbstractRequest::CollectionFetchRequest: - handleCollectionFetchRequest(static_cast<QOrganizerCollectionFetchRequest*>(req)); - break; - - case QOrganizerAbstractRequest::CollectionRemoveRequest: - handleCollectionRemoveRequest(static_cast<QOrganizerCollectionRemoveRequest*>(req)); - break; - - default: - break; - } -} - -void QOrganizerJsonDbRequestThread::finishRequest(QOrganizerAbstractRequest &request, QOrganizerManager::Error latestError, - const QMap<int, QOrganizerManager::Error> &errorMap, const QList<QOrganizerItem> &itemList, const QList<QOrganizerCollection> &collectionList, - const QList<QOrganizerItemId> &itemIdList) -{ - QWaitCondition* waitCondition = m_requestMgr->waitCondition(&request); - m_requestMgr->removeRequest(&request); - - switch (request.type()) { - case QOrganizerAbstractRequest::ItemSaveRequest: - QOrganizerManagerEngine::updateItemSaveRequest(qobject_cast<QOrganizerItemSaveRequest*>(&request), - itemList, latestError, errorMap, QOrganizerAbstractRequest::FinishedState); - break; - - case QOrganizerAbstractRequest::ItemFetchRequest: - QOrganizerManagerEngine::updateItemFetchRequest(qobject_cast<QOrganizerItemFetchRequest*>(&request), - itemList, latestError, QOrganizerAbstractRequest::FinishedState); - break; - - case QOrganizerAbstractRequest::ItemIdFetchRequest: - QOrganizerManagerEngine::updateItemIdFetchRequest(qobject_cast<QOrganizerItemIdFetchRequest*>(&request), - itemIdList, latestError, QOrganizerAbstractRequest::FinishedState); - break; - - case QOrganizerAbstractRequest::ItemFetchByIdRequest: - QOrganizerManagerEngine::updateItemFetchByIdRequest(qobject_cast<QOrganizerItemFetchByIdRequest*>(&request), - itemList, latestError, errorMap, QOrganizerAbstractRequest::FinishedState); - break; - - case QOrganizerAbstractRequest::ItemFetchForExportRequest: - QOrganizerManagerEngine::updateItemFetchForExportRequest(qobject_cast<QOrganizerItemFetchForExportRequest*>(&request), - itemList, latestError, QOrganizerAbstractRequest::FinishedState); - break; - - case QOrganizerAbstractRequest::ItemOccurrenceFetchRequest: - QOrganizerManagerEngine::updateItemOccurrenceFetchRequest(qobject_cast<QOrganizerItemOccurrenceFetchRequest*>(&request), - itemList, latestError, QOrganizerAbstractRequest::FinishedState); - break; - - case QOrganizerAbstractRequest::ItemRemoveRequest: - QOrganizerManagerEngine::updateItemRemoveRequest(qobject_cast<QOrganizerItemRemoveRequest*>(&request), - latestError, errorMap, QOrganizerAbstractRequest::FinishedState); - break; - - case QOrganizerAbstractRequest::ItemRemoveByIdRequest: - QOrganizerManagerEngine::updateItemRemoveByIdRequest(qobject_cast<QOrganizerItemRemoveByIdRequest*>(&request), - latestError, errorMap, QOrganizerAbstractRequest::FinishedState); - break; - - case QOrganizerAbstractRequest::CollectionSaveRequest: - QOrganizerManagerEngine::updateCollectionSaveRequest(qobject_cast<QOrganizerCollectionSaveRequest*>(&request), - collectionList, latestError, errorMap, QOrganizerAbstractRequest::FinishedState); - break; - - case QOrganizerAbstractRequest::CollectionFetchRequest: - QOrganizerManagerEngine::updateCollectionFetchRequest(qobject_cast<QOrganizerCollectionFetchRequest*>(&request), - collectionList, latestError, QOrganizerAbstractRequest::FinishedState); - break; - - case QOrganizerAbstractRequest::CollectionRemoveRequest: - QOrganizerManagerEngine::updateCollectionRemoveRequest(qobject_cast<QOrganizerCollectionRemoveRequest*>(&request), - latestError, errorMap, QOrganizerAbstractRequest::FinishedState); - break; - - default: - break; - } - - if (waitCondition) - waitCondition->wakeAll(); -} - -void QOrganizerJsonDbRequestThread::onItemAdded(const QOrganizerItemId &itemId) -{ - m_ics.insertAddedItem(itemId); - startTimer(); -} - -void QOrganizerJsonDbRequestThread::onItemChanged(const QOrganizerItemId &itemId) -{ - m_ics.insertChangedItem(itemId); - startTimer(); -} - -void QOrganizerJsonDbRequestThread::onItemRemoved(const QOrganizerItemId &itemId) -{ - m_ics.insertRemovedItem(itemId); - startTimer(); -} - -void QOrganizerJsonDbRequestThread::onCollectionAdded(const QOrganizerCollectionId &collectionId) -{ - m_ccs.insertAddedCollection(collectionId); - startTimer(); -} - -void QOrganizerJsonDbRequestThread::onCollectionChanged(const QOrganizerCollectionId &collectionId) -{ - m_ccs.insertChangedCollection(collectionId); - startTimer(); -} - -void QOrganizerJsonDbRequestThread::onCollectionRemoved(const QOrganizerCollectionId &collectionId) -{ - m_ccs.insertRemovedCollection(collectionId); - startTimer(); -} - -void QOrganizerJsonDbRequestThread::startTimer() -{ - if (!m_timer) { - m_timer = new QTimer(this); - m_timer->setSingleShot(true); - m_timer->setInterval(TIMEOUT_INTERVAL); - connect(m_timer, SIGNAL(timeout()), this, SLOT(onTimeout())); - } - if (!m_timer->isActive()) - m_timer->start(); -} - -void QOrganizerJsonDbRequestThread::onTimeout() -{ - if (m_engine) { - m_ics.emitSignals(m_engine); - m_ics.clearAll(); - m_ccs.emitSignals(m_engine); - m_ccs.clearAll(); - } -} - -void QOrganizerJsonDbRequestThread::handleItemSaveRequest(QOrganizerItemSaveRequest* saveReq) -{ - QMap<int, QOrganizerItem> itemMap; - QMap<int, bool> itemIsNewStatusMap; - QMap<int, QOrganizerManager::Error> errorMap; - QOrganizerManager::Error latestError = QOrganizerManager::NoError; - QList<QOrganizerItem> items = saveReq->items(); - QMap<int, QOrganizerItem> parentItemMap; - QMap<int, QOrganizerManager::Error> parentErrorMap; - QOrganizerManager::Error parentError = QOrganizerManager::NoError; - // if not defined, backend decides the default storage location -> UserDataStorage - QOrganizerJsonDbEngine::StorageLocation storageLocation = QOrganizerJsonDbEngine::UserDataStorage; - - m_requestMgr->setActive(saveReq); - - for (int i = 0; i < items.size(); i++) { - QOrganizerItem item = items.at(i); - QOrganizerItem parentItem; - bool itemIsNew = item.id().isNull(); - bool itemIsOccurrence = (item.type() == QOrganizerItemType::TypeEventOccurrence || item.type() == QOrganizerItemType::TypeTodoOccurrence); - bool errorFound = false; - - QString managerUri = QOrganizerManager::buildUri(m_engine->managerName(), m_engine->managerParameters()); - // check manager uri if is the same with the engine uri - if (!itemIsNew && (managerUri != item.id().managerUri())) { - latestError = QOrganizerManager::BadArgumentError; - errorFound = true; - } - - // TODO: to be replaced by new validity check, collection id and guid should not be mandatory fields - // this checks e.g. that occurrences have parent ids and original dates? - // // ensure that the organizeritem's details conform to their definitions - // if (!errorFound && !m_engine->validateItem(item, &latestError)) - // errorFound = true; - - - // check for view object - if (item.data(QOrganizerJsonDbStr::eventIsSynthetic()).toBool()) { - item.setData(QOrganizerJsonDbStr::eventIsSynthetic(), false); - item.setId(QOrganizerItemId()); - storageLocation = QOrganizerJsonDbEngine::SystemStorage; - itemIsNew = true; - } - - // Check the request is targeted to available storage location. - // Storage location errors are prioritised over less important other possible errors. - if (!errorFound) { - QOrganizerManager::Error error = QOrganizerManager::NoError; - if (itemIsNew) - error = checkRequestSpecificStorageLocation(storageLocation); - else - error = checkRequestSpecificStorageLocation(static_cast<const QOrganizerJsonDbItemId *>(QOrganizerManagerEngine::engineItemId(item.id()))->storageLocation()); - if (QOrganizerManager::NoError != error) { - latestError = error; - errorFound = true; - } - } - - if (!errorFound) { - if (itemIsOccurrence) { - parentItem = fetchParentItem(item); - if (parentItem.isEmpty()) { - latestError = QOrganizerManager::InvalidOccurrenceError; - errorFound = true; - } - } - } - - if (!errorFound) { - if (itemIsOccurrence && !fixParentReferences(&item, parentItem)) { - latestError = QOrganizerManager::InvalidOccurrenceError; - errorFound = true; - } - } - - if (!errorFound) { - if (itemIsOccurrence && !typesAreRelated(item.type(), parentItem.type())) { - latestError = QOrganizerManager::InvalidOccurrenceError; - errorFound = true; - } - } - - if (!errorFound) { - if (!fixGuidReferences(&item, parentItem)) { - latestError = QOrganizerManager::InvalidOccurrenceError; - errorFound = true; - } - } - - if (!errorFound) { - if (!fixCollectionReferences(&item, parentItem, itemIsNew, storageLocation)) { - latestError = QOrganizerManager::InvalidCollectionError; - errorFound = true; - } - } - - if (!errorFound && itemIsOccurrence) { - // add exception date to parent item - QOrganizerItemParent parentDetail = item.detail(QOrganizerItemDetail::TypeParent); - QDate originalDate = parentDetail.originalDate(); - QOrganizerItemRecurrence recurrenceDetail = parentItem.detail(QOrganizerItemDetail::TypeRecurrence); - QSet<QDate> exceptionDates = recurrenceDetail.exceptionDates(); - if (!exceptionDates.contains(originalDate)) - exceptionDates.insert(originalDate); - - if (parentItem.type() == QOrganizerItemType::TypeEvent) { - QOrganizerEvent *parentEvent = static_cast<QOrganizerEvent*>(&parentItem); - parentEvent->setExceptionDates(exceptionDates); - } else if (parentItem.type() == QOrganizerItemType::TypeTodo) { - QOrganizerTodo *parentTodo = static_cast<QOrganizerTodo*>(&parentItem); - parentTodo->setExceptionDates(exceptionDates); - } - parentItemMap.insert(i, parentItem); - QOrganizerItemRecurrence rec = parentItem.detail(QOrganizerItemDetail::TypeRecurrence); - } - // else if (!errorFound && !itemIsOccurrence) { - // What to do when updating a parent item, i.e. one with recurrence? should we e.g. check if any exception dates have been removed and - // remove those exceptions from db? - // NOTE: currently there is work-around for this: some cross-checking is done when fetching items - // } - - // remove version in case the item ID is reset - if (itemIsNew) { - QOrganizerItemVersion version = item.detail(QOrganizerItemDetail::TypeVersion); - if (!version.isEmpty()) - item.removeDetail(&version); - } - - if (errorFound) { - errorMap.insert(i, latestError); - } else { - itemMap.insert(i, item); - itemIsNewStatusMap.insert(i, itemIsNew); - } - } - - // save items - if (!itemMap.isEmpty()) { - m_storage->saveItems(&itemMap, &errorMap, &latestError, storageLocation); - QMap<int, QOrganizerItem>::const_iterator i = itemMap.constBegin(); - while (i != itemMap.constEnd()) { - if (!errorMap.contains(i.key())) - items.replace(i.key(), i.value()); // always replacing because of version updating - else - parentItemMap.remove(i.key()); // the item was not saved, let's not save the parent item either - ++i; - } - } - - // save parent items with modified exception dates - if (!parentItemMap.isEmpty()) - m_storage->saveItems(&parentItemMap, &parentErrorMap, &parentError, storageLocation); - - finishRequest(*saveReq, latestError, errorMap, items); -} - -void QOrganizerJsonDbRequestThread::handleItemFetchRequest(QOrganizerItemFetchRequest *fetchReq) -{ - QOrganizerManager::Error latestError = QOrganizerManager::NoError; - m_requestMgr->setActive(fetchReq); - // UserDataStorage is default storage location, if not otherwise set - QOrganizerJsonDbEngine::StorageLocations storageLocations = QOrganizerJsonDbEngine::UserDataStorage; - latestError = checkRequestSpecificStorageLocation(storageLocations); - QList<QOrganizerItem> items; - if (QOrganizerManager::NoError == latestError) - items = internalItems(fetchReq->startDate(), fetchReq->endDate(), fetchReq->filter(), fetchReq->sorting(), - fetchReq->fetchHint(), &latestError, false, storageLocations); - - finishRequest(*fetchReq, latestError, QMap<int, QOrganizerManager::Error>(), items.mid(0, fetchReq->maxCount())); -} - -void QOrganizerJsonDbRequestThread::handleItemIdFetchRequest(QOrganizerItemIdFetchRequest *idFetchReq) -{ - QOrganizerManager::Error latestError = QOrganizerManager::NoError; - m_requestMgr->setActive(idFetchReq); - // UserDataStorage is default storage location, if not otherwise set - QOrganizerJsonDbEngine::StorageLocations storageLocations = QOrganizerJsonDbEngine::UserDataStorage; - - latestError = checkRequestSpecificStorageLocation(storageLocations); - QList<QOrganizerItem> items; - if (QOrganizerManager::NoError == latestError) - items = internalItems(idFetchReq->startDate(), idFetchReq->endDate(), idFetchReq->filter(), idFetchReq->sorting(), - QOrganizerItemFetchHint(), &latestError, true, storageLocations); - QList<QOrganizerItemId> ids; - for (int i = 0; i < items.length(); i++) { - ids.append(items[i].id()); - } - - finishRequest(*idFetchReq, latestError, QMap<int, QOrganizerManager::Error>(), QList<QOrganizerItem>(), QList<QOrganizerCollection>(), ids); -} - -void QOrganizerJsonDbRequestThread::handleItemFetchByIdRequest(QOrganizerItemFetchByIdRequest *fetchByIdReq) -{ - QMap<int, QOrganizerManager::Error> errorMap; - QOrganizerManager::Error latestError = QOrganizerManager::NoError; - m_requestMgr->setActive(fetchByIdReq); - QList<QOrganizerItem> items; - if (!fetchByIdReq->ids().isEmpty()) { - QOrganizerJsonDbEngine::StorageLocations storageLocationsNeeded = resolveNeededStorageLocationsForItems(fetchByIdReq->ids()); - latestError = checkRequestSpecificStorageLocation(storageLocationsNeeded); - if (QOrganizerManager::NoError == latestError) - items = m_storage->itemsById(fetchByIdReq->ids(), &errorMap, &latestError, storageLocationsNeeded); - } - - finishRequest(*fetchByIdReq, latestError, errorMap, items); -} - -void QOrganizerJsonDbRequestThread::handleItemFetchForExportRequest(QOrganizerItemFetchForExportRequest *fetchForExportReq) -{ - QOrganizerManager::Error latestError = QOrganizerManager::NoError; - m_requestMgr->setActive(fetchForExportReq); - // UserDataStorage is default storage location, if not otherwise set - QOrganizerJsonDbEngine::StorageLocations storageLocations = QOrganizerJsonDbEngine::UserDataStorage; - latestError = checkRequestSpecificStorageLocation(storageLocations); - QList<QOrganizerItem> items; - if (QOrganizerManager::NoError == latestError) - items = internalItems(fetchForExportReq->startDate(), fetchForExportReq->endDate(), fetchForExportReq->filter(), fetchForExportReq->sorting(), - fetchForExportReq->fetchHint(), &latestError, true, storageLocations); - - finishRequest(*fetchForExportReq, latestError, QMap<int, QOrganizerManager::Error>(), items); -} - - -void QOrganizerJsonDbRequestThread::handleItemOccurrenceFetchRequest(QOrganizerItemOccurrenceFetchRequest *occurrenceFetchReq) -{ - QOrganizerManager::Error latestError = QOrganizerManager::NoError; - m_requestMgr->setActive(occurrenceFetchReq); - - QList<QOrganizerItem> items = internalItemOccurrences(occurrenceFetchReq->parentItem(), occurrenceFetchReq->startDate(), occurrenceFetchReq->endDate(), occurrenceFetchReq->fetchHint(), occurrenceFetchReq->maxOccurrences(), true, true, 0, &latestError); - - finishRequest(*occurrenceFetchReq, latestError, QMap<int, QOrganizerManager::Error>(), items); -} - -void QOrganizerJsonDbRequestThread::handleItemRemoveRequest(QOrganizerItemRemoveRequest *removeReq) -{ - QMap<int, QOrganizerManager::Error> errorMap; - QOrganizerManager::Error latestError = QOrganizerManager::NoError; - QMultiMap<QOrganizerItemId, QDate> exceptionDates; - // map from original remove req items list index to parent id - QMap<int, QOrganizerItemId> parentIds; - // map from original remove req items list index to item id - QMap<int, QOrganizerItemId> itemIds; - // map from parent item list index to parent item - QMap<int, QOrganizerItem> modifiedParents; - - QList<QOrganizerItem> items = removeReq->items(); - m_requestMgr->setActive(removeReq); - QOrganizerItem item; - int i; - for (i = 0; i < items.size(); i++) { - item = items[i]; - bool nullItemId = item.id().isNull(); - if ((item.type() == QOrganizerItemType::TypeEventOccurrence - || item.type() == QOrganizerItemType::TypeTodoOccurrence) - && nullItemId) { - // Dealing with occurence parent - // - check first if the occurence is valid - // - check then the storage location defined in id to be available - QOrganizerItemParent parentDetail = item.detail(QOrganizerItemDetail::TypeParent); - if (!parentDetail.parentId().isNull() && parentDetail.originalDate().isValid()) { - if (QOrganizerManager::NoError == checkRequestSpecificStorageLocation( - static_cast<const QOrganizerJsonDbItemId *>(QOrganizerManagerEngine::engineItemId(parentDetail.parentId()))->storageLocation())) { - // ok, insert to parentIds - exceptionDates.insert(parentDetail.parentId(), parentDetail.originalDate()); - parentIds.insert(i, parentDetail.parentId()); - } else { - // invalid storage location - latestError = QOrganizerManager::UnspecifiedError; - errorMap.insert(i, latestError); - } - } else { - // invalid occurence - latestError = QOrganizerManager::InvalidOccurrenceError; - errorMap.insert(i, latestError); - } - } else { - // Dealing with normal item - // - check first if the id is valid - // - check then the storage location defined in id to be available - if (!nullItemId) { - if (QOrganizerManager::NoError == checkRequestSpecificStorageLocation( - static_cast<const QOrganizerJsonDbItemId *>(QOrganizerManagerEngine::engineItemId(item.id()))->storageLocation())) { - // ok, insert to itemIds - itemIds.insert(i, item.id()); - } else { - // invalid storage location - latestError = QOrganizerManager::UnspecifiedError; - errorMap.insert(i, latestError); - } - } else { - // invalid id, since on removal there should not be "new items" - latestError = QOrganizerManager::BadArgumentError; - errorMap.insert(i, latestError); - } - } - } - - if (!itemIds.isEmpty() || !parentIds.isEmpty()) { - - // handle normal events - QMap<int, QOrganizerManager::Error> removeErrorMap; - QOrganizerManager::Error removeError = QOrganizerManager::NoError; - QList<QOrganizerItemId> itemIdsList = itemIds.values(); - removeItems(itemIdsList, &removeError, &removeErrorMap); - if (!removeErrorMap.isEmpty()) { - int itemIdsValuesIndex = 0; - QMap<int, QOrganizerItemId>::const_iterator iterator = itemIds.constBegin(); - while (iterator != itemIds.constEnd()) { - if (removeErrorMap.contains(itemIdsValuesIndex)) { - latestError = removeErrorMap.value(itemIdsValuesIndex); - errorMap.insert(iterator.key(), latestError); - } - itemIdsValuesIndex++; - } - } - - // check if any of the removed "normal" items was the parent of an occurrence to be removed - if (!exceptionDates.isEmpty()) { - foreach (const QOrganizerItemId &id, itemIdsList) { - if (exceptionDates.contains(id)) - exceptionDates.remove(id); - } - } - - // handle generated item occurrences: add new exception date to item's parent item recurrence detail - QMap<int, QOrganizerManager::Error> fetchErrorMap; - QOrganizerManager::Error fetchError = QOrganizerManager::NoError; - - QOrganizerJsonDbEngine::StorageLocations storageLocationsNeeded = resolveNeededStorageLocationsForItems(exceptionDates.keys()); - QList<QOrganizerItem> parentItems = m_storage->itemsById(exceptionDates.keys(), &fetchErrorMap, &fetchError, storageLocationsNeeded); - for (i = 0; i < parentItems.size(); i++) { - if (!fetchErrorMap.contains(i)) { - QOrganizerItem parentItem = parentItems[i]; - QList<QDate> addDateList = exceptionDates.values(parentItem.id()); - if (addDateList.isEmpty()) - continue; - QOrganizerItemRecurrence recurrenceDetail = parentItem.detail(QOrganizerItemDetail::TypeRecurrence); - QSet<QDate> exceptionDateSet = recurrenceDetail.exceptionDates(); - for (int j = 0; j < addDateList.size(); j++) - exceptionDateSet.insert(addDateList[j]); - - - recurrenceDetail.setExceptionDates(exceptionDateSet); - parentItem.saveDetail(&recurrenceDetail); - - modifiedParents.insert(i, parentItem); - } - } - - QMap<int, QOrganizerManager::Error> saveErrorMap; - QOrganizerManager::Error saveError = QOrganizerManager::NoError; - // modifiedParents all are already old items, so the storageLocation-param in saveItems() will be ignored - if (!modifiedParents.isEmpty()) - m_storage->saveItems(&modifiedParents, &saveErrorMap, &saveError, QOrganizerJsonDbEngine::UserDataStorage); - - if (!fetchErrorMap.isEmpty() || !saveErrorMap.isEmpty()) { - for (i = 0; i < parentItems.size(); i++) { - if (fetchErrorMap.contains(i) || saveErrorMap.contains(i)) { - QOrganizerItemId parentId = parentItems[i].id(); - // find the indexes in the original items list where this parent item was the parent of occurrence - QList<int> originalIndexes = parentIds.keys(parentId); - for (int j = 0; j < originalIndexes.size(); j++) { - latestError = QOrganizerManager::InvalidOccurrenceError; - errorMap.insert(j, latestError); - } - } - } - } - } - - finishRequest(*removeReq, latestError, errorMap); -} - -void QOrganizerJsonDbRequestThread::handleItemRemoveByIdRequest(QOrganizerItemRemoveByIdRequest *removeByIdReq) -{ - QMap<int, QOrganizerManager::Error> errorMap; - QOrganizerManager::Error latestError = QOrganizerManager::NoError; - QList<QOrganizerItemId> itemIds = removeByIdReq->itemIds(); - m_requestMgr->setActive(removeByIdReq); - - QList<QOrganizerItem> items; - if (!itemIds.isEmpty()) { - // FIXME: something to combine with validation work - bool validItemIds = false; - for (int i = 0; i < itemIds.size(); i++) { - const QOrganizerItemId &itemId = itemIds.at(i); - if (!itemId.isNull()) { - validItemIds = true; - break; - } - } - if (validItemIds) { - QOrganizerJsonDbEngine::StorageLocations storageLocationsNeeded = resolveNeededStorageLocationsForItems(itemIds); - latestError = checkRequestSpecificStorageLocation(storageLocationsNeeded); - if (QOrganizerManager::NoError == latestError) - removeItems(itemIds, &latestError, &errorMap); - } else { - latestError = QOrganizerManager::DoesNotExistError; - } - } - - finishRequest(*removeByIdReq, latestError, errorMap); -} - - -void QOrganizerJsonDbRequestThread::handleCollectionSaveRequest(QOrganizerCollectionSaveRequest *collectionSaveReq) -{ - QMap<int, QOrganizerCollection> collectionMap; - QMap<int, bool> collectionIsNewStatusMap; - QMap<int, QOrganizerManager::Error> errorMap; - QOrganizerManager::Error latestError = QOrganizerManager::NoError; - QList<QOrganizerCollection> collections = collectionSaveReq->collections(); - m_requestMgr->setActive(collectionSaveReq); - // if not defined, backend decides the default storage location -> UserDataStorage - const QOrganizerJsonDbEngine::StorageLocation storageLocation = QOrganizerJsonDbEngine::UserDataStorage; - - for (int i = 0; i < collections.size(); i++) { - QOrganizerCollection collection = collections.at(i); - bool collectionIsNew = collection.id().isNull(); - bool errorFound = false; - - if (!collectionIsNew) { - const QString managerUri = QOrganizerManager::buildUri(m_engine->managerName(), m_engine->managerParameters()); - if (managerUri != collection.id().managerUri()) {// check manager uri if is the same with the engine uri - latestError = QOrganizerManager::BadArgumentError; - errorFound = true; - } - } - - // Check the request is targeted to available storage location. - // Storage location errors are prioritised over less important other possible errors. - if (!errorFound) { - QOrganizerManager::Error error = QOrganizerManager::NoError; - if (collectionIsNew) - error = checkRequestSpecificStorageLocation(storageLocation); - else - error = checkRequestSpecificStorageLocation(static_cast<const QOrganizerJsonDbCollectionId *>(QOrganizerManagerEngine::engineCollectionId(collection.id()))->storageLocation()); - if (QOrganizerManager::NoError != error) { - latestError = error; - errorFound = true; - } - } - - if (errorFound) { - errorMap.insert(i, latestError); - } else { - collectionMap.insert(i, collection); - collectionIsNewStatusMap.insert(i, collectionIsNew); - } - } - if (!collectionMap.isEmpty()) { - m_storage->saveCollections(&collectionMap, &errorMap, &latestError, QOrganizerJsonDbEngine::UserDataStorage); - QMap<int, QOrganizerCollection>::const_iterator i = collectionMap.constBegin(); - while (i != collectionMap.constEnd()) { - if (!errorMap.contains(i.key())) { - if (collectionIsNewStatusMap.value(i.key())) - collections.replace(i.key(), i.value()); - } - ++i; - } - } - - finishRequest(*collectionSaveReq, latestError, errorMap, QList<QOrganizerItem>(), collections); -} - -void QOrganizerJsonDbRequestThread::handleCollectionFetchRequest(QOrganizerCollectionFetchRequest *collectionFetchReq) -{ - m_requestMgr->setActive(collectionFetchReq); - QOrganizerManager::Error latestError = QOrganizerManager::NoError; - // UserDataStorage is default storage location, if not otherwise set - QOrganizerJsonDbEngine::StorageLocations storageLocations = QOrganizerJsonDbEngine::UserDataStorage; - latestError = checkRequestSpecificStorageLocation(storageLocations); - QList<QOrganizerCollection> collections; - if (QOrganizerManager::NoError == latestError) - collections = m_storage->collections(&latestError, storageLocations); - - finishRequest(*collectionFetchReq, latestError, QMap<int, QOrganizerManager::Error>(), QList<QOrganizerItem>(), collections); -} - -void QOrganizerJsonDbRequestThread::handleCollectionRemoveRequest(QOrganizerCollectionRemoveRequest* collectionRemoveReq) -{ - QMap<int, QOrganizerManager::Error> errorMap; - QOrganizerManager::Error latestError = QOrganizerManager::NoError; - QList<QOrganizerCollectionId> collectionIds = collectionRemoveReq->collectionIds(); - m_requestMgr->setActive(collectionRemoveReq); - - if (!collectionIds.isEmpty()) { - QOrganizerJsonDbEngine::StorageLocations storageLocationsNeeded = resolveNeededStorageLocationsForCollections(collectionIds); - latestError = checkRequestSpecificStorageLocation(storageLocationsNeeded); - - if (QOrganizerManager::NoError == latestError) { - // only contain valid ones, i.e. default collection, empty, non-existing ones are removed - QMap<int, QOrganizerCollectionId> validCollectionIds; - for (int i = 0; i < collectionIds.size(); ++i) { - if (collectionIds.at(i) == m_storage->defaultCollection().id()) { - latestError = QOrganizerManager::PermissionsError; - errorMap.insert(i, latestError); - qWarning() << QOrganizerJsonDbStr::warningDefaultCollectionRemove(); - } else if (m_storage->collectionIds().contains(collectionIds.at(i))) { - validCollectionIds.insert(i, collectionIds.at(i)); - } else { - latestError = QOrganizerManager::BadArgumentError; - errorMap.insert(i, latestError); - } - } - int errorCount = errorMap.size(); - if (!validCollectionIds.isEmpty()) { - m_storage->removeCollections(validCollectionIds, &errorMap, &latestError); - // either all removed, or none removed - if (errorCount == errorMap.size()) { - // remove all items in those collections - QOrganizerItemCollectionFilter collectonFilter; - collectonFilter.setCollectionIds(QSet<QOrganizerCollectionId>::fromList(validCollectionIds.values())); - QOrganizerJsonDbEngine::StorageLocations storageLocationsNeeded = resolveNeededStorageLocationsForCollections(validCollectionIds.values()); - QList<QOrganizerItem> items = m_storage->items(QDateTime(), QDateTime(), collectonFilter, QList<QOrganizerItemSortOrder>(), - QOrganizerItemFetchHint(), &latestError, storageLocationsNeeded, - QOrganizerJsonDbDataStorage::FetchItemIds); - QList<QOrganizerItemId> itemIds; - for (int i = 0; i < items.length(); ++i) - itemIds.append(items.at(i).id()); - removeItems(itemIds, &latestError, &errorMap); - } - } - } - } - - finishRequest(*collectionRemoveReq, latestError, errorMap); -} - -void QOrganizerJsonDbRequestThread::initDefaultCollection() -{ - QOrganizerCollection defaultCollection = m_storage->defaultCollection(); - if (defaultCollection.id().isNull()) { - QOrganizerManager::Error error; - defaultCollection.setMetaData(QOrganizerCollection::KeyName, QOrganizerJsonDbStr::defaultCollectionDisplayName()); - m_storage->createDefaultCollection(&defaultCollection, &error); - } -} - -// Save helpers - -QOrganizerItem QOrganizerJsonDbRequestThread::fetchParentItem(const QOrganizerItem &occurrence) -{ - QList<QOrganizerItem> tmpParentItems; - QList<QOrganizerItemId> parentItemIdList; - QMap<int, QOrganizerManager::Error> parentErrorMap; - QOrganizerManager::Error parentError = QOrganizerManager::NoError; - QOrganizerItemParent parentDetail = occurrence.detail(QOrganizerItemDetail::TypeParent); - if (!parentDetail.isEmpty() && parentDetail.hasValue(QOrganizerItemParent::FieldParentId)) { - parentItemIdList.append(parentDetail.parentId()); - QOrganizerJsonDbEngine::StorageLocations storageLocationsNeeded = resolveNeededStorageLocationsForItems(parentItemIdList); - tmpParentItems = m_storage->itemsById(parentItemIdList, &parentErrorMap, &parentError, storageLocationsNeeded); - if (parentError == QOrganizerManager::NoError && tmpParentItems.length() > 0) - return tmpParentItems[0]; - } - // if parent was not found based on id, try with guid - if (!occurrence.guid().isEmpty()) { - QOrganizerItemDetailFieldFilter guidFilter; - guidFilter.setDetail(QOrganizerItemDetail::TypeGuid, QOrganizerItemGuid::FieldGuid); - guidFilter.setValue(occurrence.guid()); - - parentError = QOrganizerManager::NoError; - QOrganizerJsonDbEngine::StorageLocations allLocations(QOrganizerJsonDbEngine::UserDataStorage | QOrganizerJsonDbEngine::SystemStorage); - tmpParentItems = m_storage->items(QDateTime(), QDateTime(), guidFilter, QList<QOrganizerItemSortOrder>(), QOrganizerItemFetchHint(), &parentError, allLocations); - if (parentError == QOrganizerManager::NoError && tmpParentItems.length() > 0) - return tmpParentItems[0]; - } - return QOrganizerItem(); -} - -/*! - Returns true if and only if \a occurrenceType is the "Occurrence" version of \a parentType. - */ -bool QOrganizerJsonDbRequestThread::typesAreRelated(QOrganizerItemType::ItemType occurrenceType, QOrganizerItemType::ItemType parentType) -{ - return ((parentType == QOrganizerItemType::TypeEvent - && occurrenceType == QOrganizerItemType::TypeEventOccurrence) - || (parentType == QOrganizerItemType::TypeTodo - && occurrenceType == QOrganizerItemType::TypeTodoOccurrence)); -} - -bool QOrganizerJsonDbRequestThread::fixParentReferences(QOrganizerItem *item, const QOrganizerItem &parentItem) -{ -// bool itemIsOccurrence = !parentItem.isEmpty(); - - QOrganizerItemParent parentDetail = item->detail(QOrganizerItemDetail::TypeParent); - if (!parentDetail.hasValue(QOrganizerItemParent::FieldOriginalDate)) - return false; - - if (!parentDetail.hasValue(QOrganizerItemParent::FieldParentId)) { - parentDetail.setParentId(parentItem.id()); - item->saveDetail(&parentDetail); - } - return true; -} - -bool QOrganizerJsonDbRequestThread::fixGuidReferences(QOrganizerItem *item, const QOrganizerItem &parentItem) -{ - bool itemIsOccurrence = !parentItem.isEmpty(); - - if (!itemIsOccurrence && item->guid().isEmpty()) { - item->setGuid(QUuid::createUuid().toString()); - return true; - } - if (itemIsOccurrence) { - // item is an occurrence - if (parentItem.guid().isEmpty()) { - return false; - } - else if (item->guid().isEmpty()) { - item->setGuid(parentItem.guid()); - return true; - } else if (item->guid() != parentItem.guid()) { - return false; - } - } - return true; -} - -bool QOrganizerJsonDbRequestThread::fixCollectionReferences(QOrganizerItem *item, const QOrganizerItem &parentItem, bool itemIsNew, QOrganizerJsonDbEngine::StorageLocation storageLocation) -{ - bool itemIsOccurrence = !parentItem.isEmpty(); - QOrganizerCollectionId collectionId = item->collectionId(); - QOrganizerCollectionId parentCollectionId = parentItem.collectionId(); - if (itemIsOccurrence && (parentCollectionId.isNull() || !m_storage->collectionIds().contains(parentCollectionId))) - return false; - - if (!collectionId.isNull()) { - //If we could find the collection id in collection id list - if (!m_storage->collectionIds().contains(collectionId)) - return false; - if (itemIsOccurrence) { - // Does this occurrence have different collection id than it's parent - if (collectionId != parentCollectionId) - return false; - } - } else { - if (itemIsOccurrence) - item->setCollectionId(parentCollectionId); - else - item->setCollectionId(m_storage->defaultCollection().id()); - } - - const QOrganizerJsonDbCollectionId *collectionIdPtr = static_cast<const QOrganizerJsonDbCollectionId *>(QOrganizerManagerEngine::engineCollectionId(item->collectionId())); - const QOrganizerJsonDbItemId *itemIdPtr = static_cast<const QOrganizerJsonDbItemId *>(QOrganizerManagerEngine::engineItemId(item->id())); - if (!itemIdPtr && !itemIsNew) - return false; - - QOrganizerJsonDbEngine::StorageLocation collectionStorageLocation; - if (collectionIdPtr) - collectionStorageLocation = collectionIdPtr->storageLocation(); - else - return false; - if (itemIsNew && storageLocation != collectionStorageLocation) - return false; - else if (!itemIsNew && itemIdPtr->storageLocation() != collectionStorageLocation) - return false; - return true; -} - -// Fetch helpers - -QList<QOrganizerItem> QOrganizerJsonDbRequestThread::internalItems(const QDateTime& startDate, const QDateTime& endDate, const QOrganizerItemFilter& filter, - const QList<QOrganizerItemSortOrder>& sortOrders, const QOrganizerItemFetchHint& fetchHint, - QOrganizerManager::Error* error, bool forExport, QOrganizerJsonDbEngine::StorageLocations storageLocations) const -{ - QList<QOrganizerItem> timeUndefined; - QSet<QOrganizerItemId> parentsAdded; - QSet<QOrganizerItemId> parentsToBeAdded; - QMultiMap<QDateTime, QOrganizerItem> defaultSorted; - QList<QOrganizerItem> sorted; - QMap<QOrganizerItemId, QList<QDate> > exceptionDateMap; - bool isDefaultFilter = (filter.type() == QOrganizerItemFilter::DefaultFilter); - // fetch all parents stored to db - QList<QOrganizerItem> parentItems = m_storage->items(QDateTime(), QDateTime(), QOrganizerItemFilter(), QList<QOrganizerItemSortOrder>(), fetchHint, - error, storageLocations, QOrganizerJsonDbDataStorage::FetchParents); - if (QOrganizerManager::NoError != *error) - return sorted; - - // fetch all items (normal items and exception occurrences) stored in the given time period - // apply filters - QList<QOrganizerItem> items = m_storage->items(startDate, endDate, filter, sortOrders, fetchHint, error, storageLocations, QOrganizerJsonDbDataStorage::FetchItems); - - // generate occurrences for all parent items - foreach (QOrganizerItem parent, parentItems) { - if (!parent.detail(QOrganizerItemDetail::TypeRecurrence).isEmpty()) { - QOrganizerManager::Error recError = QOrganizerManager::NoError; - QList<QDate> exceptionDates; - QList<QOrganizerItem> recItems = internalItemOccurrences(parent, startDate, endDate, fetchHint, forExport ? 1 : QOrganizerJsonDbRequestThread::MaxOccurrenceCount, - false, false, &exceptionDates, &recError); - if (!exceptionDates.isEmpty()) - exceptionDateMap.insert(parent.id(), exceptionDates); - QOrganizerItem toAdd; - foreach (const QOrganizerItem &occurrence, recItems) { - if (!isDefaultFilter) { - if (!QOrganizerManagerEngine::testFilter(filter, occurrence)) - continue; - } - // if forExport is true, this loop is executed max. once - if (forExport) { - parentsAdded.insert(parent.id()); - toAdd = parent; - } else { - toAdd = occurrence; - } - - if (sortOrders.isEmpty()) { - if (!QOrganizerManagerEngine::addDefaultSorted(&defaultSorted, toAdd)) - timeUndefined.append(toAdd); - } else { - QOrganizerManagerEngine::addSorted(&sorted, toAdd, sortOrders); - } - } - } - } - - // add all normal items and exception occurrences to return list - foreach (const QOrganizerItem &item, items) { - // this is either Event or Todo - // or exception EventOccurrence or TodoOccurrence which has been stored to database - - if (!item.detail(QOrganizerItemDetail::TypeRecurrence).isEmpty()) { - // parent items have already been handled - continue; - } - QOrganizerItemParent parentDetail = item.detail(QOrganizerItemDetail::TypeParent); - if (!parentDetail.isEmpty() && !exceptionDateMap.value(parentDetail.parentId()).contains(parentDetail.originalDate())) - continue; - - if (forExport && !parentDetail.isEmpty()) { - QOrganizerItemId parentId = parentDetail.parentId(); - if (!parentId.isNull()) - parentsToBeAdded.insert(parentId); - } - if (sortOrders.isEmpty()) { - if (!QOrganizerManagerEngine::addDefaultSorted(&defaultSorted, item)) - timeUndefined.append(item); - } else { - QOrganizerManagerEngine::addSorted(&sorted, item, sortOrders); - } - } - - if (forExport && !parentsToBeAdded.isEmpty()) { - foreach (QOrganizerItem item, parentItems) { - if (parentsToBeAdded.contains(item.id()) && !parentsAdded.contains(item.id())) { - if (sortOrders.isEmpty()) - QOrganizerManagerEngine::addDefaultSorted(&defaultSorted, item); - else - QOrganizerManagerEngine::addSorted(&sorted, item, sortOrders); - } - } - } - - if (sortOrders.isEmpty()) { - sorted = defaultSorted.values(); - sorted.append(timeUndefined); - } - return sorted; -} - -QList<QOrganizerItem> QOrganizerJsonDbRequestThread::internalItemOccurrences(const QOrganizerItem &parentItem, const QDateTime &periodStart, const QDateTime &periodEnd, const QOrganizerItemFetchHint &fetchHint, - int maxCount, bool includeExceptions, bool sortItems, QList<QDate> *exceptionDates, QOrganizerManager::Error *error) const -{ - // given the generating item, grab it's QOrganizerItemRecurrence detail (if it exists), and calculate all of the dates within the given period. - QDateTime realPeriodStart(periodStart); - QDateTime realPeriodEnd(periodEnd); - QDateTime initialDateTime; - if (parentItem.type() == QOrganizerItemType::TypeEvent) { - QOrganizerEvent evt = parentItem; - initialDateTime = evt.startDateTime(); - } else if (parentItem.type() == QOrganizerItemType::TypeTodo) { - QOrganizerTodo todo = parentItem; - initialDateTime = todo.startDateTime().isValid() ? todo.startDateTime() : todo.dueDateTime(); - } else { - // erm... not a recurring item in our schema... - return QList<QOrganizerItem>(); - } - - if (realPeriodStart.isValid() && initialDateTime.isValid()) { - if (initialDateTime > realPeriodStart) - realPeriodStart = initialDateTime; - } else if (initialDateTime.isValid()) { - realPeriodStart = initialDateTime; - } - - if (!periodEnd.isValid()) { - // If no endDateTime is given, we'll only generate items that occur within the next 4 years of realPeriodStart. - if (realPeriodStart.isValid()) - realPeriodEnd = realPeriodStart.addDays(QOrganizerJsonDbRequestThread::DefaultTimePeriod); - else - realPeriodEnd = QDateTime::currentDateTimeUtc().addDays(QOrganizerJsonDbRequestThread::DefaultTimePeriod); - } - - if (realPeriodStart > realPeriodEnd) { - *error = QOrganizerManager::BadArgumentError; - return QList<QOrganizerItem>(); - } - - QList<QOrganizerItem> retn; - QList<QOrganizerItem> xoccurrences; - QOrganizerItemRecurrence recur = parentItem.detail(QOrganizerItemDetail::TypeRecurrence); - if (includeExceptions) { - // first, retrieve all persisted instances (exceptions) which occur between the specified datetimes. - QOrganizerItemFilter filter; - QOrganizerItemSortOrder sortOrder; - QOrganizerJsonDbEngine::StorageLocations storageLocationsNeeded = resolveNeededStorageLocationsForItems(QList<QOrganizerItemId>()<<parentItem.id()); - xoccurrences = m_storage->items(realPeriodStart, realPeriodEnd, filter, sortOrder, fetchHint, error, - storageLocationsNeeded, QOrganizerJsonDbDataStorage::FetchItemOccurrences, parentItem.id()); - } - - // then, generate the required (unchanged) instances from the parentItem. - // before doing that, we have to find out all of the exception dates. - QList<QDate> xdates; - foreach (const QDate &xdate, recur.exceptionDates()) - xdates += xdate; - - if (realPeriodStart.isValid()) { - QSet<QOrganizerRecurrenceRule> xrules = recur.exceptionRules(); - foreach (const QOrganizerRecurrenceRule& xrule, xrules) { - if (xrule.frequency() != QOrganizerRecurrenceRule::Invalid - && ((xrule.limitType() != QOrganizerRecurrenceRule::DateLimit) || (xrule.limitDate() >= realPeriodStart.date()))) { - // we cannot skip it, since it applies in the given time period. - QList<QDateTime> xdatetimes = QOrganizerManagerEngine::generateDateTimes(initialDateTime, xrule, realPeriodStart, realPeriodEnd, QOrganizerJsonDbRequestThread::MaxOccurrenceCount); - foreach (const QDateTime& xdatetime, xdatetimes) - xdates += xdatetime.date(); - } - } - } - // now generate a list of rdates (from the recurrenceDates and recurrenceRules) - - // QMap is used for storing dates, because we don't want to have duplicate dates and - // we want to have dates sorted - // Only key of the map is relevant (QDateTime), the value (int) is not used - QMap<QDateTime, int> rdateMap; - foreach (const QDate& rdate, recur.recurrenceDates()) - rdateMap.insert(QDateTime(rdate, initialDateTime.time()), 0); - - bool hasValidRule = false; - if (realPeriodStart.isValid()) { - QSet<QOrganizerRecurrenceRule> rrules = recur.recurrenceRules(); - foreach (const QOrganizerRecurrenceRule& rrule, rrules) { - if (rrule.frequency() != QOrganizerRecurrenceRule::Invalid) { - hasValidRule = true; - if ((rrule.limitType() != QOrganizerRecurrenceRule::DateLimit) || (rrule.limitDate() >= realPeriodStart.date())) { - // we cannot skip it, since it applies in the given time period. - QList<QDateTime> rdatetimes = QOrganizerManagerEngine::generateDateTimes(initialDateTime, rrule, realPeriodStart, realPeriodEnd, QOrganizerJsonDbRequestThread::MaxOccurrenceCount); - foreach (const QDateTime& rdatetime, rdatetimes) - rdateMap.insert(rdatetime, 0); - } - } - } - } - - // now order the contents of retn by date - QList<QDateTime> rdates = rdateMap.keys(); - - if (!hasValidRule && initialDateTime.isValid() && qBinaryFind(rdates, initialDateTime) == rdates.constEnd()) { - rdates.prepend(initialDateTime); - } - - // now for each rdate which isn't also an xdate - foreach (const QDateTime& rdate, rdates) { - if ((rdate >= realPeriodStart && rdate <= realPeriodEnd) - || (!realPeriodStart.isValid() && !realPeriodEnd.isValid() && rdate.isValid())) { - if (!xdates.contains(rdate.date())) { - // generate the required instance and add it to the return list. - retn.append(QOrganizerManagerEngine::generateOccurrence(parentItem, rdate)); - } else if (includeExceptions) { - for (int i = 0; i < xoccurrences.size(); i++) { - QOrganizerItemParent parentDetail = xoccurrences[i].detail(QOrganizerItemDetail::TypeParent); - if (parentDetail.originalDate() == rdate.date()) - retn.append(xoccurrences[i]); - } - } else if (exceptionDates) { - exceptionDates->append(rdate.date()); - } - - } - } - if (sortItems) { - // should we always sort if a maxCount is given? - QMultiMap<QDateTime, QOrganizerItem> defaultSorted; - foreach (QOrganizerItem item, retn) - QOrganizerManagerEngine::addDefaultSorted(&defaultSorted, item); - - retn = defaultSorted.values(); - } - - // and return the first maxCount entries. - return retn.mid(0, maxCount); -} - -void QOrganizerJsonDbRequestThread::removeItems(const QList<QOrganizerItemId> &itemIds, QOrganizerManager::Error *error, QMap<int, QOrganizerManager::Error> *errorMap) -{ - QMap<int, QOrganizerManager::Error> tmpErrorMap; - QOrganizerManager::Error tmpError = QOrganizerManager::NoError; - QList<QOrganizerItemId> removedParentIds; - QList<QOrganizerItemId> occurrenceIds; - - if (!itemIds.isEmpty()) { - // fetch items to find out if there are any persisted occurrences or parent items among them - QOrganizerJsonDbEngine::StorageLocations storageLocationsNeeded = resolveNeededStorageLocationsForItems(itemIds); - QList<QOrganizerItem> items = m_storage->itemsById(itemIds, &tmpErrorMap, &tmpError, storageLocationsNeeded); - foreach (QOrganizerItem item, items) { - if ((item.type() == QOrganizerItemType::TypeEvent || item.type() == QOrganizerItemType::TypeTodo) - && !item.detail(QOrganizerItemDetail::TypeRecurrence).isEmpty()) - removedParentIds.append(item.id()); - } - m_storage->removeItems(itemIds, errorMap, error); - - // remove all persisted occurrences of removed parent items - if (!removedParentIds.isEmpty()) { - // get all exception occurrence ids - - QOrganizerItemUnionFilter unionFilter; - for (int i = 0; i < removedParentIds.size(); i++) { - QOrganizerItemDetailFieldFilter detailFieldFilter; - detailFieldFilter.setDetail(QOrganizerItemDetail::TypeParent, QOrganizerItemParent::FieldParentId); - detailFieldFilter.setValue(QVariant::fromValue(removedParentIds[i])); - unionFilter.append(detailFieldFilter); - } - - tmpError = QOrganizerManager::NoError; - QOrganizerJsonDbEngine::StorageLocations storageLocationsNeeded = resolveNeededStorageLocationsForItems(removedParentIds); - QList<QOrganizerItem> occurrences = m_storage->items(QDateTime(), QDateTime(), unionFilter, QList<QOrganizerItemSortOrder>(), - QOrganizerItemFetchHint(), &tmpError, storageLocationsNeeded); - - for (int j = 0; j < occurrences.size(); j++) { - occurrenceIds.append(occurrences[j].id()); - } - } - tmpErrorMap.clear(); - tmpError = QOrganizerManager::NoError; - m_storage->removeItems(occurrenceIds, &tmpErrorMap, &tmpError); - } -} - -QOrganizerJsonDbEngine::StorageLocations QOrganizerJsonDbRequestThread::resolveNeededStorageLocationsForItems(const QList<QOrganizerItemId> &itemIds) const -{ - // figure out wich storage locations are needed based on items - const QOrganizerJsonDbEngine::StorageLocations availableStorageLocations = m_storage->availableStorageLocationsFlag(); - QOrganizerJsonDbEngine::StorageLocations storageLocationsNeeded(0); - foreach (QOrganizerItemId id, itemIds) { - const QOrganizerJsonDbItemId *engineId = static_cast<const QOrganizerJsonDbItemId *>(QOrganizerManagerEngine::engineItemId(id)); - if (!engineId) - continue; - - const QOrganizerJsonDbEngine::StorageLocations locations = engineId->storageLocation(); - if (locations > 0) { - if (locations & QOrganizerJsonDbEngine::UserDataStorage) - storageLocationsNeeded |= QOrganizerJsonDbEngine::UserDataStorage; - else if (locations & QOrganizerJsonDbEngine::SystemStorage) - storageLocationsNeeded |= QOrganizerJsonDbEngine::SystemStorage; - if (storageLocationsNeeded == availableStorageLocations) - break; - } - } - return storageLocationsNeeded; -} - -QOrganizerJsonDbEngine::StorageLocations QOrganizerJsonDbRequestThread::resolveNeededStorageLocationsForCollections(const QList<QOrganizerCollectionId> &collectionIds) const -{ - // figure out wich storage locations are needed based on collections - const QOrganizerJsonDbEngine::StorageLocations availableStorageLocations = m_storage->availableStorageLocationsFlag(); - QOrganizerJsonDbEngine::StorageLocations storageLocationsNeeded(0); - foreach (QOrganizerCollectionId id, collectionIds) { - const QOrganizerJsonDbCollectionId *engineId = static_cast<const QOrganizerJsonDbCollectionId *>(QOrganizerManagerEngine::engineCollectionId(id)); - if (!engineId) - continue; - - const QOrganizerJsonDbEngine::StorageLocations locations = engineId->storageLocation(); - if (locations > 0) { - if (locations & QOrganizerJsonDbEngine::UserDataStorage) - storageLocationsNeeded |= QOrganizerJsonDbEngine::UserDataStorage; - else if (locations & QOrganizerJsonDbEngine::SystemStorage) - storageLocationsNeeded |= QOrganizerJsonDbEngine::SystemStorage; - if (storageLocationsNeeded == availableStorageLocations) - break; - } - } - return storageLocationsNeeded; -} - -QOrganizerManager::Error QOrganizerJsonDbRequestThread::checkRequestSpecificStorageLocation(const QOrganizerJsonDbEngine::StorageLocations &requestSpecificStorageLocations) -{ - // Check the request is targeted to available storage location. - const QOrganizerJsonDbEngine::StorageLocations availableStoragelocations = m_storage->availableStorageLocationsFlag(); - if (requestSpecificStorageLocations && ((requestSpecificStorageLocations | availableStoragelocations) == availableStoragelocations)) - return QOrganizerManager::NoError; - else - return QOrganizerManager::UnspecifiedError; -} - -#include "moc_qorganizerjsondbrequestthread.cpp" - -QT_END_NAMESPACE_ORGANIZER diff --git a/src/plugins/organizer/jsondb/qorganizerjsondbrequestthread.h b/src/plugins/organizer/jsondb/qorganizerjsondbrequestthread.h deleted file mode 100644 index 477d98ae5..000000000 --- a/src/plugins/organizer/jsondb/qorganizerjsondbrequestthread.h +++ /dev/null @@ -1,173 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtOrganizer module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QORGANIZERJSONDBREQUESTTHREAD_H -#define QORGANIZERJSONDBREQUESTTHREAD_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/qthread.h> - -#include <QtOrganizer/qorganizercollectionchangeset.h> -#include <QtOrganizer/qorganizeritemchangeset.h> -#include <QtOrganizer/qorganizeritemrequests.h> - -#include "qorganizerjsondbengine.h" - -QT_FORWARD_DECLARE_CLASS(QMutex) -QT_FORWARD_DECLARE_CLASS(QTimer) - -QT_BEGIN_NAMESPACE_ORGANIZER - -class QOrganizerJsonDbRequestManager; -class QOrganizerJsonDbEngine; -class QOrganizerJsonDbDataStorage; - -class QOrganizerJsonDbRequestThread : public QThread -{ - Q_OBJECT -public: - QOrganizerJsonDbRequestThread(); - virtual ~QOrganizerJsonDbRequestThread(); - - void setEngine(QOrganizerJsonDbEngine* engine); - void addRequest(QOrganizerAbstractRequest* req); - bool waitForRequestFinished(QOrganizerAbstractRequest* req, int msecs); - void requestDestroyed(QOrganizerAbstractRequest* req); - QOrganizerCollection defaultCollection() const; - -public slots: - void handleRequest(QOrganizerAbstractRequest* req); - -signals: - void initialized(); - -protected: - virtual void run(); - -private slots: - // Since these three slots are triggered either by signals from data storage for notifications - // from JsonDb, or by the timer, and they are executed only in this thread, no mutex is needed. - void onItemAdded(const QOrganizerItemId &itemId); - void onItemChanged(const QOrganizerItemId &itemId); - void onItemRemoved(const QOrganizerItemId &itemId); - void onCollectionAdded(const QOrganizerCollectionId &collectionId); - void onCollectionChanged(const QOrganizerCollectionId &collectionId); - void onCollectionRemoved(const QOrganizerCollectionId &collectionId); - void onTimeout(); - -private: - void handleItemSaveRequest(QOrganizerItemSaveRequest* saveReq); - void handleItemFetchRequest(QOrganizerItemFetchRequest* fetchReq); - void handleItemIdFetchRequest(QOrganizerItemIdFetchRequest* idFetchReq); - void handleItemFetchByIdRequest(QOrganizerItemFetchByIdRequest* fetchByIdReq); - void handleItemFetchForExportRequest(QOrganizerItemFetchForExportRequest *fetchForExportReq); - void handleItemOccurrenceFetchRequest(QOrganizerItemOccurrenceFetchRequest* occurrenceFetchReq); - void handleItemRemoveRequest(QOrganizerItemRemoveRequest* removeReq); - void handleItemRemoveByIdRequest(QOrganizerItemRemoveByIdRequest *removeByIdReq); - void handleCollectionSaveRequest(QOrganizerCollectionSaveRequest* collectionSaveReq); - void handleCollectionFetchRequest(QOrganizerCollectionFetchRequest* collectionFetchReq); - void handleCollectionRemoveRequest(QOrganizerCollectionRemoveRequest* collectionRemoveReq); - void initDefaultCollection(); - - void finishRequest(QOrganizerAbstractRequest &request, QOrganizerManager::Error latestError, - const QMap<int, QOrganizerManager::Error> &errorMap, - const QList<QOrganizerItem> &itemList = QList<QOrganizerItem>(), - const QList<QOrganizerCollection> &collectionList = QList<QOrganizerCollection>(), - const QList<QOrganizerItemId> &itemIdList = QList<QOrganizerItemId>()); - - QOrganizerItem fetchParentItem(const QOrganizerItem &occurrence); - bool typesAreRelated(QOrganizerItemType::ItemType occurrenceType, QOrganizerItemType::ItemType parentType); - bool fixParentReferences(QOrganizerItem *item, const QOrganizerItem &parentItem); - bool fixGuidReferences(QOrganizerItem *item, const QOrganizerItem &parentItem); - bool fixCollectionReferences(QOrganizerItem *item, const QOrganizerItem &parentItem, bool itemIsNew, QOrganizerJsonDbEngine::StorageLocation storageLocation); - - QList<QOrganizerItem> internalItems(const QDateTime &startDate, const QDateTime &endDate, const QOrganizerItemFilter &filter, const QList<QOrganizerItemSortOrder> &sortOrders, - const QOrganizerItemFetchHint &fetchHint, QOrganizerManager::Error *error, bool forExport, QOrganizerJsonDbEngine::StorageLocations storageLocations) const; - QList<QOrganizerItem> internalItemOccurrences(const QOrganizerItem &parentItem, const QDateTime &periodStart, const QDateTime &periodEnd, const QOrganizerItemFetchHint &fetchHint, - int maxCount, bool includeExceptions, bool sortItems, QList<QDate> *exceptionDates, QOrganizerManager::Error *error) const; - - void removeItems(const QList<QOrganizerItemId> &itemIds, QOrganizerManager::Error *error, QMap<int, QOrganizerManager::Error> *errorMap); - void removeAlarmObjects(const QList<QOrganizerItemId> &itemIds, const QMap<int, QOrganizerManager::Error> &errorMap); - - bool validRequest(QOrganizerAbstractRequest *req); - bool validPlatform(QOrganizerAbstractRequest *req); - - QOrganizerManager::Error checkRequestSpecificStorageLocation(const QOrganizerJsonDbEngine::StorageLocations &requestSpecificStorageLocations); - QOrganizerJsonDbEngine::StorageLocations resolveNeededStorageLocationsForItems(const QList<QOrganizerItemId> &itemIds) const; - QOrganizerJsonDbEngine::StorageLocations resolveNeededStorageLocationsForCollections(const QList<QOrganizerCollectionId> &collectionIds) const; - - // Member variables - QOrganizerJsonDbEngine* m_engine; - QOrganizerJsonDbDataStorage* m_storage; - QOrganizerJsonDbRequestManager* m_requestMgr; - //Mutex to make the request state changes atomic - QMutex* m_reqStateMutex; - - // Handle item / collection changes - // They are only used by the notification system, so no mutex is needed. - static const int TIMEOUT_INTERVAL; - QTimer *m_timer; - QOrganizerItemChangeSet m_ics; - QOrganizerCollectionChangeSet m_ccs; - - void startTimer(); // Only used by onItemChanged() and onCollectionChanged() - - // constants for generating occurrences - - // number of days to use as time period for generating occurrences if no period is defined - static const int DefaultTimePeriod; - static const int MaxOccurrenceCount; - -}; - -QT_END_NAMESPACE_ORGANIZER - -#endif // QORGANIZERJSONDBREQUESTTHREAD_H diff --git a/src/plugins/organizer/jsondb/qorganizerjsondbstring.cpp b/src/plugins/organizer/jsondb/qorganizerjsondbstring.cpp deleted file mode 100644 index 4883b345b..000000000 --- a/src/plugins/organizer/jsondb/qorganizerjsondbstring.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtOrganizer module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qorganizerjsondbstring.h" diff --git a/src/plugins/organizer/jsondb/qorganizerjsondbstring.h b/src/plugins/organizer/jsondb/qorganizerjsondbstring.h deleted file mode 100644 index c9cb262d1..000000000 --- a/src/plugins/organizer/jsondb/qorganizerjsondbstring.h +++ /dev/null @@ -1,210 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtOrganizer module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QORGANIZERJSONDBSTRING_H -#define QORGANIZERJSONDBSTRING_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include <QtCore/qstring.h> - -#include <QtOrganizer/qorganizerglobal.h> - -QT_BEGIN_NAMESPACE_ORGANIZER - -class QOrganizerJsonDbStr -{ -public: - // JsonDb manager name - inline const static QString jsonDbManagerUri() { return QStringLiteral("qtorganizer:jsondb:"); } - inline const static QString jsonDbManagerName() { return QStringLiteral("jsondb"); } - - inline const static QString jsonDbSchemaPrefix() { return QStringLiteral("com.nokia.mt.organizer."); } - - // JsonDb object property names - inline const static QString jsonDbUuid() { return QStringLiteral("_uuid"); } - inline const static QString jsonDbType() { return QStringLiteral("_type"); } - inline const static QString jsonDbData() { return QStringLiteral("data"); } - inline const static QString jsonDbCount() { return QStringLiteral("count"); } - inline const static QString jsonDbError() { return QStringLiteral("error"); } - inline const static QString jsonDbCode() { return QStringLiteral("code"); } - inline const static QString jsonDbVersion() {return QStringLiteral("_version"); } - inline const static QString jsonDbValue() { return QStringLiteral("value"); } - - // JsonDb query strings - inline const static QString jsonDbQueryAllItems() { return QStringLiteral("[?_type in [\"com.nokia.mt.organizer.Event\", \"com.nokia.mt.organizer.Todo\", \"com.nokia.mt.organizer.EventOccurrence\", \"com.nokia.mt.organizer.TodoOccurrence\"]]"); } - inline const static QString jsonDbQueryAllEventItems() { return QStringLiteral("[?_type in [\"com.nokia.mt.organizer.Event\", \"com.nokia.mt.organizer.EventOccurrence\"]]"); } - inline const static QString jsonDbQueryEventTypeItems() { return QStringLiteral("[?_type=\"com.nokia.mt.organizer.Event\"]"); } - inline const static QString jsonDbQueryEventOccurenceTypeItems() { return QStringLiteral("[?_type=\"com.nokia.mt.organizer.EventOccurrence\"]"); } - inline const static QString jsonDbQueryAllTodoItems() { return QStringLiteral("[?_type in [\"com.nokia.mt.organizer.Todo\", \"com.nokia.mt.organizer.TodoOccurrence\"]]"); } - inline const static QString jsonDbQueryTodoTypeItems() { return QStringLiteral("[?_type=\"com.nokia.mt.organizer.Todo\"]"); } - inline const static QString jsonDbQueryTodoOccurenceTypeItems() { return QStringLiteral("[?_type=\"com.nokia.mt.organizer.TodoOccurrence\"]"); } - - inline const static QString jsonDbQueryAllCollections() { return QStringLiteral("[?_type=\"com.nokia.mt.organizer.Collection\"]"); } - inline const static QString jsonDbQueryParentItems() { return QStringLiteral("[?_type in [\"com.nokia.mt.organizer.Event\", \"com.nokia.mt.organizer.Todo\"]][?recurrenceDates exists | recurrenceRules exists | exceptionDates exists | exceptionRules exists]"); } - inline const static QString jsonDbQueryOccurrenceItems() { return QStringLiteral("[?_type in [\"com.nokia.mt.organizer.EventOccurrence\", \"com.nokia.mt.organizer.TodoOccurrence\"]]"); } - inline const static QString jsonDbQueryOccurrenceItemsByParent() { return QStringLiteral("[?_type in [\"com.nokia.mt.organizer.EventOccurrence\", \"com.nokia.mt.organizer.TodoOccurrence\"]][?parentUuid = \"%1\"]"); } - - inline const static QString jsonDbQueryEventViews() { return QStringLiteral("[?_type=\"com.nokia.mt.organizer.EventView\"]"); } - inline const static QString jsonDbQueryEventViewParentItems() { return QStringLiteral("[?_type=\"com.nokia.mt.organizer.EventView\"][?value.recurrenceRules exists]"); } - - inline const static QString jsonDbQueryCollectionUuidsTemplate() { return QStringLiteral("[?collectionUuid in [%1]]"); } - inline const static QString jsonDbQueryUuidsTemplate() { return QStringLiteral("[?_uuid in [%1]]"); } - - inline const static QString jsonDbNotificationQuery() { return QStringLiteral("[?_type in [\"com.nokia.mt.organizer.Event\", \"com.nokia.mt.organizer.EventView\", \"com.nokia.mt.organizer.EventOccurrence\", \"com.nokia.mt.organizer.Todo\", \"com.nokia.mt.organizer.TodoOccurrence\", \"com.nokia.mt.organizer.Collection\"]]"); } - inline const static QString jsonDbQueryEventStartDateTimeTemplate() { return QStringLiteral("[?startDateTime<=\"%1\"]"); } - inline const static QString jsonDbQueryEventEndDateTimeTemplate() { return QStringLiteral("[?endDateTime>=\"%1\"]"); } - - // collections - inline const static QString jsonDbCollectionType() { return QStringLiteral("com.nokia.mt.organizer.Collection"); } - - inline const static QString collectionDefaultFlag() { return QStringLiteral("isDefault"); } - inline const static QString collectionDisplayName() { return QStringLiteral("displayName"); } - inline const static QString collectionDescription() { return QStringLiteral("description"); } - inline const static QString collectionColor() { return QStringLiteral("color"); } - inline const static QString collectionImageUrl() { return QStringLiteral("imageUrl"); } - - inline const static QString defaultCollectionDisplayName() { return QStringLiteral("defaultCollection"); } - - // items - inline const static QString itemCollectionUuid() { return QStringLiteral("collectionUuid"); } - inline const static QString itemComments() { return QStringLiteral("comments"); } - inline const static QString itemDescription() { return QStringLiteral("description"); } - inline const static QString itemDisplayName() { return QStringLiteral("displayName"); } - inline const static QString itemGuid() { return QStringLiteral("guid"); } - inline const static QString itemTags() { return QStringLiteral("tags"); } - inline const static QString itemPriority() { return QStringLiteral("priority"); } - - inline const static QString itemRecurrenceDates() { return QStringLiteral("recurrenceDates"); } - inline const static QString itemRecurrenceRules() { return QStringLiteral("recurrenceRules"); } - inline const static QString itemExceptionDates() { return QStringLiteral("exceptionDates"); } - inline const static QString itemExceptionRules() { return QStringLiteral("exceptionRules"); } - - // item reminder - inline const static QString itemReminder() { return QStringLiteral("reminder"); } - inline const static QString itemReminderSecBeforeStart() { return QStringLiteral("secondsBeforeStart"); } - inline const static QString itemReminderRepetitionCount() { return QStringLiteral("repetitionCount"); } - inline const static QString itemReminderRepetitionDelay() { return QStringLiteral("repetitionDelay"); } - inline const static QString itemReminderDataUrl() { return QStringLiteral("dataUrl"); } - - // item recurrence rules - inline const static QString itemRecurrenceRuleFirstDayOfWeek() { return QStringLiteral("firstDayOfWeek"); } - inline const static QString itemRecurrenceRuleMonthsOfYear() { return QStringLiteral("monthsOfYear"); } - inline const static QString itemRecurrenceRuleFrequency() { return QStringLiteral("frequency"); } - inline const static QString itemRecurrenceRulePositions() { return QStringLiteral("positions"); } - inline const static QString itemRecurrenceRuleDaysOfMonth() { return QStringLiteral("daysOfMonth"); } - inline const static QString itemRecurrenceRuleDaysOfYear() { return QStringLiteral("daysOfYear"); } - inline const static QString itemRecurrenceRuleDaysOfWeek() { return QStringLiteral("daysOfWeek"); } - inline const static QString itemRecurrenceRuleWeeksOfYear() { return QStringLiteral("weeksOfYear"); } - inline const static QString itemRecurrenceRuleInterval() { return QStringLiteral("interval"); } - inline const static QString itemRecurrenceRuleLimitCount() { return QStringLiteral("limitCount"); } - inline const static QString itemRecurrenceRuleLimitDate() { return QStringLiteral("limitDate"); } - - // occurrence item parent - inline const static QString itemOccurrenceParent() { return QStringLiteral("parentUuid"); } - inline const static QString itemOccurrenceOriginalDate() { return QStringLiteral("originalDate"); } - - // events - inline const static QString jsonDbEventType() { return QStringLiteral("com.nokia.mt.organizer.Event"); } - inline const static QString jsonDbEventOccurrenceType() { return QStringLiteral("com.nokia.mt.organizer.EventOccurrence"); } - - inline const static QString eventStartDateTime() { return QStringLiteral("startDateTime"); } - inline const static QString eventEndDateTime() { return QStringLiteral("endDateTime"); } - inline const static QString eventIsAllDay() { return QStringLiteral("isAllDay"); } - - // event views - inline const static QString jsonDbEventViewType() { return QStringLiteral("com.nokia.mt.organizer.EventView"); } - inline const static QString eventIsSynthetic() { return QStringLiteral("isSynthetic"); } - - // event location - inline const static QString eventLocation() { return QStringLiteral("location"); } - - inline const static QString eventLocationDisplayName() { return QStringLiteral("displayName"); } - inline const static QString eventLocationGeo() { return QStringLiteral("geo"); } - inline const static QString eventLocationGeoLatitude() { return QStringLiteral("latitude"); } - inline const static QString eventLocationGeoLongitude() { return QStringLiteral("longitude"); } - - // event attendees - inline const static QString eventAttendees() { return QStringLiteral("attendees"); } - inline const static QString eventAttendeeName() { return QStringLiteral("name"); } - inline const static QString eventAttendeeParticipationRole() { return QStringLiteral("participationRole"); } - inline const static QString eventAttendeeParticipationStatus() { return QStringLiteral("participationStatus"); } - inline const static QString eventAttendeeEmailAddress() { return QStringLiteral("emailAddress"); } - inline const static QString eventAttendeeUuid() { return QStringLiteral("attendeeUuid"); } - - // event rsvp - inline const static QString eventRsvp() { return QStringLiteral("rsvp"); } - inline const static QString eventRsvpParticipationStatus() { return QStringLiteral("participationStatus"); } - inline const static QString eventRsvpParticipationRole() { return QStringLiteral("participationRole"); } - inline const static QString eventRsvpResponseRequirement() { return QStringLiteral("responseRequirement"); } - inline const static QString eventRsvpResponseDeadline() { return QStringLiteral("responseDeadline"); } - inline const static QString eventRsvpResponseDate() { return QStringLiteral("responseDate"); } - inline const static QString eventRsvpOrganizerName() { return QStringLiteral("organizerName"); } - inline const static QString eventRsvpOrganizerEmail() { return QStringLiteral("organizerEmail"); } - - // TODOs - inline const static QString jsonDbTodoType() { return QStringLiteral("com.nokia.mt.organizer.Todo"); } - inline const static QString jsonDbTodoOccurrenceType() { return QStringLiteral("com.nokia.mt.organizer.TodoOccurrence"); } - - inline const static QString todoStartDateTime() { return QStringLiteral("startDateTime"); } - inline const static QString todoDueDateTime() { return QStringLiteral("dueDateTime"); } - inline const static QString todoIsAllDay() { return QStringLiteral("isAllDay"); } - inline const static QString todoFinishedDateTime() { return QStringLiteral("finishedDateTime"); } - inline const static QString todoProgressPercentage() { return QStringLiteral("progressPercentage"); } - inline const static QString todoStatus() { return QStringLiteral("status"); } - - //warning string - inline const static QString warningCollectionRemove() { return QStringLiteral("Number of items deleted from jsondb is not equal to request!!"); } - inline const static QString warningDefaultCollectionRemove() { return QStringLiteral("Default collection can not be removed!"); } -}; - -QT_END_NAMESPACE_ORGANIZER - -#endif // QORGANIZERJSONDBSTRING_H diff --git a/src/plugins/organizer/organizer.pro b/src/plugins/organizer/organizer.pro index 2d3425e32..6f07cdf53 100644 --- a/src/plugins/organizer/organizer.pro +++ b/src/plugins/organizer/organizer.pro @@ -2,8 +2,6 @@ TEMPLATE = subdirs CONFIG += ordered -qtHaveModule(jsondb): SUBDIRS += jsondb - # Only compile this for tests (to make sure it compiles).. don't deploy this contains(QT_BUILD_PARTS,tests): SUBDIRS += skeleton diff --git a/tests/auto/auto.pri b/tests/auto/auto.pri index b8a8eceb3..bbcbae8a4 100644 --- a/tests/auto/auto.pri +++ b/tests/auto/auto.pri @@ -2,5 +2,3 @@ TEMPLATE = app CONFIG += console testcase QT += testlib - -!qtHaveModule(jsondb): DEFINES += QT_NO_JSONDB diff --git a/tests/auto/contacts/contacts.pro b/tests/auto/contacts/contacts.pro index 639afefcc..fe4cb4865 100644 --- a/tests/auto/contacts/contacts.pro +++ b/tests/auto/contacts/contacts.pro @@ -18,9 +18,3 @@ SUBDIRS += \ qcontactmanagerfiltering \ qmlcontacts -qtHaveModule(jsondb) { - SUBDIRS += qcontactjsondb \ - qcontactjsondbconverter \ - qcontactjsondbstoragelocations -} - diff --git a/tests/auto/contacts/qcontactasync/unittest/tst_qcontactasync.cpp b/tests/auto/contacts/qcontactasync/unittest/tst_qcontactasync.cpp index ce678f176..f08845fbe 100644 --- a/tests/auto/contacts/qcontactasync/unittest/tst_qcontactasync.cpp +++ b/tests/auto/contacts/qcontactasync/unittest/tst_qcontactasync.cpp @@ -65,7 +65,6 @@ #include <QtContacts/QContactName> #include <QtContacts/QContactIdFilter> -#include "jsondbprocess.h" #include "qcontactidmock.h" #include "qcontactmanagerdataholder.h" //QContactManagerDataHolder @@ -265,8 +264,6 @@ private: Qt::HANDLE m_resultsAvailableSlotThreadId; QScopedPointer<QContactManagerDataHolder> managerDataHolder; - JsonDbProcess m_jsondbProcess; - }; tst_QContactAsync::tst_QContactAsync() @@ -276,19 +273,10 @@ tst_QContactAsync::tst_QContactAsync() QCoreApplication::addLibraryPath(path); qRegisterMetaType<QContactAbstractRequest::State>("QContactAbstractRequest::State"); - - // Start JsonDb daemon if needed - if (QContactManager::availableManagers().contains("jsondb")) { - QString partitions_json = QFINDTESTDATA("partitions.json"); - QVERIFY2(!partitions_json.isEmpty(), "partitions.json file is missing"); - QVERIFY2(m_jsondbProcess.start(partitions_json), "Failed to start JsonDb process"); - } } tst_QContactAsync::~tst_QContactAsync() { - if (QContactManager::availableManagers().contains("jsondb")) - m_jsondbProcess.terminate(); } void tst_QContactAsync::initTestCase() @@ -585,9 +573,6 @@ void tst_QContactAsync::contactFetch() cfr.setSorting(sorting); cfr.setFetchHint(QContactFetchHint()); - if (cm->managerName() == "jsondb") - QSKIP("JSONDB backend does not support request cancelling, skipping..."); - int bailoutCount = MAX_OPTIMISTIC_SCHEDULING_LIMIT; // attempt to cancel 40 times. If it doesn't work due to threading, bail out. while (true) { QVERIFY(!cfr.cancel()); // not started @@ -984,9 +969,6 @@ void tst_QContactAsync::contactIdFetch() cfr.setFilter(fil); cfr.setSorting(sorting); - if (cm->managerName() == "jsondb") - QSKIP("JSONDB backend does not support request cancelling, skipping..."); - int bailoutCount = MAX_OPTIMISTIC_SCHEDULING_LIMIT; // attempt to cancel 40 times. If it doesn't work due to threading, bail out. while (true) { QVERIFY(!cfr.cancel()); // not started @@ -1048,8 +1030,7 @@ void tst_QContactAsync::contactIdFetch() } // Error cases not tested here as can not generate common error case - // for all backends. For example, for jsondb backend can not generate - // error at all. + // for all backends. } void tst_QContactAsync::contactRemove() @@ -1124,9 +1105,6 @@ void tst_QContactAsync::contactRemove() cm->saveContact(&temp); crr.setContactIds(cm->contactIds(dfil)); - if (cm->managerName() == "jsondb") - QSKIP("JSONDB backend does not support request cancelling, skipping..."); - // attempt to cancel 40 times. If it doesn't work due to threading, bail out. int bailoutCount = MAX_OPTIMISTIC_SCHEDULING_LIMIT; while (true) { @@ -1394,9 +1372,6 @@ void tst_QContactAsync::contactSave() saveList << temp; csr.setContacts(saveList); - if (cm->managerName() == "jsondb") - QSKIP("JSONDB backend does not support request cancelling, skipping..."); - int bailoutCount = MAX_OPTIMISTIC_SCHEDULING_LIMIT; // attempt to cancel 40 times. If it doesn't work due to threading, bail out. while (true) { QVERIFY(!csr.cancel()); // not started @@ -1496,7 +1471,7 @@ void tst_QContactAsync::contactSaveErrorHandling() QVERIFY(!csr.cancel()); QVERIFY(!csr.waitForFinished()); - // Save a group of contacts, including few TypeGroup contacts which are not supported by jsondb backend. + // Save a group of contacts, including few TypeGroup contacts which may not be supported by all backends. QContact testContact1, testContact2, testContact3, testContact4, testContact5, testContact6, testContact7,testContact8; QContactName nameDetail; nameDetail.setFirstName("Test Contact1"); @@ -1565,29 +1540,25 @@ void tst_QContactAsync::contactSaveErrorHandling() QVERIFY(spy.count() >= 1); // active + finished progress signals spy.clear(); - // Check errors, the group type is not supported by jsondb backend so contacts with that detail should report error. // Note, the returned value is actually set/remapped in to the errorMap by common code in qcontactmanagerengine - // TODO: move these tests to JsonDb-specific test class - if (cm->managerName() == "jsondb") { + if (!cm->supportedContactTypes().contains(QContactType::TypeGroup)) { QCOMPARE(csr.errorMap().value(0), QContactManager::InvalidContactTypeError); QCOMPARE(csr.errorMap().value(2), QContactManager::InvalidContactTypeError); QCOMPARE(csr.errorMap().value(5), QContactManager::InvalidContactTypeError); - QCOMPARE(csr.errorMap().value(6), QContactManager::BadArgumentError); - QVERIFY(csr.contacts()[5].id().isNull()); QCOMPARE(csr.error(), QContactManager::InvalidContactTypeError); - } - else { + + // With errors in the batch, we can't know that the other contacts have no error... + } else { QCOMPARE(csr.errorMap().value(0), QContactManager::NoError); QCOMPARE(csr.errorMap().value(2), QContactManager::NoError); QCOMPARE(csr.errorMap().value(5), QContactManager::NoError); - QCOMPARE(csr.errorMap().value(6), QContactManager::NoError); QCOMPARE(csr.error(), QContactManager::NoError); - } - QCOMPARE(csr.errorMap().value(1), QContactManager::NoError); - QCOMPARE(csr.errorMap().value(3), QContactManager::NoError); - QCOMPARE(csr.errorMap().value(4), QContactManager::NoError); - QCOMPARE(csr.errorMap().value(7), QContactManager::NoError); + QCOMPARE(csr.errorMap().value(1), QContactManager::NoError); + QCOMPARE(csr.errorMap().value(3), QContactManager::NoError); + QCOMPARE(csr.errorMap().value(4), QContactManager::NoError); + QCOMPARE(csr.errorMap().value(7), QContactManager::NoError); + } } void tst_QContactAsync::contactSaveRemovedContacts() @@ -1936,10 +1907,6 @@ void tst_QContactAsync::relationshipFetch() QFETCH(QString, uri); QScopedPointer<QContactManager> cm(prepareModel(uri)); - if (cm->managerName() == "jsondb") { - QSKIP("This contact manager does not support relationships!"); - } - if (cm->managerName() == "symbian") { QSKIP("This contact manager does not support the required relationship types for this test to pass!"); } @@ -2083,9 +2050,6 @@ void tst_QContactAsync::relationshipFetch() // cancelling rfr.setRelationshipType(QString()); - if (cm->managerName() == "jsondb") - QSKIP("JSONDB backend does not support request cancelling, skipping..."); - int bailoutCount = MAX_OPTIMISTIC_SCHEDULING_LIMIT; // attempt to cancel 40 times. If it doesn't work due to threading, bail out. while (true) { QVERIFY(!rfr.cancel()); // not started @@ -2146,10 +2110,6 @@ void tst_QContactAsync::relationshipRemove() QFETCH(QString, uri); QScopedPointer<QContactManager> cm(prepareModel(uri)); - if (cm->managerName() == "jsondb") { - QSKIP("This contact manager does not support relationships!"); - } - if (cm->managerName() == "symbian") { QSKIP("This contact manager does not support the required relationship types for this test to pass!"); } @@ -2239,9 +2199,6 @@ void tst_QContactAsync::relationshipRemove() relationships.clear(); relationships.push_back(r); - if (cm->managerName() == "jsondb") - QSKIP("JSONDB backend does not support request cancelling, skipping..."); - int bailoutCount = MAX_OPTIMISTIC_SCHEDULING_LIMIT; // attempt to cancel 40 times. If it doesn't work due to threading, bail out. while (true) { QVERIFY(!rrr.cancel()); // not started @@ -2306,10 +2263,6 @@ void tst_QContactAsync::relationshipSave() QFETCH(QString, uri); QScopedPointer<QContactManager> cm(prepareModel(uri)); - if (cm->managerName() == "jsondb") { - QSKIP("This contact manager does not support relationships!"); - } - if (cm->managerName() == "symbian") { QSKIP("This contact manager does not support the required relationship types for this test to pass!"); } @@ -2400,9 +2353,6 @@ void tst_QContactAsync::relationshipSave() saveList << testRel; rsr.setRelationships(saveList); - if (cm->managerName() == "jsondb") - QSKIP("JSONDB backend does not support request cancelling, skipping..."); - int bailoutCount = MAX_OPTIMISTIC_SCHEDULING_LIMIT; // attempt to cancel 40 times. If it doesn't work due to threading, bail out. while (true) { QVERIFY(!rsr.cancel()); // not started @@ -2688,10 +2638,6 @@ QContactManager* tst_QContactAsync::prepareModel(const QString& managerUri) if (cm->contacts().size() != 3) qWarning() << Q_FUNC_INFO << "Failed to prepare model!"; - if (cm->managerName() == "jsondb") { - return cm; - } - QContactRelationship arb; arb.setFirst(a); arb.setSecond(b); diff --git a/tests/auto/contacts/qcontactasync/unittest/unittest.pro b/tests/auto/contacts/qcontactasync/unittest/unittest.pro index 4dfbe1be8..48361ee75 100644 --- a/tests/auto/contacts/qcontactasync/unittest/unittest.pro +++ b/tests/auto/contacts/qcontactasync/unittest/unittest.pro @@ -3,11 +3,8 @@ include(../../../auto.pri) TARGET = tst_qcontactasync QT += contacts -qtHaveModule(jsondb): QT += jsondb SOURCES += tst_qcontactasync.cpp HEADERS += ../../qcontactmanagerdataholder.h -HEADERS += ../../../jsondbprocess.h INCLUDEPATH += ../.. -INCLUDEPATH += ../../.. DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 diff --git a/tests/auto/contacts/qcontactjsondb/partitions.json b/tests/auto/contacts/qcontactjsondb/partitions.json deleted file mode 100644 index 6d2e34d78..000000000 --- a/tests/auto/contacts/qcontactjsondb/partitions.json +++ /dev/null @@ -1,4 +0,0 @@ -[ - { "name" : "com.nokia.mt.User" }, - { "name" : "com.nokia.mt.System" } -] diff --git a/tests/auto/contacts/qcontactjsondb/qcontactjsondb.pro b/tests/auto/contacts/qcontactjsondb/qcontactjsondb.pro deleted file mode 100644 index c053463d8..000000000 --- a/tests/auto/contacts/qcontactjsondb/qcontactjsondb.pro +++ /dev/null @@ -1,33 +0,0 @@ -include(../../auto.pri) - -QT += contacts contacts-private jsondb - -SOURCES += tst_qcontactjsondbengine.cpp \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbenginefactory.cpp \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbengine.cpp \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbrequesthandler.cpp \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbrequestmanager.cpp \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbconverter.cpp \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbstring.cpp \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbid.cpp \ - qcontactjsondbbackup.cpp \ - synchronizedjsondbclient.cpp \ - synchronizedworker.cpp - -DEFINES += SRCDIR=\\\"$$PWD/\\\" - -INCLUDEPATH += ../../../../src/plugins/contacts/jsondb -INCLUDEPATH += ../.. - -HEADERS += qcontactjsondbbackup.h \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbenginefactory.h \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbengine.h \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbrequesthandler.h \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbrequestmanager.h \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbconverter.h \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbstring.h \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbid.h \ - synchronizedjsondbclient.h \ - synchronizedworker.h \ - ../../jsondbprocess.h -DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 diff --git a/tests/auto/contacts/qcontactjsondb/qcontactjsondbbackup.cpp b/tests/auto/contacts/qcontactjsondb/qcontactjsondbbackup.cpp deleted file mode 100644 index bd574b750..000000000 --- a/tests/auto/contacts/qcontactjsondb/qcontactjsondbbackup.cpp +++ /dev/null @@ -1,216 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QList> -#include "qcontactjsondbbackup.h" -#include "qcontactjsondbconverter.h" -#include "qcontactjsondbstring.h" - -QT_BEGIN_NAMESPACE_CONTACTS - -QContactJsonDbBackup::QContactJsonDbBackup() -{ - m_dbClient = new SynchronizedJsonDbClient(); - backupJsonDb(); -} - - -QContactJsonDbBackup::~QContactJsonDbBackup() -{ - revertJsonDb(); - delete m_dbClient; -} - - - - -bool QContactJsonDbBackup::loadTestData() { - QContactManager cm; - QContactSaveRequest csr; - - // save new contacts - QContact testContact; - QContactName nameDetail = testContact.detail<QContactName>(); - nameDetail.setFirstName("Harry"); - nameDetail.setLastName("Baker"); - testContact.saveDetail(&nameDetail); - QContactEmailAddress emailDetail; - emailDetail.setEmailAddress("Harry.Baker@ovi.com"); - emailDetail.setContexts(QContactDetail::ContextHome); - testContact.saveDetail(&emailDetail); - QContactPhoneNumber phoneNumberDetail; - QList<int> mySubTypes; - mySubTypes << QContactPhoneNumber::SubTypeMobile; - phoneNumberDetail.setSubTypes(mySubTypes); - phoneNumberDetail.setNumber("+358507654321"); - testContact.saveDetail(&phoneNumberDetail); - QList<QContact> saveList; - saveList << testContact; - - nameDetail.setFirstName("Paul"); - nameDetail.setLastName("Thomson"); - testContact.saveDetail(&nameDetail); - emailDetail.setEmailAddress("Paul.Thomson@ovi.com"); - emailDetail.setContexts(QContactDetail::ContextHome); - testContact.saveDetail(&emailDetail); - phoneNumberDetail.setSubTypes(mySubTypes); - phoneNumberDetail.setNumber("+358507654321"); - testContact.saveDetail(&phoneNumberDetail); - saveList << testContact; - - nameDetail.setFirstName("Julie"); - nameDetail.setLastName("King"); - testContact.saveDetail(&nameDetail); - emailDetail.setEmailAddress("Julie.King@ovi.com"); - emailDetail.setContexts(QContactDetail::ContextHome); - testContact.saveDetail(&emailDetail); - phoneNumberDetail.setSubTypes(mySubTypes); - phoneNumberDetail.setNumber("+3585012345"); - testContact.saveDetail(&phoneNumberDetail); - saveList << testContact; - - nameDetail.setFirstName("Angelina"); - nameDetail.setLastName("Row"); - testContact.saveDetail(&nameDetail); - emailDetail.setEmailAddress("Angelina.Row@ovi.com"); - emailDetail.setContexts(QContactDetail::ContextHome); - testContact.saveDetail(&emailDetail); - phoneNumberDetail.setSubTypes(mySubTypes); - phoneNumberDetail.setNumber("+3585012345"); - testContact.saveDetail(&phoneNumberDetail); - saveList << testContact; - - nameDetail.setFirstName("Natalie"); - nameDetail.setLastName("Watson"); - testContact.saveDetail(&nameDetail); - emailDetail.setEmailAddress("Natalie.Watson@ovi.com"); - emailDetail.setContexts(QContactDetail::ContextHome); - testContact.saveDetail(&emailDetail); - phoneNumberDetail.setSubTypes(mySubTypes); - phoneNumberDetail.setNumber("+358507654321"); - testContact.saveDetail(&phoneNumberDetail); - saveList << testContact; - - csr.setManager(&cm); - csr.setContacts(saveList); - csr.start(); - if (!csr.waitForFinished()) - return false; - if (csr.error() != QContactManager::NoError) - return false; - - return true; -} - - - - -void QContactJsonDbBackup::backupJsonDb() -{ - // Backup partitions for testing. - QString query = "[?_type=\"com.nokia.mt.contacts.Contact\"]"; - m_backupDataSystem = m_dbClient->query(query, QContactJsonDbStr::systemPartition()); - m_backupDataUser = m_dbClient->query(query, QContactJsonDbStr::userDataPartition()); -} - - -bool QContactJsonDbBackup::revertJsonDb() -{ - bool requestStatus = cleanJsonDb(); - requestStatus = requestStatus && addContacts(m_backupDataSystem, QContactJsonDbStr::systemPartition()); - requestStatus = requestStatus && addContacts(m_backupDataUser, QContactJsonDbStr::userDataPartition()); - m_backupDataSystem.clear(); - m_backupDataUser.clear(); - return requestStatus; -} - - -bool QContactJsonDbBackup::cleanJsonDb() -{ - QString query = "[?_type=\"com.nokia.mt.contacts.Contact\"]"; - - QList<QJsonObject> map = m_dbClient->query(query, QContactJsonDbStr::systemPartition()); - bool requestStatus = deleteContacts(map, QContactJsonDbStr::systemPartition()); - map = m_dbClient->query(query, QContactJsonDbStr::userDataPartition()); - requestStatus = requestStatus && deleteContacts(map, QContactJsonDbStr::userDataPartition()); - return requestStatus; -} - - -bool QContactJsonDbBackup::addContacts(const QList<QJsonObject> &objects, QString partition) { - - QList<QJsonObject> map; - for (int i = 0; i < objects.size(); ++i) { - QJsonObject item; - item = objects[i]; - map = m_dbClient->create(item, partition); - } - return true; -} - - -bool QContactJsonDbBackup::deleteContacts(const QList<QJsonObject> &objects, QString partition) { - - QList<QJsonObject> map; - for(int i = 0; i < objects.size(); ++i) { - QJsonObject item; - item = objects[i]; - map = m_dbClient->remove(item, partition); - } - return true; -} - - -int QContactJsonDbBackup::wasteSomeTime() { - int x=0; - int y=0; - for (int i=0; i<30; i++) - { - for (int j=0; j<100000000; j++) - { - y=(j*j); - } - x=i+y; - } - return x; -} - -QT_END_NAMESPACE_CONTACTS diff --git a/tests/auto/contacts/qcontactjsondb/qcontactjsondbbackup.h b/tests/auto/contacts/qcontactjsondb/qcontactjsondbbackup.h deleted file mode 100644 index 7051f0a7f..000000000 --- a/tests/auto/contacts/qcontactjsondb/qcontactjsondbbackup.h +++ /dev/null @@ -1,70 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QCONTACTJSONDBBACKUP_H -#define QCONTACTJSONDBBACKUP_H - -#include <QList> -#include <QtContacts/qcontactsglobal.h> -#include "synchronizedjsondbclient.h" - -QT_BEGIN_NAMESPACE_CONTACTS - -class QContactJsonDbBackup -{ -public: - QContactJsonDbBackup(); - ~QContactJsonDbBackup(); - bool loadTestData(); - bool cleanJsonDb(); -private: - void backupJsonDb(); - bool revertJsonDb(); - bool addContacts(const QList<QJsonObject> &objects, QString partition = QString()); - bool deleteContacts(const QList<QJsonObject> &objects, QString partition = QString()); -int wasteSomeTime(); - QList<QJsonObject> m_backupData, m_backupDataSystem, m_backupDataUser; - SynchronizedJsonDbClient* m_dbClient; -}; - -QT_END_NAMESPACE_CONTACTS - -#endif // QCONTACTJSONDBBACKUP_H diff --git a/tests/auto/contacts/qcontactjsondb/synchronizedjsondbclient.cpp b/tests/auto/contacts/qcontactjsondb/synchronizedjsondbclient.cpp deleted file mode 100644 index 02dfd5889..000000000 --- a/tests/auto/contacts/qcontactjsondb/synchronizedjsondbclient.cpp +++ /dev/null @@ -1,114 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QEventLoop> -#include <QVariant> -#include <QDebug> -#include <QtJsonDb/qjsondbreadrequest.h> -#include <QtJsonDb/qjsondbwriterequest.h> -#include "qcontactjsondbstring.h" -#include "synchronizedjsondbclient.h" - -#include "qcontactjsondbstring.h" - -QTCONTACTS_USE_NAMESPACE - -SynchronizedJsonDbClient::SynchronizedJsonDbClient() -{ - m_jsonDbConnection = new QJsonDbConnection(); - m_worker = new SynchronizedWorker(); - QObject::connect(m_jsonDbConnection, SIGNAL(error(QtJsonDb::QJsonDbConnection::ErrorCode,QString)), - m_worker, SLOT(onJsonDbConnectionError(QtJsonDb::QJsonDbConnection::ErrorCode,QString))); - m_jsonDbConnection->connectToServer(); -} - -SynchronizedJsonDbClient::~SynchronizedJsonDbClient() -{ - delete m_worker; - delete m_jsonDbConnection; -} - -QList<QJsonObject> SynchronizedJsonDbClient::query(const QString &query, QString partition) -{ - QJsonDbRequest *request; - request = new QJsonDbReadRequest(query, m_worker); - request->setPartition(partition); - return getResults(request); -} - -QList<QJsonObject> SynchronizedJsonDbClient::create(const QJsonObject &objects, QString partition) -{ - QJsonDbRequest *request; - request = new QJsonDbCreateRequest(objects, m_worker); - request->setPartition(partition); - return getResults(request); -} - -QList<QJsonObject> SynchronizedJsonDbClient::update(const QJsonObject &objects, QString partition) -{ - QJsonDbRequest *request = new QJsonDbUpdateRequest(objects, m_worker); - request->setPartition(partition); - return getResults(request); -} - -QList<QJsonObject> SynchronizedJsonDbClient::remove(const QJsonObject &objects, QString partition) -{ - QJsonDbRequest *request = new QJsonDbRemoveRequest(objects,m_worker); - request->setPartition(partition); - return getResults(request); -} - -QList<QJsonObject> SynchronizedJsonDbClient::getResults(QJsonDbRequest *request) -{ - QObject::connect(request, SIGNAL(finished()), m_worker, SLOT(onJsonDbRequestFinished())); - - QObject::connect(request, SIGNAL(error(QtJsonDb::QJsonDbRequest::ErrorCode,QString)), - m_worker, SLOT(onJsonDbRequestError(QtJsonDb::QJsonDbRequest::ErrorCode, QString))); - - if (m_jsonDbConnection->send(request)) { - m_worker->exec(); // Wait for db client to finish - QList<QJsonObject> results = request->takeResults(); - return results; - } else { - return QList<QJsonObject>(); - } -} - diff --git a/tests/auto/contacts/qcontactjsondb/synchronizedjsondbclient.h b/tests/auto/contacts/qcontactjsondb/synchronizedjsondbclient.h deleted file mode 100644 index 75c448486..000000000 --- a/tests/auto/contacts/qcontactjsondb/synchronizedjsondbclient.h +++ /dev/null @@ -1,77 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef SYNCHRONIZEDJSONDBCLIENT_H -#define SYNCHRONIZEDJSONDBCLIENT_H - -#include <QVariantMap> -#include <QString> -#include <QtJsonDb/qjsondbconnection.h> -#include <QtJsonDb/qjsondbrequest.h> -#include <QtContacts/qcontactsglobal.h> -#include "synchronizedworker.h" -#include "qcontactjsondbstring.h" - -QT_USE_NAMESPACE_JSONDB - -QT_BEGIN_NAMESPACE_CONTACTS - -class SynchronizedJsonDbClient -{ -public: - SynchronizedJsonDbClient(); - ~SynchronizedJsonDbClient(); - - QList<QJsonObject> query(const QString &query, QString partition = QContactJsonDbStr::userDataPartition()); - QList<QJsonObject> create(const QJsonObject &query, QString partition = QContactJsonDbStr::userDataPartition()); - QList<QJsonObject> update(const QJsonObject &query, QString partition = QContactJsonDbStr::userDataPartition()); - QList<QJsonObject> remove(const QJsonObject &query, QString partition = QContactJsonDbStr::userDataPartition()); - -private: - QList<QJsonObject> getResults(QJsonDbRequest *request); - - QJsonDbConnection *m_jsonDbConnection; - SynchronizedWorker* m_worker; -}; - -QT_END_NAMESPACE_CONTACTS - -#endif // SYNCHRONIZEDJSONDBCLIENT_H diff --git a/tests/auto/contacts/qcontactjsondb/synchronizedworker.cpp b/tests/auto/contacts/qcontactjsondb/synchronizedworker.cpp deleted file mode 100644 index 871776de1..000000000 --- a/tests/auto/contacts/qcontactjsondb/synchronizedworker.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QDebug> - -#include "synchronizedworker.h" - -SynchronizedWorker::SynchronizedWorker(QObject *parent) : - QEventLoop(parent) -{ -} - -void SynchronizedWorker::onJsonDbRequestFinished() -{ - QEventLoop::quit(); -} - -void SynchronizedWorker::onJsonDbRequestError(QtJsonDb::QJsonDbRequest::ErrorCode requestError, QString message) -{ - qWarning() << Q_FUNC_INFO << "Jsondb request error:" << requestError << "message:" << message; - QEventLoop::quit(); -} - -void SynchronizedWorker::onJsonDbConnectionError(QtJsonDb::QJsonDbConnection::ErrorCode connectionError, const QString &message) -{ - qWarning() << Q_FUNC_INFO << "Jsondb connection error:" << connectionError << "message:" << message; -} diff --git a/tests/auto/contacts/qcontactjsondb/synchronizedworker.h b/tests/auto/contacts/qcontactjsondb/synchronizedworker.h deleted file mode 100644 index e5b94056b..000000000 --- a/tests/auto/contacts/qcontactjsondb/synchronizedworker.h +++ /dev/null @@ -1,71 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef SYNCHRONIZEDWORKER_H -#define SYNCHRONIZEDWORKER_H - -#include <QEventLoop> -#include <QVariant> -#include <QMap> - -#include <QtJsonDb/qjsondbconnection.h> -#include <QJsonDbRequest> - -QT_USE_NAMESPACE_JSONDB - -class SynchronizedWorker : public QEventLoop -{ - Q_OBJECT - -public: - explicit SynchronizedWorker(QObject *parent = 0); - -public slots: - void onJsonDbRequestFinished(); - void onJsonDbRequestError(QtJsonDb::QJsonDbRequest::ErrorCode requestError, QString message); - void onJsonDbConnectionError(QtJsonDb::QJsonDbConnection::ErrorCode connectionError, const QString &message); - -signals: - -private: -}; - -#endif // SYNCHRONIZEDWORKER_H diff --git a/tests/auto/contacts/qcontactjsondb/tst_qcontactjsondbengine.cpp b/tests/auto/contacts/qcontactjsondb/tst_qcontactjsondbengine.cpp deleted file mode 100644 index 5b7d73064..000000000 --- a/tests/auto/contacts/qcontactjsondb/tst_qcontactjsondbengine.cpp +++ /dev/null @@ -1,2140 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtCore/QString> -#include <QtTest/QtTest> -#include "qcontactjsondbengine.h" -#include "qcontactjsondbenginefactory.h" -#include "qcontactjsondbbackup.h" -#include "qcontactjsondbglobal.h" -#include "qcontactjsondbconverter.h" - -#include "qcontactjsondbid.h" - -#include "synchronizedjsondbclient.h" -#include "jsondbprocess.h" - -QTCONTACTS_USE_NAMESPACE - -class tst_QContactJsondbEngine : public QObject -{ - Q_OBJECT - -public: - tst_QContactJsondbEngine(); - ~tst_QContactJsondbEngine(); -public slots: - void initTestCase(); - void init(); - void cleanup(); - void cleanupTestCase(); - -private Q_SLOTS: - void testSelfContactId(); - void testContactIds(); - void testContacts(); - void testContacts_data(); - void testContact(); - void testContact_data(); - void testSaveContact(); - void testSaveContacts(); - void testRemoveContacts(); - void testRemoveContact(); - void testContactDetailFilter(); - void testContactDetailFilter_data(); - void testContactSortOrder(); - void testContactSortOrder_data(); - void testContactUpdate(); - void testExtendedDetailsFromJsonDb(); - void testExtendedDetailsToJsonDb(); - void testSaveAndFetchToDefaultStorage(); - void testSaveAndFetchToUserDataStorage(); - void testSaveAndFetchToSystemStorage(); - void testPartialSaveToDefaultStorage(); - void testPartialSaveToUserdataStorage(); - void testPartialSaveToSystemStorage(); - void testSaveAndFetchToDefaultAndUserDataStorages(); - void testSaveAndFetchToDefaulAndSystemStorages(); - void testMultiFetchFromUserAndSystemStorages(); - void testFetchByIdFromUserAndSystemStorages(); - void testErrorsOnFetchFromWrongStorage(); - void testFetchWithIdsFromTwoStoragesInIdFilter(); - void testFetchErrorWithIdsFromWrongStorageInIdFilter(); - void testRemoveFromDefaultStorage(); - void testRemoveFromUserStorage(); - void testRemoveFromSystemStorage(); - void testRemoveFromUserAndSystemStorages(); - void testUpdateToUserDataStorage(); - void testUpdateToSystemDataStorage(); - void testWrongUpdateToDefaultStorage(); - void testWrongUpdateToSystemStorage(); - void testIdFetchRequestFromUserAndSystemStorages(); - void testSynchronousSaveAndFetchToDefaultStorage(); - -private: - void createPartition(const QString partition); - - QContactId saveTestContact(QContactManager &cm, QString &firstName, - QContactAbstractRequest::StorageLocation storageLocation - = QContactAbstractRequest::StorageLocation(0)); - - QContactId partialSaveTestContact(QContactManager &cm, QString &firstName, - QContactAbstractRequest::StorageLocation storageLocation - = QContactAbstractRequest::StorageLocation(0)); - - QContactManager::Error updateTestContact(QContactManager &cm, QContact &contact, QContactId &contactId, - QContactAbstractRequest::StorageLocation storageLocation - = QContactAbstractRequest::StorageLocation(0)); - - QList<QContact> fetchTestContacts(QContactManager &cm, QContactAbstractRequest::StorageLocations storageLocations = 0x0); - QList<QContact> fetchTestContactsById(QContactManager &cm, const QList<QContactId> &ids, QContactManager::Error &error); - - QContactManager::Error fetchTestContactByIdFilter(QContactManager &cm, QContactId &id, QContact &contact, QContactAbstractRequest::StorageLocations storageLocations = 0x0); - QContactManager::Error fetchTestContactsByIdFilter(QContactManager &cm, QList<QContactId> &ids, QList<QContact> &contacts, QContactAbstractRequest::StorageLocations storageLocations = 0x0); - - QContactManager::Error removeTestContact(QContactManager &cm, QContactId &contactId); - - QContactJsonDbEngine* m_engine; - QContactJsonDbBackup* m_myBackup; - SynchronizedJsonDbClient* m_dbClient; - JsonDbProcess m_jsondbProcess; -}; - -void tst_QContactJsondbEngine::initTestCase() -{ - // Backup and clear jsondb. - if (!m_myBackup) { - m_myBackup = new QContactJsonDbBackup; - m_myBackup->cleanJsonDb(); - } -} - -void tst_QContactJsondbEngine::init() -{ - m_myBackup->cleanJsonDb(); - QVERIFY2(m_myBackup->loadTestData(), "Failed to load test data"); // TODO: Proper fetching for test data. -} - -void tst_QContactJsondbEngine::cleanup() -{ -} - -void tst_QContactJsondbEngine::cleanupTestCase() -{ - if (m_myBackup) { - delete m_myBackup; - m_myBackup = 0; - } -} - -tst_QContactJsondbEngine::tst_QContactJsondbEngine():m_myBackup(0) -{ - m_engine = new QContactJsonDbEngine(); - m_dbClient = new SynchronizedJsonDbClient(); - - QString partitions_json = QFINDTESTDATA("partitions.json"); - QVERIFY2(!partitions_json.isEmpty(), "partitions.json file is missing"); - QVERIFY2(m_jsondbProcess.start(partitions_json), "Failed to start JsonDb process"); -} - -tst_QContactJsondbEngine::~tst_QContactJsondbEngine() -{ - delete m_engine; - delete m_dbClient; - m_jsondbProcess.terminate(); -} - -void tst_QContactJsondbEngine::createPartition(const QString partition) -{ - // Check if partition already exist. - QString partitionQuery = "[?_type=\"Partition\"][?name=\"" + partition + "\"]"; - QList<QJsonObject> queryResponse = m_dbClient->query(partitionQuery); - - qDebug() << Q_FUNC_INFO << "partition check response:" << queryResponse; - - // If no such partition, create one. - if (queryResponse.isEmpty()) { - QJsonObject object; - object.insert(QStringLiteral("_type"), QStringLiteral("Partition")); - object.insert(QStringLiteral("name"), partition); - QVariantMap partitionCreateResponse = m_dbClient->create(object).first().toVariantMap(); - qWarning() << Q_FUNC_INFO << "Created partition:" << partition << "with reponse:" << partitionCreateResponse; - return; - } - // Debug, remove when this works. - qDebug() << Q_FUNC_INFO << "Partition query response for partition:" << partition << "is" << queryResponse; -} - -QContactId tst_QContactJsondbEngine::saveTestContact(QContactManager &cm, QString &firstName, - QContactAbstractRequest::StorageLocation storageLocation) -{ - QContactName nameDetail; - nameDetail.setFirstName(firstName); - nameDetail.setLastName("StorageLocationTestContact"); - - QContact testContact; - testContact.saveDetail(&nameDetail); - - QContactSaveRequest saveRequest; - saveRequest.setManager(&cm); - saveRequest.setContact(testContact); - if (storageLocation) - saveRequest.setStorageLocation(storageLocation); - saveRequest.start(); - saveRequest.waitForFinished(); - return saveRequest.contacts().first().id(); -} - -QContactManager::Error tst_QContactJsondbEngine::updateTestContact(QContactManager &cm, QContact &contact, QContactId &contactId, QContactAbstractRequest::StorageLocation storageLocation) -{ - QContactSaveRequest saveRequest; - saveRequest.setManager(&cm); - saveRequest.setContact(contact); - if (storageLocation) - saveRequest.setStorageLocation(storageLocation); - saveRequest.start(); - saveRequest.waitForFinished(); - contactId = saveRequest.contacts().first().id(); - return saveRequest.error(); -} - -QList<QContact> tst_QContactJsondbEngine::fetchTestContacts(QContactManager &cm, QContactAbstractRequest::StorageLocations storageLocations) -{ - QContactFetchRequest fetchRequest; - fetchRequest.setManager(&cm); - if (storageLocations) - fetchRequest.setStorageLocations(storageLocations); - fetchRequest.start(); - fetchRequest.waitForFinished(); - QList<QContact> contacts = fetchRequest.contacts(); - return contacts; -} - -QContactManager::Error tst_QContactJsondbEngine::fetchTestContactsByIdFilter(QContactManager &cm, QList<QContactId> &ids, QList<QContact> &contacts, QContactAbstractRequest::StorageLocations storageLocations) -{ - QContactIdFilter idFilter; - foreach (QContactId id, ids) - idFilter.add(id); - - QContactFetchRequest fetchRequest; - fetchRequest.setManager(&cm); - fetchRequest.setFilter(idFilter); - if (storageLocations) - fetchRequest.setStorageLocations(storageLocations); - fetchRequest.start(); - fetchRequest.waitForFinished(); - if (fetchRequest.contacts().isEmpty()) - contacts = QList<QContact>(); - else - contacts = fetchRequest.contacts(); - return fetchRequest.error(); -} - -QContactManager::Error tst_QContactJsondbEngine::fetchTestContactByIdFilter(QContactManager &cm, QContactId &id, QContact &contact, QContactAbstractRequest::StorageLocations storageLocations) -{ - QContactIdFilter idFilter; - idFilter.add(id); - - QContactFetchRequest fetchRequest; - fetchRequest.setManager(&cm); - fetchRequest.setFilter(idFilter); - if (storageLocations) - fetchRequest.setStorageLocations(storageLocations); - fetchRequest.start(); - fetchRequest.waitForFinished(); - if (!fetchRequest.contacts().isEmpty()) - contact = fetchRequest.contacts().first(); - return fetchRequest.error(); -} - -QList<QContact> tst_QContactJsondbEngine::fetchTestContactsById(QContactManager &cm, const QList<QContactId> &ids, QContactManager::Error &error) -{ - QContactFetchByIdRequest fetchByIdRequest; - fetchByIdRequest.setManager(&cm); - fetchByIdRequest.setIds(ids); - fetchByIdRequest.start(); - fetchByIdRequest.waitForFinished(); - error = fetchByIdRequest.error(); - QList<QContact> contacts = fetchByIdRequest.contacts(); - return contacts; -} - -QContactManager::Error tst_QContactJsondbEngine::removeTestContact(QContactManager &cm, QContactId &contactId) -{ - QContactRemoveRequest removeRequest; - removeRequest.setManager(&cm); - removeRequest.setContactId(contactId); - removeRequest.start(); - removeRequest.waitForFinished(); - return removeRequest.error(); -} - -void tst_QContactJsondbEngine::testSaveAndFetchToDefaultStorage() -{ - // Get original count of contacts in the defaul storage. - QContactManager cm; - int originalCount = cm.contactIds().size(); - - // Test save and fetch to default storage. - QString name("SaveToDefault"); - saveTestContact(cm, name); - QList<QContact> contacts = fetchTestContacts(cm); - QCOMPARE(contacts.size(), originalCount+1); - bool contactFound = false; - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>().firstName() == name) contactFound=true; - } - QVERIFY(contactFound == true); - - // Check explicitely that fetch from userData storage gives the same. - contacts = fetchTestContacts(cm, QContactAbstractRequest::UserDataStorage); - QCOMPARE(contacts.size(), originalCount+1); - contactFound = false; - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>().firstName() == name) contactFound=true; - } - QVERIFY(contactFound == true); - - // Verify the system storage is not affected (it should be cleaned by test init). - contacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage); - QCOMPARE(contacts.size(), 0); -} - -void tst_QContactJsondbEngine::testSaveAndFetchToUserDataStorage() -{ - // Get original count of contacts in the defaul storage. - QContactManager cm; - int originalCount = cm.contactIds().size(); - - // Test save and fetch to userdata storage. - QString name("SaveToUser"); - saveTestContact(cm, name, QContactAbstractRequest::UserDataStorage); - QList<QContact> contacts = fetchTestContacts(cm, QContactAbstractRequest::UserDataStorage); - QCOMPARE(contacts.size(), originalCount+1); - bool contactFound = false; - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>().firstName() == name) contactFound=true; - } - QVERIFY(contactFound == true); - - // Verify the fetch from default gives the same. - contacts = fetchTestContacts(cm); - QCOMPARE(contacts.size(), originalCount+1); - contactFound = false; - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>().firstName() == name) contactFound=true; - } - QVERIFY(contactFound == true); - - // Verify the system storage is not affected (it should be cleaned by test init). - contacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage); - QCOMPARE(contacts.size(), 0); -} - -void tst_QContactJsondbEngine::testSaveAndFetchToSystemStorage() -{ - // Get original count of contacts in the defaul storage. - QContactManager cm; - int originalCount = cm.contactIds().size(); - - // Test save and fetch to system storage. - QString saveName("SaveToSystem"); - QContactId originalId = saveTestContact(cm, saveName, QContactAbstractRequest::SystemStorage); - QList<QContact> contacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage); - QCOMPARE(contacts.size(), 1); - QCOMPARE(contacts.first().id(), originalId); - QCOMPARE(contacts.first().detail<QContactName>().firstName(), saveName); - - // Verify userData storage is not affected. - contacts = fetchTestContacts(cm, QContactAbstractRequest::UserDataStorage); - QCOMPARE(contacts.size(), originalCount); - bool contactFound = false; - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>().firstName() == saveName) contactFound = true; - } - QVERIFY(!contactFound); - - // Verify default storage is not affected. - contacts = fetchTestContacts(cm); - QCOMPARE(contacts.size(), originalCount); - contactFound = false; - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>().firstName() == saveName) contactFound = true; - } - QVERIFY(!contactFound); -} - -QContactId tst_QContactJsondbEngine::partialSaveTestContact(QContactManager &cm, QString &firstName, QContactAbstractRequest::StorageLocation storageLocation) -{ - QContact testContact; - - QContactName nameDetail; - nameDetail.setFirstName(firstName); - nameDetail.setLastName("StorageLocationTestContact"); - testContact.saveDetail(&nameDetail); - - QContactEmailAddress emailDetail; - emailDetail.setEmailAddress("partial.save@email.address"); - testContact.saveDetail(&emailDetail); - - QContactPhoneNumber phoneDetail; - phoneDetail.setNumber("4711-4711"); - testContact.saveDetail(&phoneDetail); - - QContactSaveRequest saveRequest; - saveRequest.setManager(&cm); - saveRequest.setContact(testContact); - - QList<QContactDetail::DetailType> mask; - mask.append(QContactDetail::TypeName); - saveRequest.setTypeMask(mask); - - - if (storageLocation) - saveRequest.setStorageLocation(storageLocation); - saveRequest.start(); - saveRequest.waitForFinished(); - - return saveRequest.contacts().first().id(); -} - -void tst_QContactJsondbEngine::testPartialSaveToDefaultStorage() -{ - // Get original count of contacts in the defaul storage. - QContactManager cm; - int originalCount = cm.contactIds().size(); - - // Test partial save and fetch to userdata storage. - QString saveName("PartialSaveToUser"); - QContactId originalId = partialSaveTestContact(cm, saveName); - QList<QContact> contacts = fetchTestContacts(cm); - - // Verify default storage got the contact. - contacts = fetchTestContacts(cm); - QCOMPARE(contacts.size(), originalCount +1); - bool contactFound = false; - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>().firstName() == saveName) { - QCOMPARE(curr.id(), originalId); - contactFound = true; - } - } - QVERIFY(contactFound); - - // Verify system storage is not affected. - contacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage); - QCOMPARE(contacts.size(), 0); -} - - -void tst_QContactJsondbEngine::testPartialSaveToUserdataStorage() -{ - // Get original count of contacts in the defaul storage. - QContactManager cm; - int originalCount = cm.contactIds().size(); - - // Test partial save and fetch to userdata storage. - QString saveName("PartialSaveToUser"); - QContactId originalId = partialSaveTestContact(cm, saveName, QContactAbstractRequest::UserDataStorage); - QList<QContact> contacts = fetchTestContacts(cm, QContactAbstractRequest::UserDataStorage); - - // Verify userdata storage got the contact. - contacts = fetchTestContacts(cm); - QCOMPARE(contacts.size(), originalCount +1); - bool contactFound = false; - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>().firstName() == saveName) { - QCOMPARE(curr.id(), originalId); - contactFound = true; - } - } - QVERIFY(contactFound); - - // Verify system storage is not affected. - contacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage); - QCOMPARE(contacts.size(), 0); -} - -void tst_QContactJsondbEngine::testPartialSaveToSystemStorage() -{ - // Get original count of contacts in the defaul storage. - QContactManager cm; - int originalCount = cm.contactIds().size(); - - // Test partial save and fetch to system storage. - QString saveName("PartialSaveToSystem"); - QContactId originalId = partialSaveTestContact(cm, saveName, QContactAbstractRequest::SystemStorage); - QList<QContact> contacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage); - QCOMPARE(contacts.size(), 1); - QCOMPARE(contacts.first().id(), originalId); - QCOMPARE(contacts.first().detail<QContactName>().firstName(), saveName); - - // Verify userData storage is not affected. - contacts = fetchTestContacts(cm, QContactAbstractRequest::UserDataStorage); - QCOMPARE(contacts.size(), originalCount); - bool contactFound = false; - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>().firstName() == saveName) contactFound = true; - } - QVERIFY(!contactFound); - - // Verify default storage is not affected. - contacts = fetchTestContacts(cm); - QCOMPARE(contacts.size(), originalCount); - contactFound = false; - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>().firstName() == saveName) contactFound = true; - } - QVERIFY(!contactFound); -} - -void tst_QContactJsondbEngine::testSaveAndFetchToDefaultAndUserDataStorages() -{ - // Get original count of contacts in the defaul storage. - QContactManager cm; - int originalCount = cm.contactIds().size(); - - // Save test contact to default and userData storages. - QString nameForDefaultStorageContact("SaveToDefault"); - QContactId contactIdDefaultStorage = saveTestContact(cm, nameForDefaultStorageContact); - QString nameForUserStorageContact("SaveToUser"); - QContactId contactIdUserdataStorage = saveTestContact(cm, nameForUserStorageContact, QContactAbstractRequest::UserDataStorage); - - // Check that fetch from default storage gives them both back to us. - QList<QContact> contacts = fetchTestContacts(cm); - QCOMPARE(contacts.size(), originalCount+2); - int contactsWithNameInDefaultStorage = 0; - int contactsWithNameInUserStorage = 0; - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>().firstName() == nameForDefaultStorageContact) { - QCOMPARE(curr.id(), contactIdDefaultStorage); - contactsWithNameInDefaultStorage++; - } - if (curr.detail<QContactName>().firstName() == nameForUserStorageContact) { - QCOMPARE(curr.id(), contactIdUserdataStorage); - contactsWithNameInUserStorage++; - } - } - QCOMPARE(contactsWithNameInDefaultStorage, 1); - QCOMPARE(contactsWithNameInUserStorage, 1); - - // Verify the fetch from the userData gives the same. - contacts = fetchTestContacts(cm, QContactAbstractRequest::UserDataStorage); - QCOMPARE(contacts.size(), originalCount+2); - contactsWithNameInDefaultStorage = 0; - contactsWithNameInUserStorage = 0; - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>().firstName() == nameForDefaultStorageContact) { - QCOMPARE(curr.id(), contactIdDefaultStorage); - contactsWithNameInDefaultStorage++; - } - if (curr.detail<QContactName>().firstName() == nameForUserStorageContact) { - QCOMPARE(curr.id(), contactIdUserdataStorage); - contactsWithNameInUserStorage++; - } - } - QCOMPARE(contactsWithNameInDefaultStorage, 1); - QCOMPARE(contactsWithNameInUserStorage, 1); - - // Verify the system storage is not affected (it should be cleaned by test init). - contacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage); - QCOMPARE(contacts.size(), 0); -} - -void tst_QContactJsondbEngine::testSaveAndFetchToDefaulAndSystemStorages() -{ - // Get original count of contacts in the defaul storage. - QContactManager cm; - int originalCount = cm.contactIds().size(); - - // Save test contact to default and system storages. - QString nameForDefaultStorageContact("SaveToDefault"); - QContactId contactIdForDefaultStorageContact = saveTestContact(cm, nameForDefaultStorageContact); - - QString nameForSystemStorageContact("SaveToSystem"); - QContactId contactIdForSystemStorageContact = saveTestContact(cm, nameForSystemStorageContact, QContactAbstractRequest::SystemStorage); - - // Check that fetch from default storage gives the right contact back to us. - QList<QContact> contacts = fetchTestContacts(cm); - QCOMPARE(contacts.size(), originalCount+1); - int contactsFound = 0; - foreach (QContact current, contacts) { - if (current.detail<QContactName>().firstName() == nameForDefaultStorageContact) { - QCOMPARE(current.id(), contactIdForDefaultStorageContact); - contactsFound++; - } - } - QCOMPARE(contactsFound, 1); - - // Check that fetch from system storage gives the right contact back to us. - contacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage); - QCOMPARE(contacts.size(), 1); - QCOMPARE(contacts.first().id(), contactIdForSystemStorageContact); - QCOMPARE(contacts.first().detail<QContactName>().firstName(), nameForSystemStorageContact); -} - -void tst_QContactJsondbEngine::testMultiFetchFromUserAndSystemStorages() -{ - // Get original count of contacts in the defaul storage. - QContactManager cm; - int originalCount = cm.contactIds().size(); - - // Save test contact to default and system storages. - QString nameForDefaultStorageContact("FetchFromDefault"); - QContactId idForDefaultStorageContact = saveTestContact(cm, nameForDefaultStorageContact); - - QString nameForSystemStorageContact("FetchFromSystem"); - QContactId idForSystemStorageContact = saveTestContact(cm, nameForSystemStorageContact, QContactAbstractRequest::SystemStorage); - - // Check that fetch from both storages at the same time gives the right contacts back to us. - QList<QContact> contacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage | QContactAbstractRequest::UserDataStorage); - QCOMPARE(contacts.size(), originalCount+2); - - int contactsDefaultFound = 0; - int contactsSystemFound = 0; - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>().firstName() == nameForDefaultStorageContact) { - contactsDefaultFound++; - QCOMPARE(curr.id(), idForDefaultStorageContact); - } - if (curr.detail<QContactName>().firstName() == nameForSystemStorageContact) { - contactsSystemFound++; - QCOMPARE(curr.id(), idForSystemStorageContact); - } - } - - QCOMPARE(contactsDefaultFound, 1); - QCOMPARE(contactsSystemFound, 1); -} - -void tst_QContactJsondbEngine::testFetchByIdFromUserAndSystemStorages() -{ - // Save test contact to user and system storages. - - QContactManager cm; - QString nameForUserdataStorageContact("FetchByIdFromDefault"); - QContactId idForUserdataStorageContact = saveTestContact(cm, nameForUserdataStorageContact); - - QString nameForSystemStorageContact("FetchbyIdFromSystem"); - QContactId idForSystemStorageContact = saveTestContact(cm, nameForSystemStorageContact, QContactAbstractRequest::SystemStorage); - - QList<QContactId> ids; - ids << idForUserdataStorageContact << idForSystemStorageContact; - // Check that fetch from both storages at the same time gives the right contacts back to us. - QContactManager::Error error = QContactManager::NoError; - QList<QContact> contacts = fetchTestContactsById(cm, ids, error); - QCOMPARE(error, QContactManager::NoError); - QCOMPARE(contacts.size(), 2); - - int contactsUserdataFound = 0; - int contactsSystemFound = 0; - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>().firstName() == nameForUserdataStorageContact) { - contactsUserdataFound++; - QCOMPARE(curr.id(), idForUserdataStorageContact); - } - if (curr.detail<QContactName>().firstName() == nameForSystemStorageContact) { - contactsSystemFound++; - QCOMPARE(curr.id(), idForSystemStorageContact); - } - } - - QCOMPARE(contactsUserdataFound, 1); - QCOMPARE(contactsSystemFound, 1); -} - -void tst_QContactJsondbEngine::testErrorsOnFetchFromWrongStorage() -{ - // Save a test contact to system storage and fetch by Id from default and user storages. - QContactManager cm; - QString name("FetchError"); - QContactId originalId = saveTestContact(cm, name, QContactAbstractRequest::SystemStorage); - QContact contact; - QCOMPARE(fetchTestContactByIdFilter(cm, originalId, contact), QContactManager::DoesNotExistError); - QCOMPARE(fetchTestContactByIdFilter(cm, originalId, contact, QContactAbstractRequest::UserDataStorage), QContactManager::DoesNotExistError); - - // Save a test contact to default storage and fetch from system storage. - originalId = saveTestContact(cm, name); - QCOMPARE(fetchTestContactByIdFilter(cm, originalId, contact, QContactAbstractRequest::SystemStorage), QContactManager::DoesNotExistError); - - // Save a test contact to user storage and fetch from system storage. - originalId = saveTestContact(cm, name, QContactAbstractRequest::UserDataStorage); - QCOMPARE(fetchTestContactByIdFilter(cm, originalId, contact, QContactAbstractRequest::SystemStorage), QContactManager::DoesNotExistError); -} - -void tst_QContactJsondbEngine::testFetchWithIdsFromTwoStoragesInIdFilter() -{ - // Save two test contacts to both user and system storages and fetch by Id one from both of them. - QContactManager cm; - QString name("FetchErrorMultipleIds"); - QContactId contactIdDefault = saveTestContact(cm, name); - contactIdDefault = saveTestContact(cm, name); - QContactId contactIdSystem = saveTestContact(cm, name, QContactAbstractRequest::SystemStorage); - contactIdSystem = saveTestContact(cm, name, QContactAbstractRequest::SystemStorage); - - QList<QContactId> ids; - ids << contactIdDefault << contactIdSystem; - QList<QContact> contacts; - - // Check we get only the right contact from default storage (user storage) when no storage defined. - QCOMPARE(fetchTestContactsByIdFilter(cm, ids, contacts), QContactManager::NoError); - QCOMPARE(contacts.size(), 1); - QCOMPARE(contacts.first().id(), contactIdDefault); - QCOMPARE(contacts.first().detail<QContactName>().firstName(), name); - - // Check we get only the right contact from system storage when explicitely defining the storage. - QCOMPARE(fetchTestContactsByIdFilter(cm, ids, contacts, QContactAbstractRequest::SystemStorage), QContactManager::NoError); - QCOMPARE(contacts.size(), 1); - QCOMPARE(contacts.first().id(), contactIdSystem); - QCOMPARE(contacts.first().detail<QContactName>().firstName(), name); -} - -void tst_QContactJsondbEngine::testFetchErrorWithIdsFromWrongStorageInIdFilter() -{ - // Save two test contacts to both user and system storages. - QContactManager cm; - QString name("FetchErrorMultipleIds"); - QContactId contactIdDefault = saveTestContact(cm, name); - contactIdDefault = saveTestContact(cm, name); - QContactId contactIdSystem = saveTestContact(cm, name, QContactAbstractRequest::SystemStorage); - contactIdSystem = saveTestContact(cm, name, QContactAbstractRequest::SystemStorage); - - // Check fetch error when none of the ids in filter match with the default storage location. - QList<QContactId> idsNotInDefaultStorage; - idsNotInDefaultStorage << contactIdSystem << contactIdSystem; - QList<QContact> contacts; - QCOMPARE(fetchTestContactsByIdFilter(cm, idsNotInDefaultStorage, contacts), QContactManager::DoesNotExistError); - QCOMPARE(contacts.size(), 0); - - // Check fetch error when none of the ids in filter match with the system storage location. - QList<QContactId> idsNotInSystemStorage; - idsNotInSystemStorage << contactIdDefault << contactIdDefault; - QCOMPARE(fetchTestContactsByIdFilter(cm, idsNotInSystemStorage, contacts, QContactAbstractRequest::SystemStorage), QContactManager::DoesNotExistError); - QCOMPARE(contacts.size(), 0); -} - -void tst_QContactJsondbEngine::testRemoveFromDefaultStorage() -{ - // Get original count of contacts in the defaul and system storages. - QContactManager cm; - int originalCount = cm.contactIds().size(); - QList<QContact> contacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage); - int originalCountInSystemStorage = contacts.size(); - - // Save and remove test contact to default storage and check it is not there. - QString name("RemoveFromDefault"); - QContactId id = saveTestContact(cm, name); - QCOMPARE(removeTestContact(cm, id), QContactManager::NoError); - - // Check the contact is removed from the default storage. - contacts = fetchTestContacts(cm); - QCOMPARE(contacts.size(), originalCount); - foreach (QContact curr, contacts) { - QVERIFY(curr.detail<QContactName>().firstName() != name); - QVERIFY(curr.id() != id); - } - - // Check remove did not affect to amount of contacts in the system storage. - contacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage); - QCOMPARE(contacts.size(), originalCountInSystemStorage); - - // Check re-remove fails with proper error code. - QCOMPARE(removeTestContact(cm, id), QContactManager::DoesNotExistError); -} - -void tst_QContactJsondbEngine::testRemoveFromUserStorage() -{ - // Get original count of contacts in the defaul and system storages. - QContactManager cm; - int originalCount = cm.contactIds().size(); - QList<QContact> contacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage); - int originalCountInSystemStorage = contacts.size(); - - // Save a test contact to user data storage and then remove it. - QString name("RemoveFromUser"); - QContactId id = saveTestContact(cm, name, QContactAbstractRequest::UserDataStorage); - QCOMPARE(removeTestContact(cm, id), QContactManager::NoError); - - // Check the contact is removed from the user data storage. - contacts = fetchTestContacts(cm, QContactAbstractRequest::UserDataStorage); - QCOMPARE(contacts.size(), originalCount); - foreach (QContact curr, contacts) { - QVERIFY(curr.detail<QContactName>().firstName() != name); - QVERIFY(curr.id() != id); - } - - // Check remove did not affect to amount of contacts in the system storage. - contacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage); - QCOMPARE(contacts.size(), originalCountInSystemStorage); - - // Check re-remove fails with proper error code. - QCOMPARE(removeTestContact(cm, id), QContactManager::DoesNotExistError); -} - -void tst_QContactJsondbEngine::testRemoveFromSystemStorage() -{ - // Get original count of contacts in the defaul and system storages. - QContactManager cm; - int originalCount = cm.contactIds().size(); - - // Save test contact to system storage. - QString name("RemoveFromSystem"); - QContactId id = saveTestContact(cm, name, QContactAbstractRequest::SystemStorage); - - // Check that remove from system storage succeeds. - QCOMPARE(removeTestContact(cm, id), QContactManager::NoError); - QList<QContact> contacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage); - QCOMPARE(contacts.size(), 0); - - // Check remove did not affect to amount of contacts in the user data storage. - contacts = fetchTestContacts(cm, QContactAbstractRequest::UserDataStorage); - QCOMPARE(contacts.size(), originalCount); - - // Check re-remove fails with proper error code. - QCOMPARE(removeTestContact(cm, id), QContactManager::DoesNotExistError); -} - -void tst_QContactJsondbEngine::testRemoveFromUserAndSystemStorages() -{ - // Get original count of contacts in the defaul and system storages. - QContactManager cm; - int originalCount = cm.contactIds().size(); - - // Save test contact to default and system storages. - QString nameForDefaultStorageContact("RemoveFromDefault"); - QContactId idForDefaultStorageContact = saveTestContact(cm, nameForDefaultStorageContact); - - QString nameForSystemStorageContact("RemoveFromSystem"); - QContactId idForSystemStorageContact = saveTestContact(cm, nameForSystemStorageContact, QContactAbstractRequest::SystemStorage); - - // Check that remove from system storage succeeds. - QCOMPARE(removeTestContact(cm, idForSystemStorageContact), QContactManager::NoError); - QList<QContact> contacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage); - QCOMPARE(contacts.size(), 0); - - // Check that fetch from default storage still has the right number of contacts and a test contact. - contacts = fetchTestContacts(cm); - QCOMPARE(contacts.size(), originalCount+1); - int contactsFound = 0; - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>().firstName() == nameForDefaultStorageContact) contactsFound++; - } - QCOMPARE(contactsFound, 1); - - // Check remove from user data storage succeeds. - QCOMPARE(removeTestContact(cm, idForDefaultStorageContact), QContactManager::NoError); - contacts = fetchTestContacts(cm); - QCOMPARE(contacts.size(), originalCount); - contactsFound = 0; - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>().firstName() == nameForDefaultStorageContact) - contactsFound++; - } - QCOMPARE(contactsFound, 0); - - // Check re-remove for both contacts fails with proper error codes. - QCOMPARE(removeTestContact(cm, idForSystemStorageContact), QContactManager::DoesNotExistError); - QCOMPARE(removeTestContact(cm, idForDefaultStorageContact), QContactManager::DoesNotExistError); -} - -void tst_QContactJsondbEngine::testUpdateToUserDataStorage() -{ - // Get original count of contacts in the defaul and system storages. - QContactManager cm; - int originalCount = cm.contactIds().size(); - - // Save a test contact to user data storage and fetch it back. - QString name("UpdateToUser"); - QContactId originalId = saveTestContact(cm, name, QContactAbstractRequest::UserDataStorage); - QContact contact; - QCOMPARE(fetchTestContactByIdFilter(cm, originalId, contact), QContactManager::NoError); - QCOMPARE(contact.id(), originalId); - QCOMPARE(contact.detail<QContactName>().firstName(), name); - - // Update contact with new lastname specific for this test case. - QString updatedLastName("UpdatedToUserData"); - QContactName nameDetail = contact.detail(QContactDetail::TypeName); - nameDetail.setLastName(updatedLastName); - contact.saveDetail(&nameDetail); - QContactId idFromUpdate; - QVERIFY(updateTestContact(cm, contact, idFromUpdate) == QContactManager::NoError); - QCOMPARE (idFromUpdate, originalId); - - // Fetch with id filter and verify contact data. - QContact fetchedContact; - QCOMPARE(fetchTestContactByIdFilter(cm, originalId, fetchedContact), QContactManager::NoError); - QCOMPARE(fetchedContact.id(), originalId); - QCOMPARE(fetchedContact.detail<QContactName>().firstName(), name); - QCOMPARE(fetchedContact.detail<QContactName>().lastName(), updatedLastName); - - // Verify the default storage contacts amount. - QList<QContact> defaultStorageContacts = fetchTestContacts(cm); - QCOMPARE(defaultStorageContacts.size(), originalCount + 1); - - // Verify the user storage contacts amount. - QList<QContact> userdataContacts = fetchTestContacts(cm, QContactAbstractRequest::UserDataStorage); - QCOMPARE(userdataContacts.size(), originalCount +1); - - // Verify the system storage is not affected (it should be clean by test init). - QList<QContact> systemStorageContacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage); - QCOMPARE(systemStorageContacts.size(), 0); -} - -void tst_QContactJsondbEngine::testUpdateToSystemDataStorage() -{ - // Get original count of contacts in the defaul and system storages. - QContactManager cm; - int originalCount = cm.contactIds().size(); - - // Save and fetch test contact to user data storage. - QString name("UpdateToSystem"); - QContactId originalId = saveTestContact(cm, name, QContactAbstractRequest::SystemStorage); - QContact contact; - QCOMPARE(fetchTestContactByIdFilter(cm, originalId, contact, QContactAbstractRequest::SystemStorage), QContactManager::NoError); - QCOMPARE(contact.id(), originalId); - QCOMPARE(contact.detail<QContactName>().firstName(), name); - - // Update contact with new lastname specific for this test case. - QString updatedLastName("UpdatedToSystemRestricted"); - QContactName nameDetail = contact.detail(QContactDetail::TypeName); - nameDetail.setLastName(updatedLastName); - contact.saveDetail(&nameDetail); - QContactId idFromUpdate; - QVERIFY(updateTestContact(cm, contact, idFromUpdate) == QContactManager::NoError); - QCOMPARE (idFromUpdate, originalId); - - // Fetch with id filter and verify contact data. - QContact fetchedContact; - QCOMPARE(fetchTestContactByIdFilter(cm, originalId, fetchedContact, QContactAbstractRequest::SystemStorage), QContactManager::NoError); - QCOMPARE(fetchedContact.id(), originalId); - QCOMPARE(fetchedContact.detail<QContactName>().firstName(), name); - QCOMPARE(fetchedContact.detail<QContactName>().lastName(), updatedLastName); - - // Verify the cointact is in the system storage. - QList<QContact> systemStorageContacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage); - QCOMPARE(systemStorageContacts.size(), 1); - - // Verify the default storage contacts amount. - QList<QContact> defaultStorageContacts = fetchTestContacts(cm); - QCOMPARE(defaultStorageContacts.size(), originalCount); - - // Verify the user storage contacts amount. - QList<QContact> userdataContacts = fetchTestContacts(cm, QContactAbstractRequest::UserDataStorage); - QCOMPARE(userdataContacts.size(), originalCount); -} - -void tst_QContactJsondbEngine::testWrongUpdateToDefaultStorage() -{ - // Get original count of contacts in the defaul and system storages. - QContactManager cm; - int originalCount = cm.contactIds().size(); - - // Save and fetch test contact to system storage. - QString name("WrongUpdateToDefault"); - QContactId originalId = saveTestContact(cm, name, QContactAbstractRequest::SystemStorage); - QContact contact; - QCOMPARE(fetchTestContactByIdFilter(cm, originalId, contact, QContactAbstractRequest::SystemStorage), QContactManager::NoError); - QCOMPARE(contact.id(), originalId); - QCOMPARE(contact.detail<QContactName>().firstName(), name); - - // Try to update contact to "wrong" storage location. - // By documentation it should go to it's home storage instead of defined one. - QString updatedLastName("UpdateToWrongStorageGoestoHomeStorage"); - QContactName nameDetail = contact.detail(QContactDetail::TypeName); - nameDetail.setLastName(updatedLastName); - contact.saveDetail(&nameDetail); - QContactId idFromUpdate; - QCOMPARE(updateTestContact(cm, contact, idFromUpdate), QContactManager::NoError); - QCOMPARE (idFromUpdate, originalId); - - // Fetch with id filter from default to verify proper error code. - QContact fetchedContact; - QCOMPARE(fetchTestContactByIdFilter(cm, originalId, fetchedContact), QContactManager::DoesNotExistError); - - // Verify the default storage contacts amount did not change. - QList<QContact> defaultStorageContacts = fetchTestContacts(cm); - QCOMPARE(defaultStorageContacts.size(), originalCount); - - // Verify the user storage contacts amount did not change. - QList<QContact> userdataContacts = fetchTestContacts(cm, QContactAbstractRequest::UserDataStorage); - QCOMPARE(userdataContacts.size(), originalCount); - - // Verify the system storage, there should be only the updated test contact. - QList<QContact> systemStorageContacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage); - QCOMPARE(systemStorageContacts.size(), 1); - QCOMPARE(systemStorageContacts.first().detail<QContactName>().firstName(), name); - QCOMPARE(systemStorageContacts.first().detail<QContactName>().lastName(), updatedLastName); -} - -void tst_QContactJsondbEngine::testWrongUpdateToSystemStorage() -{ - // Get original count of contacts in the defaul and system storages. - QContactManager cm; - int originalCount = cm.contactIds().size(); - - // Save and fetch test contact to default storage. - QString name("WrongUpdateToSystem"); - QContactId originalId = saveTestContact(cm, name); - QContact contact; - QCOMPARE(fetchTestContactByIdFilter(cm, originalId, contact), QContactManager::NoError); - QCOMPARE(contact.id(), originalId); - QCOMPARE(contact.detail<QContactName>().firstName(), name); - - // Try to update contact to "wrong" storage location. - // By documentation it should go to 'home' storage instead. - QString updatedLastName("UpdateToWrongStorageGoesToHomeStorage"); - QContactName nameDetail = contact.detail(QContactDetail::TypeName); - nameDetail.setLastName(updatedLastName); - contact.saveDetail(&nameDetail); - QContactId idFromUpdate; - QCOMPARE(updateTestContact(cm, contact, idFromUpdate, QContactAbstractRequest::SystemStorage), QContactManager::NoError); - QCOMPARE (idFromUpdate, originalId); - - // Fetch with id filter frp, system storage to verify the correct error code. - QContact fetchedContact; - QCOMPARE(fetchTestContactByIdFilter(cm, originalId, fetchedContact, QContactAbstractRequest::SystemStorage), QContactManager::DoesNotExistError); - - // Verify the default storage contacts amount and updated test contact there. - QList<QContact> defaultStorageContacts = fetchTestContacts(cm); - QCOMPARE(defaultStorageContacts.size(), originalCount + 1); - bool contactFound = false; - foreach (QContact curr, defaultStorageContacts) { - if (curr.detail<QContactName>().firstName() == name) { - contactFound = true; - QCOMPARE(curr.detail<QContactName>().lastName(), updatedLastName); - } - } - QVERIFY(contactFound == true); - - // Verify the user storage contacts amount. - QList<QContact> userdataContacts = fetchTestContacts(cm, QContactAbstractRequest::UserDataStorage); - QCOMPARE(userdataContacts.size(), originalCount +1); - - // Verify the system storage is not affected (it should be clean by test init). - QList<QContact> systemStorageContacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage); - QCOMPARE(systemStorageContacts.size(), 0); -} - -void tst_QContactJsondbEngine::testIdFetchRequestFromUserAndSystemStorages() -{ - // Get original count of contacts in the defaul and system storages. - QContactManager cm; - int originalCount = cm.contactIds().size(); - QList<QContact> contacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage); - int originalCountInSystemStorage = contacts.size(); - - // Save a test contact to both user and system storage. - QString name("FetchByIdTest"); - QContactId contactIdDefault = saveTestContact(cm, name); - QContactId contactIdSystem = saveTestContact(cm, name, QContactAbstractRequest::SystemStorage); - - // Fetch ids using id fetch request. - QContactIdFetchRequest idFetchRequest; - idFetchRequest.setManager(&cm); - idFetchRequest.setStorageLocations(QContactAbstractRequest::UserDataStorage | QContactAbstractRequest::SystemStorage); - idFetchRequest.start(); - idFetchRequest.waitForFinished(); - - QCOMPARE(idFetchRequest.error(), QContactManager::NoError); - - // Check we get the right ids. - QCOMPARE(idFetchRequest.ids().size(), originalCount + originalCountInSystemStorage + 2); - bool contactIdDefaultFound = false; - bool contactIdSystemFound = false; - foreach (QContactId id, idFetchRequest.ids()) { - if (id == contactIdDefault) contactIdDefaultFound = true; - if (id == contactIdSystem) contactIdSystemFound = true; - } - QVERIFY(contactIdDefaultFound); - QVERIFY(contactIdSystemFound); -} - -void tst_QContactJsondbEngine::testSynchronousSaveAndFetchToDefaultStorage() -{ - // Get original count of contacts in the defaul and system storages. - QContactManager cm; - int originalCount = cm.contactIds().size(); - - // Save two test contacts to default partition. - QContact testContact; - QContactName nameDetail; - nameDetail.setFirstName("Test Contact 1"); - testContact.saveDetail(&nameDetail); - QList<QContact> saveList; - saveList << testContact; - QContact testContact2; - QContactName nameDetail2; - nameDetail2.setFirstName("Test Contact 2"); - testContact2.saveDetail(&nameDetail2); - saveList << testContact2; - - bool returnValue = cm.saveContacts(&saveList); - QVERIFY(returnValue == true); - QCOMPARE (cm.contactIds().size(), originalCount+2); - - // Fetch and check contacts from the default partition. - QList<QContactId> ids = cm.contactIds(); - QList<QContact> contacts = cm.contacts(ids); - QCOMPARE(contacts.size(), originalCount+2); - int contactsWithTest1 = 0; - int contactsWithTest2 = 0; - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>() == nameDetail) { - contactsWithTest1++; - QCOMPARE(curr.id(), saveList.at(0).id()); - } - if (curr.detail<QContactName>() == nameDetail2) { - contactsWithTest2++; - QCOMPARE(curr.id(), saveList.at(1).id()); - } - } - QCOMPARE(contactsWithTest1, 1); - QCOMPARE(contactsWithTest2, 1); - - // Fetch contacts from userData storage explicitely and check they are - // there as the userData storage should be the default storage. - contacts = fetchTestContacts(cm, QContactAbstractRequest::UserDataStorage); - QCOMPARE(contacts.size(), originalCount+2); - contactsWithTest1 = 0; - contactsWithTest2 = 0; - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>() == nameDetail) { - contactsWithTest1++; - QCOMPARE(curr.id(), saveList.at(0).id()); - } - if (curr.detail<QContactName>() == nameDetail2) { - contactsWithTest2++; - QCOMPARE(curr.id(), saveList.at(1).id()); - } - } - QCOMPARE(contactsWithTest1, 1); - QCOMPARE(contactsWithTest2, 1); - - // Fetch contacts from the system storage to verify new contact is not available - // there. The storage should be clean by test init. - contacts = fetchTestContacts(cm, QContactAbstractRequest::SystemStorage); - QCOMPARE(contacts.size(), 0); -} - -void tst_QContactJsondbEngine::testSelfContactId() { - qDebug() << "NOTE: THE IDENTIFICATION FIELD DOES NOT EXIST YET IN JSON SCHEMA, just returns \"not found\""; - QContactManager myContactManager; - QContactId myId; - myId = myContactManager.selfContactId(); - qDebug() << "MyId is:" << myId; -} - -void tst_QContactJsondbEngine::testContactIds() { - QContactManager myContactManager; - QContactFilter filter; - QList<QContactSortOrder> sortOrders; - QList<QContactId> resultContactIds = myContactManager.contactIds(filter, sortOrders); - - QList<QContact> contacts = myContactManager.contacts(filter, sortOrders); // used as reference. Not possible to use a table here because the IDs change every time the test is triggered... - QList<QContactId> referenceContactIds; - foreach (QContact contact, contacts) { - referenceContactIds.append(contact.id()); - } - QCOMPARE(resultContactIds.size(), referenceContactIds.size()); - for (int i = 0; i < resultContactIds.size(); i++) { - QVERIFY(resultContactIds.at(i) == referenceContactIds.at(i)); - } -} - -void tst_QContactJsondbEngine::testContacts() { - QContactManager cm; - - // "all contacts" retrieval - QContactFilter filter; - QList<QContactSortOrder> sortOrders; - QList<QContact> contacts = cm.contacts(filter, sortOrders); - QCOMPARE(contacts.size(), 5); - - QFETCH(QString, expectedContact1FirstName); - QFETCH(QString, expectedContact1LastName); - QFETCH(QString, expectedContact2FirstName); - QFETCH(QString, expectedContact2LastName); - QFETCH(QString, expectedContact3FirstName); - QFETCH(QString, expectedContact3LastName); - QFETCH(QString, expectedContact4FirstName); - QFETCH(QString, expectedContact4LastName); - QFETCH(QString, expectedContact5FirstName); - QFETCH(QString, expectedContact5LastName); - QList<QString> expectedContacts; - expectedContacts << expectedContact1FirstName << expectedContact1LastName << expectedContact2FirstName << expectedContact2LastName << expectedContact3FirstName << expectedContact3LastName << expectedContact4FirstName << expectedContact4LastName << expectedContact5FirstName << expectedContact5LastName; - QVERIFY(expectedContacts.size() == 10); - for (int i = 0; i < contacts.size(); i++) { - bool contactFound = false; - QString firstNameString = contacts.at(i).detail<QContactName>().firstName(); - QString lastNameString = contacts.at(i).detail<QContactName>().lastName(); - for (int j = 0; j < expectedContacts.size(); j++) { - if ( (firstNameString == expectedContacts.at(j)) && (lastNameString == expectedContacts.at(j+1)) ) contactFound=true; - } - QCOMPARE(contactFound, true); - } -} - -void tst_QContactJsondbEngine::testContacts_data() { - QTest::addColumn<QString>("expectedContact1FirstName"); - QTest::addColumn<QString>("expectedContact1LastName"); - QTest::addColumn<QString>("expectedContact2FirstName"); - QTest::addColumn<QString>("expectedContact2LastName"); - QTest::addColumn<QString>("expectedContact3FirstName"); - QTest::addColumn<QString>("expectedContact3LastName"); - QTest::addColumn<QString>("expectedContact4FirstName"); - QTest::addColumn<QString>("expectedContact4LastName"); - QTest::addColumn<QString>("expectedContact5FirstName"); - QTest::addColumn<QString>("expectedContact5LastName"); - { - QTest::newRow("expectedContactsNames") << "Harry" << "Baker" << "Paul" << "Thomson" << "Julie" << "King" << "Angelina" << "Row" << "Natalie" << "Watson"; - } -} - -void tst_QContactJsondbEngine::testContact() { - QContactManager cm; - - // contact retrieval - QContactFilter filter; - QList<QContactSortOrder> sortOrders; - QList<QContactId> resultContactIds = cm.contactIds(filter, sortOrders); - QVERIFY(resultContactIds.size() > 0); - QContactId id = resultContactIds.at(1); // Just a random ID picked - QContact contact = cm.contact(id); - QVERIFY(id == contact.id()); - - QFETCH(QString, expectedContact1FirstName); - QFETCH(QString, expectedContact1LastName); - QFETCH(QString, expectedContact2FirstName); - QFETCH(QString, expectedContact2LastName); - QFETCH(QString, expectedContact3FirstName); - QFETCH(QString, expectedContact3LastName); - QFETCH(QString, expectedContact4FirstName); - QFETCH(QString, expectedContact4LastName); - QFETCH(QString, expectedContact5FirstName); - QFETCH(QString, expectedContact5LastName); - QList<QString> expectedContacts; - expectedContacts << expectedContact1FirstName << expectedContact1LastName << expectedContact2FirstName << expectedContact2LastName << expectedContact3FirstName << expectedContact3LastName << expectedContact4FirstName << expectedContact4LastName << expectedContact5FirstName << expectedContact5LastName; - QVERIFY(expectedContacts.size() == 10); - bool contactFound = false; - QString firstNameString = contact.detail<QContactName>().firstName(); - QString lastNameString = contact.detail<QContactName>().lastName(); - for (int j = 0; j < expectedContacts.size(); j++) { - if ( (firstNameString == expectedContacts.at(j)) && (lastNameString == expectedContacts.at(j+1)) ) contactFound=true; - } - QCOMPARE(contactFound, true); -} - -void tst_QContactJsondbEngine::testContact_data() { - QTest::addColumn<QString>("expectedContact1FirstName"); - QTest::addColumn<QString>("expectedContact1LastName"); - QTest::addColumn<QString>("expectedContact2FirstName"); - QTest::addColumn<QString>("expectedContact2LastName"); - QTest::addColumn<QString>("expectedContact3FirstName"); - QTest::addColumn<QString>("expectedContact3LastName"); - QTest::addColumn<QString>("expectedContact4FirstName"); - QTest::addColumn<QString>("expectedContact4LastName"); - QTest::addColumn<QString>("expectedContact5FirstName"); - QTest::addColumn<QString>("expectedContact5LastName"); - { - QTest::newRow("expectedContactsNames") << "Harry" << "Baker" << "Paul" << "Thomson" << "Julie" << "King" << "Angelina" << "Row" << "Natalie" << "Watson"; - } -} - -void tst_QContactJsondbEngine::testContactUpdate() { - - // Fetch existing contacts. - QContactManager cm; - QContactIdFilter idFilter; - QList<QContactSortOrder> sortOrders; - QList<QContact> contacts = cm.contacts(sortOrders); // fetch all contacts - QVERIFY(contacts.size() > 0); - - // Take first of them as test contact for update test. - QContact testContact = contacts[0]; - idFilter.add(testContact.id()); - QContactFetchRequest fetchRequest; - fetchRequest.setFilter(idFilter); - - // Convert QContact to JsonDb contact and insert extra fields to json contact. - QJsonObject jsonContact; - QContactJsonDbConverter jsonDbConverter; - int extraFieldInContact = 3; - int extraFieldInContactDetails = 5; - int extraFieldInContactEmails = 8; - if (jsonDbConverter.toJsonContact(&jsonContact, testContact)) { - jsonContact.insert("extra3", extraFieldInContact); - - QJsonObject embeddedDetails; - embeddedDetails["extra5"] = extraFieldInContactDetails; - jsonContact.insert("details", embeddedDetails); - - QJsonObject embeddedEmail; - embeddedEmail["extra8"] = extraFieldInContactEmails; - jsonContact.insert("emails", embeddedEmail); - } - // Save test contact with extra fields directly to the jsondb. - QVariantMap jsonResponse = m_dbClient->update(jsonContact, QContactJsonDbStr::userDataPartition()).first().toVariantMap(); - - // Update the test contact through the QContacts API with some details. - QContactName nameDetail = testContact.detail<QContactName>(); - nameDetail.setFirstName("Kary"); - nameDetail.setLastName("Krant"); - testContact.saveDetail(&nameDetail); - - QContactEmailAddress emailDetail; - testContact.removeDetail(&emailDetail); - emailDetail.setEmailAddress("Kary.Krant@ovi.com"); - emailDetail.setContexts(QContactDetail::ContextHome); - testContact.saveDetail(&emailDetail); - QContactPhoneNumber phoneNumberDetail; - testContact.removeDetail(&phoneNumberDetail); - - QList<int> currSubtype; - currSubtype << QContactPhoneNumber::SubTypeMobile; - phoneNumberDetail.setSubTypes(currSubtype); - phoneNumberDetail.setNumber("+358507654322"); - testContact.saveDetail(&phoneNumberDetail); - cm.saveContact(&testContact); - - // TODO: Check the updated fields are properly there. - QList<QContact> contactsNow = cm.contacts(idFilter, sortOrders); - foreach (QContact cntc, contactsNow ) { - if (cntc.id() == testContact.id()) { - } - } - - // Fetch directly from jsondb the test contact data. - QString finalQuery; - QVERIFY(jsonDbConverter.queryFromRequest(&fetchRequest, finalQuery)); - QVariantMap finalJsonContact = m_dbClient->query(finalQuery, QContactJsonDbStr::userDataPartition()).first().toVariantMap(); - QVERIFY(!finalJsonContact.isEmpty()); - - QVariantMap embeddedDetailsMap = finalJsonContact["details"].value<QVariantMap>(); - QVariantMap embeddedEmailMap = finalJsonContact["emails"].value<QVariantMap>(); - - // Check that update did not change extra fields in contact object. - QCOMPARE(finalJsonContact.value("extra3").toInt(),extraFieldInContact); - // Check that update did not change extra fields in contact embededed details object. - QCOMPARE(embeddedDetailsMap.value("extra5").toInt(),extraFieldInContactDetails); - // We do not preserve extra fields for other embedded objects like emails. - QCOMPARE(embeddedEmailMap.value("extra8"), QVariant()); -} - - -void tst_QContactJsondbEngine::testExtendedDetailsFromJsonDb() { - - // Fetch existing contacts. - QContactManager cm; - QContactIdFilter idFilter; - QList<QContactSortOrder> sortOrders; - QList<QContact> contacts = cm.contacts(sortOrders); // fetch all contacts - QVERIFY(contacts.size() > 0); - - // Take first of them as test contact. - QContact testContact = contacts[0]; - idFilter.add(testContact.id()); - - // Convert QContact to JsonDb contact and insert unknown properties to json contact. - QJsonObject jsonContact; - QContactJsonDbConverter jsonDbConverter; - int extraFieldInContactDetails = 5; - - QVERIFY(jsonDbConverter.toJsonContact(&jsonContact, testContact)); - jsonContact.insert("simpleStringDetail", QJsonValue::fromVariant("Simple string as detail data.")); - - QVariantMap variantMap; - variantMap.insert("MapItemInt", 1); - variantMap.insert("MapItemQString", "QStringData"); - variantMap.insert("MapItemQVariant", QVariant( QString("QStringInQVariant"))); - variantMap.insert("MapItemQVariantList", QVariantList() << QString("QStringInVariantList") << 5 ); - - QJsonObject jsonData; - jsonData.insert("QStringItem", QJsonValue::fromVariant("Content for QStringItem.")); - jsonData.insert("MapInMap", QJsonObject::fromVariantMap(variantMap)); - jsonContact.insert("complexVariantMapDetail", jsonData); - jsonContact.insert("anotherSimilarComplexVariantMapDetail", jsonData); - - QJsonObject embeddedDetails; - embeddedDetails["extra5"] = extraFieldInContactDetails; - jsonContact.insert("details", embeddedDetails); - - // Save test contact with unknown properties directly to the jsondb. - QVariantMap jsonResponse = m_dbClient->update(jsonContact,QContactJsonDbStr::userDataPartition()).first().toVariantMap(); - - // Check that the unknown properties come up as extended details. - QList<QContact> contactsNow = cm.contacts(idFilter, sortOrders); - foreach (QContact contact, contactsNow ) { - if (contact.id() == testContact.id()) { - QList<QContactExtendedDetail> extendedDetails = contact.details<QContactExtendedDetail>(); - QCOMPARE(extendedDetails.size(), 3); - for (int i = 0; i < extendedDetails.size(); ++i) { - if (extendedDetails.at(i).name() == "simpleStringDetail") { - QCOMPARE(extendedDetails[i].data().toString(), QString("Simple string as detail data.")); - } - if (extendedDetails.at(i).name() == "complexVariantMapDetail") { - QVariantMap extendedDetailItems = extendedDetails[i].data().toMap(); - QCOMPARE(extendedDetailItems.value("QStringItem").toString(), QString("Content for QStringItem.")); - QVariantMap returnMap = extendedDetailItems.value("MapInMap").toMap(); - QCOMPARE(returnMap.value("MapItemInt").toInt(), 1); - QCOMPARE(returnMap.value("MapItemQString").toString(), QString("QStringData")); - QCOMPARE(returnMap.value("MapItemQVariant").toString(), QString("QStringInQVariant")); - QCOMPARE(returnMap.value("MapItemQVariantList").toList().at(0).toString(), QString("QStringInVariantList")); - QCOMPARE(returnMap.value("MapItemQVariantList").toList().at(1).toInt(), 5); - } - if (extendedDetails.at(i).name() == "anotherSimilarComplexVariantMapDetail") { - QVariantMap extendedDetailItems = extendedDetails[i].data().toMap(); - QCOMPARE(extendedDetailItems.value("QStringItem").toString(), QString("Content for QStringItem.")); - QVariantMap returnMap = extendedDetailItems.value("MapInMap").toMap(); - QCOMPARE(returnMap.value("MapItemInt").toInt(), 1); - QCOMPARE(returnMap.value("MapItemQString").toString(), QString("QStringData")); - QCOMPARE(returnMap.value("MapItemQVariant").toString(), QString("QStringInQVariant")); - QCOMPARE(returnMap.value("MapItemQVariantList").toList().at(0).toString(), QString("QStringInVariantList")); - QCOMPARE(returnMap.value("MapItemQVariantList").toList().at(1).toInt(), 5); - } - } - } - } -} - -void tst_QContactJsondbEngine::testExtendedDetailsToJsonDb() { - - // Fetch existing contacts. - QContactManager cm; - QContactIdFilter idFilter; - QList<QContactSortOrder> sortOrders; - QList<QContact> contacts = cm.contacts(sortOrders); // fetch all contacts - QVERIFY(contacts.size() > 0); - - // Take first of them as test contact for update test. - QContact testContact = contacts[0]; - idFilter.add(testContact.id()); - QContactFetchRequest fetchRequest; - fetchRequest.setFilter(idFilter); - - // Add simple string as extended detail. - QContactExtendedDetail extendedDetail; - extendedDetail.setName("extendedDetailQString"); - extendedDetail.setData(QString("Simple QString as extended detail.")); - testContact.saveDetail(&extendedDetail); - - // Add QVariantList as extended detail. - QContactExtendedDetail variantListDetail; - variantListDetail.setName("extendedDetailQVariantList"); - variantListDetail.setData(QVariantList() << QString("QString in the QVariantlist detail.") - << QVariant(1) - << QString("Another QString in the QVariantlist detail.") - << 2); - testContact.saveDetail(&variantListDetail); - - // Add exteded details with a complex variantmap data in to test contact and save it. - QContactExtendedDetail complexExtendedDetail; - complexExtendedDetail.setName("complexExtendedDetail"); - QVariantMap variantMap; - variantMap.insert("mapItemInt", 3); - variantMap.insert("mapItemQString", QString("QString item in QVariantMap")); - variantMap.insert("mapItemVariant", QVariant(QString("QString item as QVariant in QVariantMap"))); - variantMap.insert("mapItemVariantList", QVariantList() - << QString("QString item in QVariantList in QVarianMap") - << QVariant(4) - << QString("Another QString item in QVariantList in QVariantMap")); - complexExtendedDetail.setData(variantMap); - testContact.saveDetail(&complexExtendedDetail); - cm.saveContact(&testContact); - - //Fetch saved test contact data directly from jsondb. - QContactJsonDbConverter jsonDbConverter; - QString finalQuery; - QVERIFY(jsonDbConverter.queryFromRequest(&fetchRequest, finalQuery)); - QVariantMap jsonContact = m_dbClient->query(finalQuery, QContactJsonDbStr::userDataPartition()).first().toVariantMap(); - - // Check simple extended detail got correctly to jsondb. - QCOMPARE(jsonContact["extendedDetailQString"].value<QVariant>().toString(),QString("Simple QString as extended detail.")); - - // Check variantlist exteded details got correctly to jsondb. - QVariantList variantList = jsonContact["extendedDetailQVariantList"].value<QVariant>().toList(); - QCOMPARE(variantList.size(), 4); - QCOMPARE( variantList[0].toString(), QString("QString in the QVariantlist detail.")); - QCOMPARE( variantList[1].toInt(), 1); - QCOMPARE( variantList[2].toString(), QString("Another QString in the QVariantlist detail.")); - QCOMPARE( variantList[3].toInt(),2); - - // Check complex extended detail field got correctly to jsondb. - QVariantMap convertedVariantMap = jsonContact["complexExtendedDetail"].value<QVariant>().toMap(); - QCOMPARE( convertedVariantMap["mapItemInt"].toInt(), 3); - QCOMPARE( convertedVariantMap["mapItemQString"].toString(),QString("QString item in QVariantMap")); - QCOMPARE( convertedVariantMap["mapItemVariant"].toString(),QString("QString item as QVariant in QVariantMap")); - variantList = convertedVariantMap["mapItemVariantList"].toList(); - QCOMPARE(variantList.size(), 3); - QCOMPARE( variantList[0].toString(), QString("QString item in QVariantList in QVarianMap")); - QCOMPARE( variantList[1].toInt(), 4); - QCOMPARE( variantList[2].toString(), QString("Another QString item in QVariantList in QVariantMap")); -} - - -void tst_QContactJsondbEngine::testSaveContact() { - QContactManager cm; - - // save a new contact - int originalCount = cm.contactIds().size(); - QContact testContact; - - QContactName nameDetail; - nameDetail.setFirstName("Test Contact"); - testContact.saveDetail(&nameDetail); - - // testing - QContactFilter filter; - QList<QContactSortOrder> sortOrders; - QList<QContact> contacts = cm.contacts(filter, sortOrders); - bool returnValue = cm.saveContact(&testContact); - QVERIFY(returnValue == true); - - QContactId testContactId = testContact.id(); - QContact expected = cm.contact(testContactId); - - QCOMPARE(cm.contactIds().size(), originalCount + 1); - QCOMPARE(testContact.id(), expected.id()); - QCOMPARE(testContact.detail(QContactName::Type), expected.detail(QContactName::Type)); -} - -void tst_QContactJsondbEngine::testSaveContacts() { - QContactManager cm; - - // save new contacts - int originalCount = cm.contactIds().size(); - QContact testContact; - QContactName nameDetail; - nameDetail.setFirstName("Test Contact 1"); - testContact.saveDetail(&nameDetail); - QList<QContact> saveList; - saveList << testContact; - - QContact testContact2; - QContactName nameDetail2; - nameDetail2.setFirstName("Test Contact 2"); - testContact2.saveDetail(&nameDetail2); - saveList << testContact2; - - // dummy contact that will not be added - QContact testContact3; - QContactName nameDetail3; - nameDetail3.setFirstName("Test Contact 3"); - testContact3.saveDetail(&nameDetail3); - - // testing - QContactFilter filter; - QList<QContactSortOrder> sortOrders; - QList<QContact> initialContacts = cm.contacts(filter, sortOrders); - bool returnValue = cm.saveContacts(&saveList); - QVERIFY(returnValue == true); - QList<QContact> contacts = cm.contacts(filter, sortOrders); - - bool contact1Found = false; - bool contact2Found = false; - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>() == nameDetail) contact1Found=true; - if (curr.detail<QContactName>() == nameDetail2) contact2Found=true; - } - QVERIFY(contact1Found == true); - QVERIFY(contact2Found == true); - QCOMPARE(cm.contactIds().size(), originalCount + 2); -} - -void tst_QContactJsondbEngine::testContactDetailFilter() { - QContactManager myContactManager; - QList<QContactSortOrder> sortOrders; - - // ------------ MATCH FLAG = CONTAINS ------------ - - // retrieve contacts filtering by first name - QString firstName = " li "; - // This is to test the string sanitation: the filter will use the - // sanitized version of this string, thus: "li" - QContactDetailFilter dfil; - dfil.setDetailType(QContactName::Type, QContactName::FieldFirstName); - dfil.setValue(firstName); - dfil.setMatchFlags(QContactFilter::MatchContains); - QVERIFY(dfil.matchFlags() == QContactFilter::MatchContains); - QList<QContact> contacts = myContactManager.contacts(dfil, sortOrders); - QCOMPARE(contacts.size(), 3); - - QFETCH(QString, expectedContact3FirstName); - QFETCH(QString, expectedContact4FirstName); - QFETCH(QString, expectedContact5FirstName); - QList<QString> expectedContacts; - expectedContacts << expectedContact3FirstName << expectedContact4FirstName << expectedContact5FirstName; - QVERIFY(expectedContacts.size() == 3); - for (int i = 0; i < contacts.size(); i++) { - bool contactFound = false; - QString firstNameString = contacts.at(i).detail<QContactName>().firstName(); - for (int j = 0; j < expectedContacts.size(); j++) { - if (firstNameString == expectedContacts.at(j)) contactFound=true; - } - QCOMPARE(contactFound, true); - } - - // retrieve contacts filtering by Last name - QString lastName = "o"; - dfil.setDetailType(QContactName::Type, QContactName::FieldLastName); - dfil.setValue(lastName); - QVERIFY(dfil.matchFlags() == QContactFilter::MatchContains); - contacts = myContactManager.contacts(dfil, sortOrders); - QVERIFY(contacts.size() == 3); - QFETCH(QString, expectedContact2LastName); - QFETCH(QString, expectedContact4LastName); - QFETCH(QString, expectedContact5LastName); - expectedContacts.clear(); - expectedContacts << expectedContact2LastName << expectedContact4LastName << expectedContact5LastName; - QVERIFY(expectedContacts.size() == 3); - for (int i = 0; i < contacts.size(); i++) { - bool contactFound = false; - QString lastNameString = contacts.at(i).detail<QContactName>().lastName(); - for (int j = 0; j < expectedContacts.size(); j++) { - if (lastNameString == expectedContacts.at(j)) contactFound=true; - } - QCOMPARE(contactFound, true); - } - - // retrieve contacts filtering by phone number - QString phoneNr = " 6543HHHH HHHHHHHH"; - //The number above will be sanitized by jsondb contacts plugin - //Hence, the filter will look for contacts matching the - //sanitized version of phoneNr, i.e., "6543" - dfil.setDetailType(QContactPhoneNumber::Type, QContactPhoneNumber::FieldNumber); - dfil.setValue(phoneNr); - QVERIFY(dfil.matchFlags() == QContactFilter::MatchContains); - contacts = myContactManager.contacts(dfil, sortOrders); - QCOMPARE(contacts.size(), 3); - QFETCH(QString, expectedContact1LastName); // Contacts 2 and 5 were fetched already - expectedContacts.clear(); - expectedContacts << expectedContact1LastName << expectedContact2LastName << expectedContact5LastName; - QVERIFY(expectedContacts.size() == 3); - for (int i = 0; i < contacts.size(); i++) { - bool contactFound = false; - QString lastNameString = contacts.at(i).detail<QContactName>().lastName(); - for (int j = 0; j < expectedContacts.size(); j++) { - if (lastNameString == expectedContacts.at(j)) contactFound=true; - } - QCOMPARE(contactFound, true); - } - - // retrieve contacts filtering by email - QString email = " on "; - // This is to test the string sanitation: the filter will use the - // sanitized version of this string, thus: "on" - dfil.setDetailType(QContactEmailAddress::Type, QContactEmailAddress::FieldEmailAddress); - dfil.setValue(email); - QVERIFY(dfil.matchFlags() == QContactFilter::MatchContains); - contacts = myContactManager.contacts(dfil, sortOrders); - QVERIFY(contacts.size() == 2); - expectedContacts.clear(); - QFETCH(QString, expectedContact2EmailAddress); - QFETCH(QString, expectedContact5EmailAddress); - expectedContacts << expectedContact2EmailAddress << expectedContact5EmailAddress; - QVERIFY(expectedContacts.size() == 2); - for (int i = 0; i < contacts.size(); i++) { - bool contactFound = false; - QString firstNameString = contacts.at(i).detail<QContactName>().firstName(); - QString lastNameString = contacts.at(i).detail<QContactName>().lastName(); - QString emailAddress = "mailto:"; - emailAddress.append(firstNameString + "." + lastNameString + "@ovi.com"); - for (int j = 0; j < expectedContacts.size(); j++) { - if (emailAddress == expectedContacts.at(j)) contactFound=true; - } - QCOMPARE(contactFound, true); - } - - // ------------ MATCH FLAG = MATCH EXACTLY ------------ - - // retrieve contacts filtering by first name - firstName = "Julie"; - dfil.setDetailType(QContactName::Type, QContactName::FieldFirstName); - dfil.setValue(firstName); - dfil.setMatchFlags(QContactFilter::MatchExactly); - QVERIFY(dfil.matchFlags() == QContactFilter::MatchExactly); - contacts = myContactManager.contacts(dfil, sortOrders); - QVERIFY(contacts.size() == 1); - expectedContacts.clear(); - expectedContacts << expectedContact3FirstName; - QVERIFY(expectedContacts.size() == 1); - for (int i = 0; i < contacts.size(); i++) { - bool contactFound = false; - QString firstNameString = contacts.at(i).detail<QContactName>().firstName(); - for (int j = 0; j < expectedContacts.size(); j++) { - if (firstNameString == expectedContacts.at(j)) contactFound=true; - } - QCOMPARE(contactFound, true); - } - - // retrieve contacts filtering by Last name - lastName = "Thomson"; - dfil.setDetailType(QContactName::Type, QContactName::FieldLastName); - dfil.setValue(lastName); - QVERIFY(dfil.matchFlags() == QContactFilter::MatchExactly); - contacts = myContactManager.contacts(dfil, sortOrders); - QVERIFY(contacts.size() == 1); - expectedContacts.clear(); - expectedContacts << expectedContact2LastName; - QVERIFY(expectedContacts.size() == 1); - for (int i = 0; i < contacts.size(); i++) { - bool contactFound = false; - QString lastNameString = contacts.at(i).detail<QContactName>().lastName(); - for (int j = 0; j < expectedContacts.size(); j++) { - if (lastNameString == expectedContacts.at(j)) contactFound=true; - } - QCOMPARE(contactFound, true); - } - - // retrieve contacts filtering by phone number - phoneNr = "+358507654321"; - dfil.setDetailType(QContactPhoneNumber::Type, QContactPhoneNumber::FieldNumber); - dfil.setValue(phoneNr); - QVERIFY(dfil.matchFlags() == QContactFilter::MatchExactly); - contacts = myContactManager.contacts(dfil, sortOrders); - QVERIFY(contacts.size() == 3); - expectedContacts.clear(); - expectedContacts << expectedContact1LastName << expectedContact2LastName << expectedContact5LastName; - QVERIFY(expectedContacts.size() == 3); - for (int i = 0; i < contacts.size(); i++) { - bool contactFound = false; - QString lastNameString = contacts.at(i).detail<QContactName>().lastName(); - for (int j = 0; j < expectedContacts.size(); j++) { - if (lastNameString == expectedContacts.at(j)) contactFound=true; - } - QCOMPARE(contactFound, true); - } - - // retrieve contacts filtering by email - email = "Angelina.Row@ovi.com"; - dfil.setDetailType(QContactEmailAddress::Type, QContactEmailAddress::FieldEmailAddress); - dfil.setValue(email); - QVERIFY(dfil.matchFlags() == QContactFilter::MatchExactly); - contacts = myContactManager.contacts(dfil, sortOrders); - QVERIFY(contacts.size() == 1); - expectedContacts.clear(); - QFETCH(QString, expectedContact4EmailAddress); - expectedContacts.clear(); - expectedContacts << expectedContact4EmailAddress; - QVERIFY(expectedContacts.size() == 1); - for (int i = 0; i < contacts.size(); i++) { - bool contactFound = false; - QString firstNameString = contacts.at(i).detail<QContactName>().firstName(); - QString lastNameString = contacts.at(i).detail<QContactName>().lastName(); - QString emailAddress = "mailto:"; - emailAddress.append(firstNameString + "." + lastNameString + "@ovi.com"); - for (int j = 0; j < expectedContacts.size(); j++) { - if (emailAddress == expectedContacts.at(j)) contactFound=true; - } - QCOMPARE(contactFound, true); - } - - // retrieve contacts filtering by local ID - QList<QContactId> ids = myContactManager.contactIds(sortOrders); // retrieve all ids - - // Retrieve an empty list of ids - QContactIdFilter idf; - QVERIFY(idf.type() == QContactFilter::IdFilter); - QVERIFY(idf.ids().count() == 0); - contacts = myContactManager.contacts(idf, sortOrders); - QVERIFY(contacts.size() == 0); - - // Retrieve only the first ID - QContactId firstId = ids.first(); - QList<QContactId> shortList; - shortList << firstId; - idf.setIds(shortList); - QVERIFY(idf.ids() == shortList); - - QContact contact = myContactManager.contact(firstId); - QVERIFY(firstId == contact.id()); - contacts = myContactManager.contacts(idf, sortOrders); - QVERIFY(contacts.size() == 1); - QFETCH(QString, expectedContact1FirstName); - QFETCH(QString, expectedContact2FirstName); - QFETCH(QString, expectedContact3LastName); - expectedContacts.clear(); - expectedContacts << expectedContact1FirstName << expectedContact1LastName << expectedContact2FirstName << expectedContact2LastName << expectedContact3FirstName << expectedContact3LastName << expectedContact4FirstName << expectedContact4LastName << expectedContact5FirstName << expectedContact5LastName; - QVERIFY(expectedContacts.size() == 10); - bool contactFound = false; - QString firstNameString = contact.detail<QContactName>().firstName(); - QString lastNameString = contact.detail<QContactName>().lastName(); - for (int j = 0; j < expectedContacts.size(); j++) { - if ( (firstNameString == expectedContacts.at(j)) && (lastNameString == expectedContacts.at(j+1)) ) contactFound=true; - } - QCOMPARE(contactFound, true); - - // Retrieve multiple IDs - idf.setIds(ids); - QVERIFY(idf.ids() == ids); - contacts = myContactManager.contacts(idf, sortOrders); - QVERIFY(contacts.size() == 5); - expectedContacts.clear(); - expectedContacts << expectedContact1FirstName << expectedContact1LastName << expectedContact2FirstName << expectedContact2LastName << expectedContact3FirstName << expectedContact3LastName << expectedContact4FirstName << expectedContact4LastName << expectedContact5FirstName << expectedContact5LastName; - QVERIFY(expectedContacts.size() == 10); - for (int i = 0; i < contacts.size(); i++) { - bool contactFound = false; - QString firstNameString = contacts.at(i).detail<QContactName>().firstName(); - QString lastNameString = contacts.at(i).detail<QContactName>().lastName(); - for (int j = 0; j < expectedContacts.size(); j++) { - if ( (firstNameString == expectedContacts.at(j)) && (lastNameString == expectedContacts.at(j+1)) ) contactFound=true; - } - QCOMPARE(contactFound, true); - } - - // ------------ MATCH FLAG = MatchStartsWith ------------ - - // retrieve contacts filtering by first name - firstName = "Jul"; - dfil.setDetailType(QContactName::Type, QContactName::FieldFirstName); - dfil.setValue(firstName); - dfil.setMatchFlags(QContactFilter::MatchStartsWith); - QVERIFY(dfil.matchFlags() == QContactFilter::MatchStartsWith); - contacts = myContactManager.contacts(dfil, sortOrders); - QVERIFY(contacts.size() == 1); - expectedContacts.clear(); - expectedContacts << expectedContact3FirstName; - QVERIFY(expectedContacts.size() == 1); - for (int i = 0; i < contacts.size(); i++) { - bool contactFound = false; - QString firstNameString = contacts.at(i).detail<QContactName>().firstName(); - for (int j = 0; j < expectedContacts.size(); j++) { - if (firstNameString == expectedContacts.at(j)) contactFound=true; - } - QCOMPARE(contactFound, true); - } - - // ------------ MATCH FLAG = MatchEndsWith ------------ - - // retrieve contacts filtering by first name - firstName = "ie"; - dfil.setDetailType(QContactName::Type, QContactName::FieldFirstName); - dfil.setValue(firstName); - dfil.setMatchFlags(QContactFilter::MatchEndsWith); - QVERIFY(dfil.matchFlags() == QContactFilter::MatchEndsWith); - contacts = myContactManager.contacts(dfil, sortOrders); - QVERIFY(contacts.size() == 2); - expectedContacts.clear(); - expectedContacts << expectedContact3FirstName << expectedContact5FirstName; - QVERIFY(expectedContacts.size() == 2); - for (int i = 0; i < contacts.size(); i++) { - bool contactFound = false; - QString firstNameString = contacts.at(i).detail<QContactName>().firstName(); - for (int j = 0; j < expectedContacts.size(); j++) { - if (firstNameString == expectedContacts.at(j)) contactFound=true; - } - QCOMPARE(contactFound, true); - } -} - -void tst_QContactJsondbEngine::testContactDetailFilter_data() { - QTest::addColumn<QString>("expectedContact1FirstName"); - QTest::addColumn<QString>("expectedContact1LastName"); - QTest::addColumn<QString>("expectedContact2FirstName"); - QTest::addColumn<QString>("expectedContact2LastName"); - QTest::addColumn<QString>("expectedContact3FirstName"); - QTest::addColumn<QString>("expectedContact3LastName"); - QTest::addColumn<QString>("expectedContact4FirstName"); - QTest::addColumn<QString>("expectedContact4LastName"); - QTest::addColumn<QString>("expectedContact5FirstName"); - QTest::addColumn<QString>("expectedContact5LastName"); - QTest::addColumn<QString>("expectedContact2EmailAddress"); - QTest::addColumn<QString>("expectedContact4EmailAddress"); - QTest::addColumn<QString>("expectedContact5EmailAddress"); - { - QTest::newRow("expectedContactsNames") << "Harry" << "Baker" << "Paul" << "Thomson" << "Julie" << "King" << "Angelina" << "Row" << "Natalie" << "Watson" << "mailto:Paul.Thomson@ovi.com" << "mailto:Angelina.Row@ovi.com" << "mailto:Natalie.Watson@ovi.com"; - } -} - -void tst_QContactJsondbEngine::testContactSortOrder() { - QContactManager myContactManager; - - // sort order - QContactSortOrder sortOrder; - sortOrder.setDetailType(QContactName::Type, QContactName::FieldFirstName); - QList<QContactSortOrder> sortOrders; - sortOrders.append(sortOrder); - - // retrieve all the contacts and sort first names alphabetically - QContactFilter filter; - QList<QContact> contacts = myContactManager.contacts(filter, sortOrders); - QCOMPARE(contacts.size(), 5); - - QFETCH(QString, expectedContact1FirstName); - QFETCH(QString, expectedContact2FirstName); - QFETCH(QString, expectedContact3FirstName); - QFETCH(QString, expectedContact4FirstName); - QFETCH(QString, expectedContact5FirstName); - QList<QString> expectedContacts; - expectedContacts << expectedContact4FirstName << expectedContact1FirstName << expectedContact3FirstName << expectedContact5FirstName << expectedContact2FirstName; - QCOMPARE(expectedContacts.size(), 5); - if (qt_debug_jsondb_contacts()) - qDebug() << " (TEST) expected ordered contacts: " << expectedContacts; - for (int i = 0; i < contacts.size(); i++) { - QVERIFY (contacts.at(i).detail<QContactName>().firstName() == expectedContacts.at(i)); - } - - // now sort last names alphabetically - sortOrder.setDetailType(QContactName::Type, QContactName::FieldLastName); - sortOrders.clear(); - sortOrders.append(sortOrder); - contacts = myContactManager.contacts(filter, sortOrders); - if (qt_debug_jsondb_contacts()) - qDebug() << " (TEST) contacts sorted by surname: " << contacts; - QVERIFY(contacts.size() == 5); - - expectedContacts.clear(); - QFETCH(QString, expectedContact1LastName); - QFETCH(QString, expectedContact2LastName); - QFETCH(QString, expectedContact3LastName); - QFETCH(QString, expectedContact4LastName); - QFETCH(QString, expectedContact5LastName); - expectedContacts << expectedContact1LastName << expectedContact3LastName << expectedContact4LastName << expectedContact2LastName << expectedContact5LastName; - if (qt_debug_jsondb_contacts()) - qDebug() << " (TEST) EXPECTED contacts sorted by surname: " << expectedContacts; - for (int i = 0; i < contacts.size(); i++) { - QVERIFY (contacts.at(i).detail<QContactName>().lastName() == expectedContacts.at(i)); - } - - // now sort emails alphabetically - sortOrder.setDetailType(QContactEmailAddress::Type, QContactEmailAddress::FieldEmailAddress); - sortOrders.clear(); - sortOrders.append(sortOrder); - contacts = myContactManager.contacts(filter, sortOrders); - if (qt_debug_jsondb_contacts()) - qDebug() << " (TEST) contacts sorted by email address: " << contacts; - QVERIFY(contacts.size() == 5); - - expectedContacts.clear(); - QFETCH(QString, expectedContact1EmailAddress); - QFETCH(QString, expectedContact2EmailAddress); - QFETCH(QString, expectedContact3EmailAddress); - QFETCH(QString, expectedContact4EmailAddress); - QFETCH(QString, expectedContact5EmailAddress); - expectedContacts << expectedContact4EmailAddress << expectedContact1EmailAddress << expectedContact3EmailAddress << expectedContact5EmailAddress << expectedContact2EmailAddress; - QVERIFY(expectedContacts.size() == 5); - if (qt_debug_jsondb_contacts()) - qDebug() << " (TEST) EXPECTED contacts sorted by email: " << expectedContacts; - for (int i = 0; i < contacts.size(); i++) { - QVERIFY (contacts.at(i).detail<QContactEmailAddress>().emailAddress() == expectedContacts.at(i)); - } - - // retrieve contacts filtering them by first name, then sort the results alphabetically - sortOrder.setDetailType(QContactName::Type, QContactName::FieldFirstName); - sortOrders.clear(); - sortOrders.append(sortOrder); - QString firstName = "li"; - QContactDetailFilter dfil; - dfil.setDetailType(QContactName::Type, QContactName::FieldFirstName); - dfil.setValue(firstName); - dfil.setMatchFlags(QContactFilter::MatchContains); - QVERIFY(dfil.matchFlags() == QContactFilter::MatchContains); - contacts = myContactManager.contacts(dfil, sortOrders); - if (qt_debug_jsondb_contacts()) - qDebug() << " (TEST) contacts filtered and sorted by first name: " << contacts; - expectedContacts.clear(); - QVERIFY(contacts.size() == 3); - - expectedContacts << expectedContact4FirstName << expectedContact3FirstName << expectedContact5FirstName; - QVERIFY(expectedContacts.size() == 3); - if (qt_debug_jsondb_contacts()) - qDebug() << " (TEST) expected filtered and ordered contacts: " << expectedContacts; - for (int i = 0; i < expectedContacts.size(); i++) { - QVERIFY (contacts.at(i).detail<QContactName>().firstName() == expectedContacts.at(i)); - } - - // now sort the filtered results by email address - sortOrder.setDetailType(QContactEmailAddress::Type, QContactEmailAddress::FieldEmailAddress); - sortOrders.clear(); - sortOrders.append(sortOrder); - firstName = ""; - dfil.setDetailType(QContactName::Type, QContactName::FieldFirstName); - dfil.setValue(firstName); - dfil.setMatchFlags(QContactFilter::MatchContains); - QVERIFY(dfil.matchFlags() == QContactFilter::MatchContains); - contacts = myContactManager.contacts(dfil, sortOrders); - if (qt_debug_jsondb_contacts()) - qDebug() << " (TEST) filtered contacts sorted by email address: " << contacts; - QVERIFY(contacts.size() == 5); -} - -void tst_QContactJsondbEngine::testContactSortOrder_data() { - QTest::addColumn<QString>("expectedContact1FirstName"); - QTest::addColumn<QString>("expectedContact1LastName"); - QTest::addColumn<QString>("expectedContact2FirstName"); - QTest::addColumn<QString>("expectedContact2LastName"); - QTest::addColumn<QString>("expectedContact3FirstName"); - QTest::addColumn<QString>("expectedContact3LastName"); - QTest::addColumn<QString>("expectedContact4FirstName"); - QTest::addColumn<QString>("expectedContact4LastName"); - QTest::addColumn<QString>("expectedContact5FirstName"); - QTest::addColumn<QString>("expectedContact5LastName"); - QTest::addColumn<QString>("expectedContact1EmailAddress"); - QTest::addColumn<QString>("expectedContact2EmailAddress"); - QTest::addColumn<QString>("expectedContact3EmailAddress"); - QTest::addColumn<QString>("expectedContact4EmailAddress"); - QTest::addColumn<QString>("expectedContact5EmailAddress"); - { - QTest::newRow("expectedContactsNames") << "Harry" << "Baker" << "Paul" << "Thomson" << "Julie" << "King" << "Angelina" << "Row" << "Natalie" << "Watson" << "Harry.Baker@ovi.com" << "Paul.Thomson@ovi.com" << "Julie.King@ovi.com" << "Angelina.Row@ovi.com" << "Natalie.Watson@ovi.com"; - } -} - -void tst_QContactJsondbEngine::testRemoveContacts() { - QContactManager cm; - - // Test error generation when passing empty Id list - QList<QContactId> emptyList; - bool returnValue = cm.removeContacts(emptyList); - QVERIFY(returnValue == false); - QVERIFY(cm.error() == 10); // Check if the generated error is in fact "BadArgumentError" - - // Test error generation when passing invalid Ids: empty string - QList<QContactId> voidList; - voidList << QContactId(); - returnValue = cm.removeContacts(voidList); - QVERIFY(returnValue == false); - QVERIFY(cm.error() == 1); // Check if the generated error is in fact "DoesNotExistError" - - // TODO: This is the same as above, clean or use real invalid id. - // Test error generation when passing invalid Ids: non existing string - QList<QContactId> invalidList; - invalidList << QContactId(); - qDebug() << "(non existing contact Id) TO REMOVE: " << invalidList; - returnValue = cm.removeContacts(invalidList); - QVERIFY(returnValue == false); - - QVERIFY(cm.error() == 1); // Check whether the generated error code is in fact "DoesNotExistError" - - // Remove only two contacts - QList<QContact> saveList; - QContactName nameDetail; - QContact contactToRemove1; - nameDetail.setFirstName("Contact To Remove 1"); - contactToRemove1.saveDetail(&nameDetail); - saveList << contactToRemove1; - cm.saveContact(&contactToRemove1); - QContactId contactToRemove1Id = contactToRemove1.id(); - - QContact contactToRemove2; - nameDetail.setFirstName("Contact To Remove 2"); - contactToRemove2.saveDetail(&nameDetail); - saveList << contactToRemove2; - cm.saveContact(&contactToRemove2); - QContactId contactToRemove2Id = contactToRemove2.id(); - - QList<QContactId> contactsToRemove; - QContactFilter filter; - QList<QContactSortOrder> sortOrders; - QList<QContact> contacts = cm.contacts(filter, sortOrders); - QContactName nameDetail1; - nameDetail1.setFirstName("Contact To Remove 1"); - QContactName nameDetail2; - nameDetail2.setFirstName("Contact To Remove 2"); - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>() == nameDetail1) contactsToRemove << curr.id(); - if (curr.detail<QContactName>() == nameDetail2) contactsToRemove << curr.id(); - } - if (qt_debug_jsondb_contacts()) - qDebug() << "(two contacts) TO REMOVE: " << contactsToRemove; - returnValue = cm.removeContacts(contactsToRemove); - QVERIFY(returnValue == true); - - QVERIFY(cm.error() == 0); // Check if there are errors - //QCOMPARE(cm.contactIds().size(), originalCount - 2); // Does not work when there are multiple contacts with the same name - bool contact1Found = false; - bool contact2Found = false; - contacts = cm.contacts(filter, sortOrders); // Update the contact list after removal - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>() == nameDetail1) contact1Found=true; - if (curr.detail<QContactName>() == nameDetail2) contact2Found=true; - } - QVERIFY(contact1Found == false); - QVERIFY(contact2Found == false); - - QList<QContactId> toRemove = cm.contactIds(); - if (qt_debug_jsondb_contacts()) - qDebug() << "TO REMOVE: " << toRemove; - returnValue = cm.removeContacts(toRemove); - QVERIFY(returnValue == true || cm.error() == QContactManager::BadArgumentError); // It currently gives BadArgumentError if empty list given (no contacts in cm). - QList<QContactId> contactsLeft = cm.contactIds(); - qDebug() << "NOTE: the error message by doSyncRequest in function contactIds is due to the fact that there are no contacts left in the database"; - QVERIFY(contactsLeft.isEmpty()); // Check that all the contacts have been removed - - // save two new contacts (just not to leave the database empty) - QContact newContact1; - nameDetail.setFirstName("new contact 1"); - newContact1.saveDetail(&nameDetail); - saveList << newContact1; - cm.saveContact(&newContact1); - QContact newContact2; - nameDetail.setFirstName("new contact 2"); - newContact2.saveDetail(&nameDetail); - saveList << newContact2; - cm.saveContact(&newContact2); -} - -void tst_QContactJsondbEngine::testRemoveContact() { - QContactManager cm; - - // save a new contact - QContact contactToRemove; - QContactName nameDetail; - nameDetail.setFirstName("Contact To Remove"); - contactToRemove.saveDetail(&nameDetail); - cm.saveContact(&contactToRemove); - QContactId contactToRemoveId = contactToRemove.id(); - - // Remove the contact - bool returnValue = cm.removeContact(contactToRemoveId); - QVERIFY(returnValue == true); - QVERIFY(cm.error() == 0); // Check if there are errors - bool contactToRemoveFound = false; - QContactFilter filter; - QList<QContactSortOrder> sortOrders; - QList<QContact> contacts = cm.contacts(filter, sortOrders); // Update the contact list after removal - foreach (QContact curr, contacts) { - if (curr.detail<QContactName>() == nameDetail) contactToRemoveFound=true; - } - QVERIFY(contactToRemoveFound == false); -} - -QTEST_MAIN(tst_QContactJsondbEngine); - -#include "tst_qcontactjsondbengine.moc" diff --git a/tests/auto/contacts/qcontactjsondbconverter/qcontactjsondbconverter.pro b/tests/auto/contacts/qcontactjsondbconverter/qcontactjsondbconverter.pro deleted file mode 100644 index ec531de79..000000000 --- a/tests/auto/contacts/qcontactjsondbconverter/qcontactjsondbconverter.pro +++ /dev/null @@ -1,24 +0,0 @@ -include(../../auto.pri) - -QT += contacts contacts-private jsondb - -SOURCES += tst_qcontactjsondbconverter.cpp \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbconverter.cpp \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbenginefactory.cpp \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbengine.cpp \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbrequesthandler.cpp \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbrequestmanager.cpp \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbid.cpp \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbstring.cpp - -HEADERS += ../../../../src/plugins/contacts/jsondb/qcontactjsondbenginefactory.h \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbengine.h \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbconverter.h \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbrequesthandler.h \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbrequestmanager.h \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbid.h \ - ../../../../src/plugins/contacts/jsondb/qcontactjsondbstring.h - -INCLUDEPATH += ../../../../src/plugins/contacts/jsondb - -DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 diff --git a/tests/auto/contacts/qcontactjsondbconverter/tst_qcontactjsondbconverter.cpp b/tests/auto/contacts/qcontactjsondbconverter/tst_qcontactjsondbconverter.cpp deleted file mode 100644 index 54f81c906..000000000 --- a/tests/auto/contacts/qcontactjsondbconverter/tst_qcontactjsondbconverter.cpp +++ /dev/null @@ -1,1471 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtCore/QString> -#include <QtTest/QtTest> -#include <QJsonObject> -#include <QtContacts/QContact> -#include <QtContacts/qcontactname.h> -#include <QtContacts/QContactGender> -#include <QtContacts/QContactOrganization> -#include <QtContacts/QContactBirthday> -#include <QtContacts/QContactAvatar> -#include <QtContacts/QContactRingtone> -#include <QtContacts/QContactNickname> -#include <QtContacts/QContactNote> -#include <QtContacts/QContactEmailAddress> -#include <QtContacts/QContactPhoneNumber> -#include <QtContacts/QContactAddress> -#include <QtContacts/QContactUrl> -#include <QtContacts/QContactIdFilter> -#include <QtContacts/QContactId> - -#include "qcontactjsondbconverter.h" -#include "qcontactjsondbengine.h" -#include "qcontactjsondbstring.h" -#include "qcontactjsondbid.h" - -QTCONTACTS_USE_NAMESPACE - -class tst_QcontactJsondbConverter : public QObject -{ - Q_OBJECT -public: - tst_QcontactJsondbConverter(); -private Q_SLOTS: - void toQContactTest(); - void toJsonContactTest(); - void toQContactsTest(); - void updateContextsTest(); - void queryFromRequestTest(); - void convertCompoundFilterTest(); - void convertSortOrderTest(); - void contactIdToUuidTest(); -private: - void testJsonDetailItems(const QJsonObject& values, const QString& extractField, - const QMap<QString, QString>& fields, bool testSize = true); - void initializeJsonContact(QJsonObject& jsonContact, unsigned int numbering = 0); - -private: - QString m_partitionName; -}; - - -tst_QcontactJsondbConverter::tst_QcontactJsondbConverter() - : m_partitionName(QContactJsonDbStr::userDataPartition()) -{ - // nothing needed -} - - - - - -void tst_QcontactJsondbConverter::toQContactTest() -{ - QContactJsonDbConverter converter; - QContactJsonDbEngine engine; - QJsonObject jsonContact; - QContact contact; - QJsonObject jsonData; - QContactDetail detail; - - // test name (set in initialization) - initializeJsonContact(jsonContact); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactName::Type); - QVERIFY(!detail.isEmpty()); - QContactName* name = static_cast<QContactName*>(&detail); - QVERIFY(name != NULL); - QCOMPARE(name->firstName(), QString("John")); - QCOMPARE(name->lastName(), QString("Doe")); - QCOMPARE(name->middleName(), QString("Tom")); - // cleanup - contact.clearDetails(); - // test name with white spaces to be trimmed - jsonData.insert("firstName", QString("John")); - jsonData.insert("lastName", QString("Doe ")); - jsonData.insert("middleName", QString(" Tom")); - jsonContact.insert(QContactJsonDbStr::nameDefinitionName(), jsonData); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactName::Type); - QVERIFY(!detail.isEmpty()); - name = static_cast<QContactName*>(&detail); - QVERIFY(name != NULL); - QCOMPARE(name->firstName(), QString("John")); - QCOMPARE(name->lastName(), QString("Doe")); - QCOMPARE(name->middleName(), QString("Tom")); - // cleanup - jsonData = QJsonObject(); - contact.clearDetails(); - // test invalid name (name is too long) - jsonData.insert("firstName", QString(" John ")); - jsonData.insert("lastName", QString("Vvvvvvvvvveeeeeeeeeerrrrrrrrrryyyyyyyyyylongnameeeeeeeeee")); - jsonData.insert("middleName", QString(" Tom")); - jsonContact.insert(QContactJsonDbStr::nameDefinitionName(), jsonData); - QVERIFY(!converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactName::Type); - QVERIFY(detail.isEmpty()); - name = static_cast<QContactName*>(&detail); - QVERIFY(name->isEmpty()); - // cleanup - jsonData = QJsonObject(); - contact.clearDetails(); - // test passing an empty string in the first place: invalid - QString emptyName; - jsonData.insert("firstName", emptyName); - jsonData.insert("lastName", emptyName); - jsonContact.insert(QContactJsonDbStr::nameDefinitionName(), jsonData); - QVERIFY(!converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactName::Type); - QVERIFY(detail.isEmpty()); - name = static_cast<QContactName*>(&detail); - QVERIFY(name->isEmpty()); - // cleanup - jsonData = QJsonObject(); - contact.clearDetails(); - // test with a string which becomes empty after sanitizing it: invalid, contact not saved - QString invalidName = " "; - jsonData.insert("firstName", QString(" John ")); - jsonData.insert("lastName", invalidName); - jsonContact.insert(QContactJsonDbStr::nameDefinitionName(), jsonData); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactName::Type); - QVERIFY(!detail.isEmpty()); - name = static_cast<QContactName*>(&detail); - QVERIFY(!name->isEmpty()); - QVERIFY(name->lastName().isEmpty()); - // cleanup - jsonData = QJsonObject(); - contact.clearDetails(); - - // gender - initializeJsonContact(jsonContact); - jsonData.insert("gender", QString("male")); - jsonContact.insert("gender", jsonData); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactGender::Type); - QVERIFY(!detail.isEmpty()); - QContactGender* gender = static_cast<QContactGender*>(&detail); - QVERIFY(gender != NULL); - QCOMPARE(gender->gender(), QContactGender::GenderMale); - // cleanup - contact.clearDetails(); - jsonData = QJsonObject(); - - // organization - initializeJsonContact(jsonContact); - jsonData.insert("name", QString("ACME")); - jsonData.insert("department", QString("Spy")); - jsonData.insert("title", QString("Vice President")); - jsonData.insert("role", QString("Superhero")); - jsonData.insert("assistantName", QString("Daisy Duck")); - jsonData.insert("logoUrl", QString("http://www.acme.com/logo.jpg")); - QJsonArray organizationData; - organizationData.append(jsonData); - jsonContact.insert("organizations", organizationData); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactOrganization::Type); - QVERIFY(!detail.isEmpty()); - QContactOrganization* org = static_cast<QContactOrganization*>(&detail); - QVERIFY(org != NULL); - QCOMPARE(org->name(), QString("ACME")); - QCOMPARE(org->department().at(0), QString("Spy")); - QCOMPARE(org->title(), QString("Vice President")); - QCOMPARE(org->role(), QString("Superhero")); - QCOMPARE(org->assistantName(), QString("Daisy Duck")); - QCOMPARE(org->logoUrl(), QUrl("http://www.acme.com/logo.jpg")); - // cleanup - contact.clearDetails(); - jsonData = QJsonObject(); - // test organization with white spaces to be trimmed - jsonData.insert("name", QString(" ACME2")); - jsonData.insert("department", QString("Spy2 ")); - jsonData.insert("title", QString(" Vice President 2")); - jsonData.insert("role", QString(" Superhero2 ")); - jsonData.insert("assistantName", QString(" Daisy Duck 2")); - QJsonArray organizationData1; - organizationData1.append(jsonData); - jsonContact.insert("organizations", organizationData1); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactOrganization::Type); - QVERIFY(!detail.isEmpty()); - org = static_cast<QContactOrganization*>(&detail); - QVERIFY(org != NULL); - QCOMPARE(org->name(), QString("ACME2")); - QCOMPARE(org->department().at(0), QString("Spy2")); - QCOMPARE(org->title(), QString("Vice President 2")); - QCOMPARE(org->role(), QString("Superhero2")); - QCOMPARE(org->assistantName(), QString("Daisy Duck 2")); - // cleanup - contact.clearDetails(); - jsonData = QJsonObject(); - // test invalid organization name (name is too long) - jsonData.insert("name", QString("Vvvvvvvvvveeeeeeeeeerrrrrrrrrryyyyyyyyyylongnameeeeeeeeee")); - QJsonArray organizationData2; - organizationData2.append(jsonData); - jsonContact.insert(QContactJsonDbStr::organizationDefinitionName(), organizationData2); - QVERIFY(!converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactOrganization::Type); - QVERIFY(detail.isEmpty()); - org = static_cast<QContactOrganization*>(&detail); - QVERIFY(org->isEmpty()); - // cleanup - jsonData = QJsonObject(); - contact.clearDetails(); - // test passing an empty string in the first place: allowed - jsonData.insert("name", emptyName); - jsonContact.insert(QContactJsonDbStr::organizationDefinitionName(), jsonData); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactOrganization::Type); - QVERIFY(detail.isEmpty()); - org = static_cast<QContactOrganization*>(&detail); - QVERIFY(org->isEmpty()); - // cleanup - jsonData = QJsonObject(); - contact.clearDetails(); - // test with a string which becomes empty after sanitizing it: detail is ignored - jsonData.insert("name", invalidName); - QJsonArray organizationData3; - organizationData3.append(jsonData); - jsonContact.insert(QContactJsonDbStr::organizationDefinitionName(), organizationData3); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactOrganization::Type); - QVERIFY(detail.isEmpty()); - org = static_cast<QContactOrganization*>(&detail); - QVERIFY(org->isEmpty()); - // cleanup - jsonData = QJsonObject(); - contact.clearDetails(); - - - // birthday - initializeJsonContact(jsonContact); - QDateTime birthDayDate = QDateTime::fromString("1979-11-22", Qt::ISODate); - jsonData.insert("birthday", QStringLiteral("1979-11-22")); - jsonContact.insert("details", jsonData); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactBirthday::Type); - QVERIFY(!detail.isEmpty()); - QContactBirthday* bd = static_cast<QContactBirthday*>(&detail); - QVERIFY(bd != NULL); - QCOMPARE(bd->dateTime(), birthDayDate); - // cleanup - contact.clearDetails(); - - // avatar - initializeJsonContact(jsonContact); - jsonData.insert("photoUrl", QString("http://www.acme.com/logo.jpg")); - jsonContact.insert("details", jsonData); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactAvatar::Type); - QVERIFY(!detail.isEmpty()); - QContactAvatar* avatar = static_cast<QContactAvatar*>(&detail); - QVERIFY(avatar != NULL); - QCOMPARE(avatar->imageUrl(), QUrl("http://www.acme.com/logo.jpg")); - // cleanup - contact.clearDetails(); - - - // ringtone - initializeJsonContact(jsonContact); - jsonData.insert("ringtoneUrl", QString("http://www.acme.com/ring.mp3")); - jsonContact.insert("details", jsonData); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactRingtone::Type); - QVERIFY(!detail.isEmpty()); - QContactRingtone* ring = static_cast<QContactRingtone*>(&detail); - QVERIFY(ring != NULL); - QCOMPARE(ring->audioRingtoneUrl(), QUrl("http://www.acme.com/ring.mp3")); - // cleanup - contact.clearDetails(); - jsonData = QJsonObject(); - - // nickname - initializeJsonContact(jsonContact); - jsonData.insert("nickname", QString("Chupacabra")); - jsonContact.insert("details", jsonData); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactNickname::Type); - QVERIFY(!detail.isEmpty()); - QContactNickname* nick = static_cast<QContactNickname*>(&detail); - QVERIFY(nick != NULL); - QCOMPARE(nick->nickname(), QString("Chupacabra")); - // cleanup - contact.clearDetails(); - jsonData = QJsonObject(); - // test nickname with white spaces to be trimmed - jsonData.insert("nickname", QString(" Chupacabra")); - jsonContact.insert("details", jsonData); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactNickname::Type); - QVERIFY(!detail.isEmpty()); - nick = static_cast<QContactNickname*>(&detail); - QVERIFY(nick != NULL); - QCOMPARE(nick->nickname(), QString("Chupacabra")); - // cleanup - jsonData = QJsonObject(); - contact.clearDetails(); - // test invalid nickname (nickname is too long) - jsonData.insert("nickname", QString("Vvvvvvvvvveeeeeeeeeerrrrrrrrrryyyyyyyyyylongnameeeeeeeeee")); - jsonContact.insert("details", jsonData); - QVERIFY(!converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactNickname::Type); - QVERIFY(detail.isEmpty()); - nick = static_cast<QContactNickname*>(&detail); - QVERIFY(nick->isEmpty()); - // cleanup - jsonData = QJsonObject(); - contact.clearDetails(); - // test passing an empty string in the first place: allowed - jsonData.insert("nickname", emptyName); - jsonContact.insert("details", jsonData); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactNickname::Type); - QVERIFY(detail.isEmpty()); - nick = static_cast<QContactNickname*>(&detail); - QVERIFY(nick->isEmpty()); - // cleanup - jsonData = QJsonObject(); - contact.clearDetails(); - // test with a string which becomes empty after sanitizing it: invalid, detail ignored - jsonData.insert("nickname", invalidName); - jsonContact.insert("details", jsonData); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactNickname::Type); - QVERIFY(detail.isEmpty()); - nick = static_cast<QContactNickname*>(&detail); - QVERIFY(nick->isEmpty()); - // cleanup - jsonData = QJsonObject(); - contact.clearDetails(); - - // note - initializeJsonContact(jsonContact); - jsonData.insert("note", QString("test note")); - jsonContact.insert("details", jsonData); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactNote::Type); - QVERIFY(!detail.isEmpty()); - QContactNote* note = static_cast<QContactNote*>(&detail); - QVERIFY(note != NULL); - QCOMPARE(note->note(), QString("test note")); - // cleanup - contact.clearDetails(); - jsonData = QJsonObject(); - // test note with white spaces to be trimmed - jsonData.insert("note", QString(" Chupacabra")); - jsonContact.insert("details", jsonData); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactNote::Type); - QVERIFY(!detail.isEmpty()); - note = static_cast<QContactNote*>(&detail); - QVERIFY(note != NULL); - QCOMPARE(note->note(), QString("Chupacabra")); - // cleanup - jsonData = QJsonObject(); - contact.clearDetails(); - // test invalid note (note is too long) - QString tooLongNote; - for (int i=0; i<10001; i++) { - tooLongNote += 'a'; - } - jsonData.insert("note", tooLongNote); - jsonContact.insert("details", jsonData); - QVERIFY(!converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactNote::Type); - QVERIFY(detail.isEmpty()); - note = static_cast<QContactNote*>(&detail); - QVERIFY(note->isEmpty()); - // cleanup - jsonData = QJsonObject(); - contact.clearDetails(); - // test passing an empty string in the first place: allowed - jsonData.insert("note", emptyName); - jsonContact.insert("details", jsonData); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactNote::Type); - QVERIFY(detail.isEmpty()); - note = static_cast<QContactNote*>(&detail); - QVERIFY(note->isEmpty()); - // cleanup - jsonData = QJsonObject(); - contact.clearDetails(); - // test with a string which becomes empty after sanitizing it: invalid, detail ignored - jsonData.insert("note", invalidName); - jsonContact.insert("details", jsonData); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactNote::Type); - QVERIFY(detail.isEmpty()); - note = static_cast<QContactNote*>(&detail); - QVERIFY(note->isEmpty()); - // cleanup - jsonData = QJsonObject(); - contact.clearDetails(); - - // email - initializeJsonContact(jsonContact); - jsonData.insert("value", QString("john@doe.com")); - jsonData.insert("context", QString("home")); - QJsonArray emails; - emails.append(jsonData); - jsonContact.insert("emails", emails); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactEmailAddress::Type); - QVERIFY(!detail.isEmpty()); - QContactEmailAddress* email = static_cast<QContactEmailAddress*>(&detail); - QVERIFY(email != NULL); - QCOMPARE(email->emailAddress(), QString("john@doe.com")); - QVERIFY(email->contexts().size() == 1); - QVERIFY(email->contexts()[0] == QContactEmailAddress::ContextHome); - // cleanup - contact.clearDetails(); - jsonData = QJsonObject(); - emails.removeFirst(); - // test email with white spaces to be trimmed - jsonData.insert("value", QString(" john@doe.com")); - jsonData.insert("context", QString("home")); - emails.append(jsonData); - jsonContact.insert("emails", emails); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactEmailAddress::Type); - QVERIFY(!detail.isEmpty()); - email = static_cast<QContactEmailAddress*>(&detail); - QVERIFY(email != NULL); - QCOMPARE(email->emailAddress(), QString("john@doe.com")); - QVERIFY(email->contexts().size() == 1); - QVERIFY(email->contexts()[0] == QContactEmailAddress::ContextHome); - // cleanup - contact.clearDetails(); - jsonData = QJsonObject(); - emails.removeFirst(); - // test invalid email (email is too long) - QString tooLongEmail; - for (int i=0; i<127; i++) { - tooLongEmail += 'a'; - } - jsonData.insert("value", tooLongEmail); - jsonData.insert("context", QString("home")); - emails.append(jsonData); - jsonContact.insert("emails", emails); - QVERIFY(!converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactEmailAddress::Type); - QVERIFY(detail.isEmpty()); - email = static_cast<QContactEmailAddress*>(&detail); - QVERIFY(email != NULL); - QVERIFY(email->isEmpty()); - // cleanup - contact.clearDetails(); - jsonData = QJsonObject(); - emails.removeFirst(); - // test passing an empty string in the first place: allowed - jsonData.insert("value", emptyName); - jsonData.insert("context", QString("home")); - emails.append(jsonData); - jsonContact.insert("emails", emails); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactEmailAddress::Type); - QVERIFY(detail.isEmpty()); - email = static_cast<QContactEmailAddress*>(&detail); - QVERIFY(email->isEmpty()); - // cleanup - contact.clearDetails(); - jsonData = QJsonObject(); - emails.removeFirst(); - // test with a string which becomes empty after sanitizing it: invalid, contact not saved - jsonData.insert("value", invalidName); - jsonData.insert("context", QString("home")); - emails.append(jsonData); - jsonContact.insert("emails", emails); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactEmailAddress::Type); - QVERIFY(detail.isEmpty()); - email = static_cast<QContactEmailAddress*>(&detail); - QVERIFY(email->isEmpty()); - // cleanup - contact.clearDetails(); - jsonData = QJsonObject(); - emails.removeFirst(); - - // phone number - initializeJsonContact(jsonContact); - jsonData.insert("value", QString("0507654321")); - jsonData.insert("subType", QString("cell")); - QJsonArray phones; - phones.append(jsonData); - jsonContact.insert("phones", phones); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactPhoneNumber::Type); - QVERIFY(!detail.isEmpty()); - QContactPhoneNumber* phone = static_cast<QContactPhoneNumber*>(&detail); - QVERIFY(phone != NULL); - QCOMPARE(phone->number(), QString("0507654321")); - QVERIFY(phone->subTypes().size() == 1); - QVERIFY(phone->subTypes()[0] == QContactPhoneNumber::SubTypeMobile); - // cleanup - contact.clearDetails(); - phones = QJsonArray(); - jsonData = QJsonObject(); - - //let's try with a phone number containing a few invalid characters - jsonData.insert("value", - QString(" +123(45678)90-+++abcdefghijklmnopqrstuvwxyz#*+++++ ")); - jsonData.insert("subType", QString("cell")); - phones.append(jsonData); - jsonContact.insert("phones", phones); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactPhoneNumber::Type); - QVERIFY(!detail.isEmpty()); - phone = static_cast<QContactPhoneNumber*>(&detail); - QVERIFY(phone != NULL); - QCOMPARE(phone->number(), QString("+123(45678)90-abcdpw#*")); - QVERIFY(phone->subTypes().size() == 1); - QVERIFY(phone->subTypes()[0] == QContactPhoneNumber::SubTypeMobile); - // cleanup - jsonData = QJsonObject(); - phones = QJsonArray(); - contact.clearDetails(); - - //let's try with an invalid phone number - jsonData.insert("value", - QString(" efghijk\"\"][[[]]] ")); - jsonData.insert("subType", QString("cell")); - phones.append(jsonData); - jsonContact.insert("phones", phones); - QVERIFY(!converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactPhoneNumber::Type); - QVERIFY(detail.isEmpty()); - phone = static_cast<QContactPhoneNumber*>(&detail); - QVERIFY(phone->isEmpty()); - contact.clearDetails(); - //yet another invalid phone number (too long) - QString tooLongNumber; - for (int i=0; i<100; i++) { - tooLongNumber += QString::number(i/10); - } - jsonData = QJsonObject(); - phones = QJsonArray(); - jsonData.insert("value", tooLongNumber); - phones.append(jsonData); - jsonContact.insert("phones", phones); - QVERIFY(!converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactPhoneNumber::Type); - QVERIFY(detail.isEmpty()); - phone = static_cast<QContactPhoneNumber*>(&detail); - QVERIFY(phone->isEmpty()); - // cleanup - jsonData = QJsonObject(); - phones = QJsonArray(); - contact.clearDetails(); - //last but not least, empty phone number should be ignored - QString emptyNumber; - jsonData.insert("value", emptyNumber); - phones.append(jsonData); - jsonContact.insert("phones", phones); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - QVERIFY(contact.details(QContactPhoneNumber::Type).isEmpty()); - phone = static_cast<QContactPhoneNumber*>(&detail); - QVERIFY(phone->isEmpty()); - // cleanup - jsonData = QJsonObject(); - contact.clearDetails(); - - // address - initializeJsonContact(jsonContact); - jsonData.insert("country", QString("Finland")); - jsonData.insert("postOfficeBox", QString("347")); - jsonData.insert("postcode", QString("33101")); - jsonData.insert("locality", QString("Tampere")); - jsonData.insert("region", QString("Pirkanmaa")); - jsonData.insert("street", QString("PL 347")); - QJsonArray addresses; - addresses.append(jsonData); - jsonContact.insert("addresses", addresses); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactAddress::Type); - QVERIFY(!detail.isEmpty()); - QContactAddress* addr = static_cast<QContactAddress*>(&detail); - QVERIFY(addr != NULL); - QCOMPARE(addr->country(), QString("Finland")); - QCOMPARE(addr->postOfficeBox(), QString("347")); - QCOMPARE(addr->postcode(), QString("33101")); - QCOMPARE(addr->locality(), QString("Tampere")); - QCOMPARE(addr->region(), QString("Pirkanmaa")); - QCOMPARE(addr->street(), QString("PL 347")); - // cleanup - contact.clearDetails(); - jsonData = QJsonObject(); - - // test address with white spaces to be trimmed - jsonData.insert("country", QString(" Finland2")); - jsonData.insert("postOfficeBox", QString("347 ")); - jsonData.insert("postcode", QString(" 33101 ")); - jsonData.insert("locality", QString(" Tampere2 ")); - jsonData.insert("region", QString(" Pirkanmaa2 ")); - jsonData.insert("street", QString(" PL 347 ")); - QJsonArray addressData1; - addressData1.append(jsonData); - jsonContact.insert("addresses", addressData1); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactAddress::Type); - QVERIFY(!detail.isEmpty()); - addr = static_cast<QContactAddress*>(&detail); - QVERIFY(addr != NULL); - QCOMPARE(addr->country(), QString("Finland2")); - QCOMPARE(addr->postOfficeBox(), QString("347")); - QCOMPARE(addr->postcode(), QString("33101")); - QCOMPARE(addr->locality(), QString("Tampere2")); - QCOMPARE(addr->region(), QString("Pirkanmaa2")); - QCOMPARE(addr->street(), QString("PL 347")); - // cleanup - contact.clearDetails(); - jsonData = QJsonObject(); - // test invalid address name (name is too long) - jsonData.insert("country", QString("Vvvvvvvvvveeeeeeeeeerrrrrrrrrryyyyyyyyyylongnameeeeeeeeee")); - QJsonArray addressData2; - addressData2.append(jsonData); - jsonContact.insert(QContactJsonDbStr::addressDefinitionName(), addressData2); - QVERIFY(!converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactAddress::Type); - QVERIFY(detail.isEmpty()); - addr = static_cast<QContactAddress*>(&detail); - QVERIFY(org->isEmpty()); - // cleanup - jsonData = QJsonObject(); - contact.clearDetails(); - // test passing an empty string in the first place: allowed - jsonData.insert("country", emptyName); - jsonContact.insert(QContactJsonDbStr::addressDefinitionName(), jsonData); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactAddress::Type); - QVERIFY(detail.isEmpty()); - addr = static_cast<QContactAddress*>(&detail); - QVERIFY(org->isEmpty()); - // cleanup - jsonData = QJsonObject(); - contact.clearDetails(); - // test with a string which becomes empty after sanitizing it: invalid, contact not saved - jsonData.insert("country", invalidName); - QJsonArray addressData3; - addressData3.append(jsonData); - jsonContact.insert(QContactJsonDbStr::addressDefinitionName(), addressData3); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactAddress::Type); - QVERIFY(detail.isEmpty()); - addr = static_cast<QContactAddress*>(&detail); - QVERIFY(org->isEmpty()); - // cleanup - jsonData = QJsonObject(); - contact.clearDetails(); - - // url - initializeJsonContact(jsonContact); - jsonData.insert("value", QString("http://www.acme.com")); - QJsonArray urls; - urls.append(jsonData); - jsonContact.insert("urls", urls); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactUrl::Type); - QVERIFY(!detail.isEmpty()); - QContactUrl* url = static_cast<QContactUrl*>(&detail); - QVERIFY(url != NULL); - QCOMPARE(url->url(), QString("http://www.acme.com")); - // cleanup - contact.clearDetails(); - jsonData = QJsonObject(); - - // version - initializeJsonContact(jsonContact); - QString sequenceNumberString (QStringLiteral("1")); - QString versionString (QStringLiteral("1234567890")); - QString jsonVersion(sequenceNumberString + "-" + versionString); - QByteArray expectedExtendedVersion(versionString.toLatin1()); - - jsonContact.insert("_version", jsonVersion); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactVersion::Type); - QVERIFY(!detail.isEmpty()); - QContactVersion* version = static_cast<QContactVersion*>(&detail); - QVERIFY(version != NULL); - QCOMPARE(version->extendedVersion(), expectedExtendedVersion); - QCOMPARE(version->sequenceNumber(), sequenceNumberString.toInt()); - // cleanup - contact.clearDetails(); - jsonData = QJsonObject(); - - // extended detail with simple string data - initializeJsonContact(jsonContact); - jsonContact.insert("simpleStringDetail", QString("Simple string as detail data.")); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - QList<QContactExtendedDetail> extendedDetails = contact.details<QContactExtendedDetail>(); - QCOMPARE(extendedDetails[0].name(), QString("simpleStringDetail")); - QCOMPARE(extendedDetails[0].data().toString(), QString("Simple string as detail data.")); - // cleanup - contact.clearDetails(); - jsonData = QJsonObject(); - - // extended detail with QJsonObject as data - initializeJsonContact(jsonContact); - jsonData.insert("Item1", QString("Content for list item 1.")); - jsonData.insert("Item2", int(2)); - jsonData.insert("Item3", QString("Content for list item 3.")); - jsonData.insert("Item4", QString("Content for list item 4.")); - jsonContact.insert("jsonObjectDetail", jsonData); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactExtendedDetail::Type); - QContactExtendedDetail* extendedDetail = static_cast<QContactExtendedDetail*>(&detail); - QCOMPARE(extendedDetail->name(), QString("jsonObjectDetail")); - QJsonObject extendedDetailItems = QJsonObject::fromVariantMap(extendedDetail->data().toMap()); - QCOMPARE(extendedDetailItems.value("Item1").toString(), QString("Content for list item 1.")); - QCOMPARE(extendedDetailItems.value("Item2").toVariant().toInt(), 2); - QCOMPARE(extendedDetailItems.value("Item3").toString(), QString("Content for list item 3.")); - QCOMPARE(extendedDetailItems.value("Item4").toString(), QString("Content for list item 4.")); - // cleanup - contact.clearDetails(); - jsonData = QJsonObject(); - - // extended detail with QJsonArray as data - initializeJsonContact(jsonContact); - QStringList extendedDetailsStringList; - extendedDetailsStringList<<"QStringInListFirst"<<"QStringInListSecond"; - QJsonArray array = QJsonArray::fromStringList(extendedDetailsStringList); - jsonContact.insert("jsonArrayDetail", array); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactExtendedDetail::Type); - extendedDetail = static_cast<QContactExtendedDetail*>(&detail); - QCOMPARE(extendedDetail->name(), QString("jsonArrayDetail")); - QJsonArray extendedDetailListItems = QJsonArray::fromVariantList(extendedDetail->data().toList()); - QCOMPARE(extendedDetailListItems.count(),2); - QCOMPARE(extendedDetailListItems.at(0).toString(), QString("QStringInListFirst")); - QCOMPARE(extendedDetailListItems.at(1).toString(), QString("QStringInListSecond")); - // cleanup - contact.clearDetails(); - jsonData = QJsonObject(); - - // extended detail with complex structure as data - initializeJsonContact(jsonContact); - QVariantMap variantMap; - QJsonArray array2; - QString expectedStringFromVariantList(QStringLiteral("QStringInVariantList")); - int expectedIntFromVariantList = 5; - array2.append(expectedStringFromVariantList); - array2.append(expectedIntFromVariantList); - variantMap.insert("ItemInt", 1); - variantMap.insert("ItemQString", QString("QStringData")); - variantMap.insert("ItemQVariant", QJsonValue( QString("QStringInQVariant")).toVariant()); - variantMap.insert("ItemQVariantList", array2.toVariantList() ); - jsonData.insert("QStringItem", QString("Content for QStringItem.")); - jsonData.insert("arrayInMap", QJsonObject::fromVariantMap(variantMap)); - jsonContact.insert("complexObjectDetail", jsonData); - QVERIFY(converter.toQContact(jsonContact, &contact, m_partitionName)); - detail = contact.detail(QContactExtendedDetail::Type); - extendedDetail = static_cast<QContactExtendedDetail*>(&detail); - QCOMPARE(extendedDetail->name(), QString("complexObjectDetail")); - extendedDetailItems = QJsonObject::fromVariantMap(extendedDetail->data().toMap()); - QCOMPARE(extendedDetailItems.value("QStringItem").toString(), QString("Content for QStringItem.")); - QJsonObject returnedObject = extendedDetailItems.value("arrayInMap").toObject(); - QCOMPARE(returnedObject.value("ItemInt").toVariant().toInt(), 1); - QCOMPARE(returnedObject.value("ItemQString").toString(), QString("QStringData")); - QCOMPARE(returnedObject.value("ItemQVariant").toString(), QString("QStringInQVariant")); - QCOMPARE(returnedObject.value("ItemQVariantList").toVariant().toList().size(), array2.size()); - QCOMPARE(returnedObject.value("ItemQVariantList").toVariant().toList().at(0).toString(), expectedStringFromVariantList); - QCOMPARE(returnedObject.value("ItemQVariantList").toVariant().toList().at(1).toInt(), expectedIntFromVariantList); - // cleanup - contact.clearDetails(); - jsonData = QJsonObject(); -} - - -void tst_QcontactJsondbConverter::toQContactsTest() -{ - QList<QJsonObject> contacts; - // create bunch of contacts and convert those - for(int i = 1; i < 10; ++i) { - QJsonObject contact; - QJsonObject phoneObject; - QJsonObject emailObject; - // add name field - initializeJsonContact(contact, i); - // add phone number - phoneObject.insert("value", QString("050765432") + QString().setNum(i)); - phoneObject.insert("subType", QString("home")); - QJsonArray phones; - phones.append(phoneObject); - contact.insert("phones", phones); - // add email address - emailObject.insert("value", QString().setNum(i) + "john@doe.com"); - emailObject.insert("subType", QString("home")); - QJsonArray emails; - emails.append(emailObject); - contact.insert("emails", emails); - contacts.append(contact); - } - QContactJsonDbConverter converter; - QContactJsonDbEngine engine; - QContactManager::Error error; - QList<QContact> qcontacts; - QContact qcontact; - QContactDetail detail; - QString number; - // convert - QVERIFY(converter.toQContacts(contacts, qcontacts, error, m_partitionName)); - QCOMPARE(error, QContactManager::NoError); - QCOMPARE(qcontacts.size(), contacts.size()); - int i = 1; - foreach(qcontact, qcontacts) { - number = QString().setNum(i++); - detail = qcontact.detail(QContactName::Type); - QVERIFY(!detail.isEmpty()); - QContactName* name = static_cast<QContactName*>(&detail); - QVERIFY(name != NULL); - QCOMPARE(name->firstName(), "John" + number); - QCOMPARE(name->lastName(), "Doe" + number); - QCOMPARE(name->middleName(), "Tom" + number); - detail = qcontact.detail(QContactPhoneNumber::Type); - QVERIFY(!detail.isEmpty()); - QContactPhoneNumber* phone = static_cast<QContactPhoneNumber*>(&detail); - QVERIFY(phone != NULL); - QCOMPARE(phone->number(), "050765432" + number); - detail = qcontact.detail(QContactEmailAddress::Type); - QVERIFY(!detail.isEmpty()); - QContactEmailAddress* email = static_cast<QContactEmailAddress*>(&detail); - QVERIFY(email != NULL); - QCOMPARE(email->emailAddress(), number + "john@doe.com"); - } -} - -void tst_QcontactJsondbConverter::toJsonContactTest() -{ - QContactJsonDbConverter converter; - QJsonObject jsonContact; - QContact contact; - QMap<QString, QString> testFields; - - // Test name conversion - QContactName name; - name.setFirstName("John"); - name.setLastName("Doe"); - name.setMiddleName("Tom"); - contact.saveDetail(&name); - QVERIFY(converter.toJsonContact(&jsonContact, contact)); - testFields.insert("firstName", "John"); - testFields.insert("lastName", "Doe"); - testFields.insert("middleName", "Tom"); - // test fields - testJsonDetailItems(jsonContact, QContactJsonDbStr::nameDefinitionName(), testFields); - // cleanup - contact.clearDetails(); - jsonContact = QJsonObject(); - testFields.clear(); - - // Test Gender - QContactGender gender; - gender.setGender(QContactGender::GenderMale); - contact.saveDetail(&gender); - QVERIFY(converter.toJsonContact(&jsonContact, contact)); - testFields.insert("gender", "male"); - - // test fields - testJsonDetailItems(jsonContact, "gender", testFields); - // cleanup - contact.clearDetails(); - jsonContact = QJsonObject(); - testFields.clear(); - - // Test organization - QContactOrganization organization; - organization.setName("ACME"); - organization.setDepartment(QStringList() << "Spy"); - organization.setTitle("Vice President"); - organization.setRole("Superhero"); - organization.setAssistantName("Daisy Duck"); - organization.setLogoUrl(QUrl("http://www.acme.com/logo.jpg")); - QList<int> OrganizationContextList; - OrganizationContextList << QContactDetail::ContextWork; - organization.setContexts(OrganizationContextList); - contact.saveDetail(&organization); - QVERIFY(converter.toJsonContact(&jsonContact, contact)); - testFields.insert("name", "ACME"); - testFields.insert("department", "Spy"); - testFields.insert("title", "Vice President"); - testFields.insert("role", "Superhero"); - testFields.insert("assistantName", "Daisy Duck"); - testFields.insert("logoUrl", "http://www.acme.com/logo.jpg"); - testFields.insert("context", "work"); - // test fields - testJsonDetailItems(jsonContact, "organizations", testFields); - // cleanup - contact.clearDetails(); - jsonContact = QJsonObject(); - testFields.clear(); - - - // Test contact details - // birthday - QContactBirthday birthday; - birthday.setDate(QDate(1979, 11, 22)); - contact.saveDetail(&birthday); - QVERIFY(converter.toJsonContact(&jsonContact, contact)); - testFields.insert("birthday", "1979-11-22"); - // avatar - QContactAvatar avatar; - avatar.setImageUrl(QUrl("http://www.acme.com/logo.jpg")); - contact.saveDetail(&avatar); - testFields.insert("photoUrl", "http://www.acme.com/logo.jpg"); - // ringtone - QContactRingtone ringtone; - ringtone.setAudioRingtoneUrl(QUrl("http://www.acme.com/ring.mp3")); - contact.saveDetail(&ringtone); - testFields.insert("ringtoneUrl", "http://www.acme.com/ring.mp3"); - // nickname - QContactNickname nick; - nick.setNickname("Chupacabra"); - contact.saveDetail(&nick); - testFields.insert("nickname", "Chupacabra"); - // note - QContactNote note; - note.setNote("test note"); - contact.saveDetail(¬e); - testFields.insert("note", "test note"); - // convert - QVERIFY(converter.toJsonContact(&jsonContact, contact)); - // test fields - testJsonDetailItems(jsonContact, "details", testFields); - //cleanup - contact.clearDetails(); - jsonContact = QJsonObject(); - testFields.clear(); - - // email - QContactEmailAddress email; - email.setEmailAddress("john@doe.com"); - email.setContexts(QContactEmailAddress::ContextHome); - contact.saveDetail(&email); - QVERIFY(converter.toJsonContact(&jsonContact, contact)); - testFields.insert("value", "john@doe.com"); - testFields.insert("context", "home"); - testJsonDetailItems(jsonContact, "emails", testFields); - //cleanup - contact.clearDetails(); - jsonContact = QJsonObject(); - testFields.clear(); - - // phone number - QContactPhoneNumber number; - number.setNumber("0507654321"); - QList<int> phoneNumberContextList; - phoneNumberContextList << QContactPhoneNumber::ContextWork; - number.setContexts(phoneNumberContextList); - contact.saveDetail(&number); - QVERIFY(converter.toJsonContact(&jsonContact, contact)); - testFields.insert("value", "0507654321"); - testFields.insert("context", "work"); - testJsonDetailItems(jsonContact, "phones", testFields); - //cleanup - contact.clearDetails(); - jsonContact = QJsonObject(); - testFields.clear(); - //let's try with a phone number containing a few invalid characters - number.setNumber(" +123(45678)90-+++abcdefghijklmnopqrstuvwxyz#*+++++ "); - number.setContexts(phoneNumberContextList); - contact.saveDetail(&number); - QVERIFY(converter.toJsonContact(&jsonContact, contact)); - testFields.insert("value", "+123(45678)90-abcdpw#*"); - testFields.insert("context", "work"); - testJsonDetailItems(jsonContact, "phones", testFields); - //cleanup - contact.clearDetails(); - jsonContact = QJsonObject(); - testFields.clear(); - //let's try with an invalid phone number - number.setNumber(" efghijk\"\"][[[]]] "); - number.setContexts(phoneNumberContextList); - contact.saveDetail(&number); - QVERIFY(!converter.toJsonContact(&jsonContact, contact)); - contact.clearDetails(); - //yet another invalid phone number (too long) - QString tooLongNumber; - for (int i=0; i<100; i++) { - tooLongNumber += QString::number(i/10); - } - number.setNumber(tooLongNumber); - contact.saveDetail(&number); - QVERIFY(!converter.toJsonContact(&jsonContact, contact)); - //cleanup - contact.clearDetails(); - jsonContact = QJsonObject(); - testFields.clear(); - //last but not least empty phone number should be ignored - QString emptyNumber; - number.setNumber(emptyNumber); - contact.saveDetail(&number); - QVERIFY(converter.toJsonContact(&jsonContact, contact)); - QCOMPARE(jsonContact.value("phones").toArray().size(), 0); - //cleanup - contact.clearDetails(); - jsonContact = QJsonObject(); - testFields.clear(); - - - // Test address conversion - QContactAddress address; - address.setCountry("Finland"); - address.setPostcode("33101"); - address.setStreet("PL 347"); - address.setPostOfficeBox("347"); - address.setRegion("Pirkanmaa"); - address.setLocality("Tampere"); - contact.saveDetail(&address); - QVERIFY(converter.toJsonContact(&jsonContact, contact)); - // test fields - testFields.insert("country", "Finland"); - testFields.insert("postOfficeBox", "347"); - testFields.insert("postcode", "33101"); - testFields.insert("locality", "Tampere"); - testFields.insert("region", "Pirkanmaa"); - testFields.insert("street", "PL 347"); - // test fields - testJsonDetailItems(jsonContact, "addresses", testFields); - // cleanup - contact.clearDetails(); - jsonContact = QJsonObject(); - testFields.clear(); - - - // Test url conversion - QContactUrl url; - url.setUrl("http://www.acme.com"); - contact.saveDetail(&url); - QVERIFY(converter.toJsonContact(&jsonContact, contact)); - // test fields - testFields.insert("value", "http://www.acme.com"); - testJsonDetailItems(jsonContact, "urls", testFields); - // cleanup - contact.clearDetails(); - jsonContact = QJsonObject(); - testFields.clear(); - - // Test version conversion - QContactVersion version; - QString sequenceNumberString (QStringLiteral("1")); - QString versionString (QStringLiteral("1234567890")); - QString expectedJsonVersion(sequenceNumberString + "-" + versionString); - QByteArray expectedExtendedVersion(versionString.toLatin1()); - version.setSequenceNumber(1); - version.setExtendedVersion(expectedExtendedVersion); - contact.saveDetail(&version); - QVERIFY(converter.toJsonContact(&jsonContact, contact)); - // test fields - QCOMPARE((jsonContact.value(QContactJsonDbStr::version())).toString(), - expectedJsonVersion); - // cleanup - contact.clearDetails(); - - // extended detail with a simple string as data. - QContactExtendedDetail extendedDetail; - extendedDetail.setName("extendedDetail1"); - extendedDetail.setData("Simple data for an extened detail."); - contact.saveDetail(&extendedDetail); - QVERIFY(converter.toJsonContact(&jsonContact, contact)); - // test size, type and actual field - QCOMPARE((jsonContact.value(QContactJsonDbStr::type())).toString(), QContactJsonDbStr::contactsJsonDbType()); - QCOMPARE((jsonContact.value("extendedDetail1")).toString(), QString("Simple data for an extened detail.")); - // cleanup - contact.clearDetails(); - - // extended detail with QJsonArray as data - QContactExtendedDetail listExtendedDetail; - listExtendedDetail.setName("listExtendedDetail"); - QStringList stringList; - stringList << "QStringInListFirst" <<"QStringInListSecond"; - QJsonArray extendedDetailListItems = QJsonArray::fromStringList(stringList); - listExtendedDetail.setData(extendedDetailListItems.toVariantList()); - contact.saveDetail(&listExtendedDetail); - QVERIFY(converter.toJsonContact(&jsonContact, contact)); - QCOMPARE(jsonContact.value(QContactJsonDbStr::type()).toString(), QContactJsonDbStr::contactsJsonDbType()); - QJsonArray convertedVariantList = jsonContact.value("listExtendedDetail").toArray(); - QCOMPARE(convertedVariantList.count(),2); - QCOMPARE(convertedVariantList.at(0).toString(), QString("QStringInListFirst")); - QCOMPARE(convertedVariantList.at(1).toString(), QString("QStringInListSecond")); - // cleanup - contact.clearDetails(); - - // extended detail with a complex variantmap data - QContactExtendedDetail complexExtendedDetail; - complexExtendedDetail.setName("complexExtendedDetail"); - QVariantMap variantMap; - variantMap.insert("mapItemInt", 1); - variantMap.insert("mapItemQString", QString("QStringItem")); - variantMap.insert("mapItemVariant", QVariant(QString("QStringItemInVariant"))); - variantMap.insert("mapItemVariantList", QVariantList() << QString("QStringItemInVariantList") - << QVariant(5) - << QString("AnotherQStringItemInVariantList")); - complexExtendedDetail.setData(variantMap); - contact.saveDetail(&complexExtendedDetail); - initializeJsonContact(jsonContact); - QVERIFY(converter.toJsonContact(&jsonContact, contact)); - // test size, type and actual extended detail fields - QCOMPARE(jsonContact.size(), 3); - QCOMPARE(jsonContact.value(QContactJsonDbStr::type()).toString(), QContactJsonDbStr::contactsJsonDbType()); - QJsonObject convertedObject = jsonContact.value("complexExtendedDetail").toObject(); - QCOMPARE( convertedObject.value("mapItemInt").toVariant().toInt(), 1); - QCOMPARE( convertedObject["mapItemQString"].toString(),QString("QStringItem")); - QCOMPARE( convertedObject["mapItemVariant"].toString(),QString("QStringItemInVariant")); - QJsonArray jsonArray = convertedObject.value("mapItemVariantList").toArray(); - QCOMPARE( jsonArray.at(0).toString(), QString("QStringItemInVariantList")); - QCOMPARE( jsonArray.at(1).toVariant().toInt(), 5); - QCOMPARE( jsonArray.at(2).toString(), QString("AnotherQStringItemInVariantList")); - // cleanup - contact.clearDetails(); - jsonContact = QJsonObject(); -} - -void tst_QcontactJsondbConverter::updateContextsTest() -{ - QContactJsonDbConverter converter; - QContactJsonDbEngine engine; - QStringList contexts; - contexts << "home" << "work" << "other"; - QList<int> qcontexts; - qcontexts << QContactDetail::ContextHome - << QContactDetail::ContextWork - << QContactDetail::ContextOther; - QString context; - QContactDetail qdetail; - QJsonObject detail; - int i = 0; - // test every context - foreach(context, contexts) { - detail.insert("value", QString("0507654321")); - detail.insert("context", context); - QVERIFY(converter.updateContexts(detail, &qdetail)); - QVERIFY(qdetail.contexts().size() == 1); - QVERIFY(qdetail.contexts()[0] == qcontexts.at(i++)); - } -} - - -void tst_QcontactJsondbConverter::queryFromRequestTest() -{ - QContactJsonDbConverter converter; - // ContactSaveRequest - // Functionality still missing - - // ContactFetchRequest with different filters - QContactFetchRequest request; - // Contactdetail with field, without value - QContactDetailFilter detailFilter; - detailFilter.setDetailType(QContactName::Type); - request.setFilter(detailFilter); - QString jsonDbQuery; - QVERIFY(converter.queryFromRequest(&request,jsonDbQuery)); - QCOMPARE(jsonDbQuery, - QString("[?_type=\"%1\"][?name exists]").arg(QContactJsonDbStr::contactsJsonDbType())); - jsonDbQuery.clear(); - // Contactdetail with field and value - detailFilter.setDetailType(QContactName::Type, QContactName::FieldFirstName); - detailFilter.setValue("John"); - request.setFilter(detailFilter); - QVERIFY(converter.queryFromRequest(&request,jsonDbQuery)); - QCOMPARE(jsonDbQuery, - QString("[?_type=\"%1\"][?name.firstName=\"John\"]").arg(QContactJsonDbStr::contactsJsonDbType())); - jsonDbQuery.clear(); - // Contactdetail with matchflags - // Contains flag - detailFilter.setMatchFlags(QContactFilter::MatchContains); - request.setFilter(detailFilter); - QVERIFY(converter.queryFromRequest(&request,jsonDbQuery)); - QCOMPARE(jsonDbQuery, - QString("[?_type=\"%1\"][?name.firstName=~\"/*John*/wi\"]").arg(QContactJsonDbStr::contactsJsonDbType())); - jsonDbQuery.clear(); - // Exactly flag - detailFilter.setMatchFlags(QContactFilter::MatchExactly); - request.setFilter(detailFilter); - QVERIFY(converter.queryFromRequest(&request,jsonDbQuery)); - QCOMPARE(jsonDbQuery, - QString("[?_type=\"%1\"][?name.firstName=\"John\"]").arg(QContactJsonDbStr::contactsJsonDbType())); - jsonDbQuery.clear(); - // Starts with flag - detailFilter.setMatchFlags(QContactFilter::MatchStartsWith); - request.setFilter(detailFilter); - QVERIFY(converter.queryFromRequest(&request,jsonDbQuery)); - QCOMPARE(jsonDbQuery, - QString("[?_type=\"%1\"][?name.firstName=~\"/John*/wi\"]").arg(QContactJsonDbStr::contactsJsonDbType())); - jsonDbQuery.clear(); - // Ends with flag - detailFilter.setMatchFlags(QContactFilter::MatchEndsWith); - request.setFilter(detailFilter); - QVERIFY(converter.queryFromRequest(&request,jsonDbQuery)); - QCOMPARE(jsonDbQuery, - QString("[?_type=\"%1\"][?name.firstName=~\"/*John/wi\"]").arg(QContactJsonDbStr::contactsJsonDbType())); - jsonDbQuery.clear(); - - // CaseSensitive flag - detailFilter.setMatchFlags(QContactFilter::MatchCaseSensitive); - request.setFilter(detailFilter); - QVERIFY(converter.queryFromRequest(&request,jsonDbQuery)); - QCOMPARE(jsonDbQuery, - QString("[?_type=\"%1\"][?name.firstName=~\"/John/w\"]").arg(QContactJsonDbStr::contactsJsonDbType())); - jsonDbQuery.clear(); - - // FixedString flag - detailFilter.setMatchFlags(QContactFilter::MatchFixedString); - request.setFilter(detailFilter); - QVERIFY(converter.queryFromRequest(&request,jsonDbQuery)); - QCOMPARE(jsonDbQuery, - QString("[?_type=\"%1\"][?name.firstName=~\"/John/wi/\"]").arg(QContactJsonDbStr::contactsJsonDbType())); - jsonDbQuery.clear(); - - // Multiple flags "MatchFixedString and CaseSensitive" - QContactFilter::MatchFlags flags; - flags = QContactFilter::MatchFixedString; - flags = flags | QContactFilter::MatchCaseSensitive; - detailFilter.setMatchFlags(flags); - request.setFilter(detailFilter); - QVERIFY(converter.queryFromRequest(&request,jsonDbQuery)); - QCOMPARE(jsonDbQuery, - QString("[?_type=\"%1\"][?name.firstName=~\"/John/w/\"]").arg(QContactJsonDbStr::contactsJsonDbType())); - jsonDbQuery.clear(); - - // Multiple flags "MatchFixedString and MatchStartsWith" - flags = QContactFilter::MatchFixedString; - flags = flags | QContactFilter::MatchStartsWith; - detailFilter.setMatchFlags(flags); - request.setFilter(detailFilter); - QVERIFY(converter.queryFromRequest(&request,jsonDbQuery)); - QCOMPARE(jsonDbQuery, - QString("[?_type=\"%1\"][?name.firstName=~\"/John*/wi/\"]").arg(QContactJsonDbStr::contactsJsonDbType())); - jsonDbQuery.clear(); - - // Multiple flags "MatchFixedString and MatchEndsWith" - flags = QContactFilter::MatchFixedString; - flags = flags | QContactFilter::MatchEndsWith; - detailFilter.setMatchFlags(flags); - request.setFilter(detailFilter); - QVERIFY(converter.queryFromRequest(&request,jsonDbQuery)); - QCOMPARE(jsonDbQuery, - QString("[?_type=\"%1\"][?name.firstName=~\"/*John/wi/\"]").arg(QContactJsonDbStr::contactsJsonDbType())); - jsonDbQuery.clear(); - - // Multiple flags "MatchFixedString and MatchContains" - flags = QContactFilter::MatchFixedString; - flags = flags | QContactFilter::MatchContains; - detailFilter.setMatchFlags(flags); - request.setFilter(detailFilter); - QVERIFY(converter.queryFromRequest(&request,jsonDbQuery)); - QCOMPARE(jsonDbQuery, - QString("[?_type=\"%1\"][?name.firstName=~\"/*John*/wi/\"]").arg(QContactJsonDbStr::contactsJsonDbType())); - jsonDbQuery.clear(); - - // Multiple flags "MatchFixedString, MatchStartsWith and MatchCaseSensitive" - flags = QContactFilter::MatchFixedString; - flags = flags | QContactFilter::MatchStartsWith; - flags = flags | QContactFilter::MatchCaseSensitive; - detailFilter.setMatchFlags(flags); - request.setFilter(detailFilter); - QVERIFY(converter.queryFromRequest(&request,jsonDbQuery)); - QCOMPARE(jsonDbQuery, - QString("[?_type=\"%1\"][?name.firstName=~\"/John*/w/\"]").arg(QContactJsonDbStr::contactsJsonDbType())); - jsonDbQuery.clear(); - - // Multiple flags "Starts with and CaseSensitive" - flags = QContactFilter::MatchStartsWith; - flags = flags | QContactFilter::MatchCaseSensitive; - detailFilter.setMatchFlags(flags); - request.setFilter(detailFilter); - QVERIFY(converter.queryFromRequest(&request,jsonDbQuery)); - QCOMPARE(jsonDbQuery, - QString("[?_type=\"%1\"][?name.firstName=~\"/John*/w\"]").arg(QContactJsonDbStr::contactsJsonDbType())); - jsonDbQuery.clear(); - - // Multiple flags "Ends with and CaseSensitive" - flags = QContactFilter::MatchEndsWith; - flags = flags | QContactFilter::MatchCaseSensitive; - detailFilter.setMatchFlags(flags); - request.setFilter(detailFilter); - QVERIFY(converter.queryFromRequest(&request,jsonDbQuery)); - QCOMPARE(jsonDbQuery, - QString("[?_type=\"%1\"][?name.firstName=~\"/*John/w\"]").arg(QContactJsonDbStr::contactsJsonDbType())); - jsonDbQuery.clear(); - - // Multiple flags "Contains and CaseSensitive" - flags = QContactFilter::MatchContains; - flags = flags | QContactFilter::MatchCaseSensitive; - detailFilter.setMatchFlags(flags); - request.setFilter(detailFilter); - QVERIFY(converter.queryFromRequest(&request,jsonDbQuery)); - QCOMPARE(jsonDbQuery, - QString("[?_type=\"%1\"][?name.firstName=~\"/*John*/w\"]").arg(QContactJsonDbStr::contactsJsonDbType())); - jsonDbQuery.clear(); - - // Detail range filtering - // Functionality still missing - - // contactId filtering - QContactIdFilter idFilter; - QUuid filterUuid("123"); - QString expectedUuid = filterUuid.toString(); - QContactJsonDbId *engineId = new QContactJsonDbId(filterUuid, QContactAbstractRequest::UserDataStorage); - QContactId testId (engineId); - QList<QContactId> ids; - ids.append(testId); - idFilter.setIds(ids); - request.setFilter(idFilter); - QVERIFY(converter.queryFromRequest(&request,jsonDbQuery)); - QCOMPARE(jsonDbQuery, - QString("[?_type=\"%1\"][?_uuid in [\"" + expectedUuid + "\"]]").arg(QContactJsonDbStr::contactsJsonDbType())); - jsonDbQuery.clear(); - - // Sortings - QContactSortOrder sort; - // Sort by firstname, descending - sort.setDetailType(QContactName::Type, QContactName::FieldFirstName); - sort.setDirection(Qt::DescendingOrder); - request.setSorting(QList<QContactSortOrder>() << sort); - QVERIFY(converter.queryFromRequest(&request,jsonDbQuery)); - QCOMPARE(jsonDbQuery, - QString("[?_type=\"%1\"][?_uuid in [\"" + expectedUuid + "\"]][\\name.firstName]").arg(QContactJsonDbStr::contactsJsonDbType())); - jsonDbQuery.clear(); - // Sort by lastname, ascending - sort.setDetailType(QContactName::Type, QContactName::FieldLastName); - sort.setDirection(Qt::AscendingOrder); - request.setSorting(QList<QContactSortOrder>() << sort); - QVERIFY(converter.queryFromRequest(&request,jsonDbQuery)); - QCOMPARE(jsonDbQuery, - QString("[?_type=\"%1\"][?_uuid in [\"" + expectedUuid + "\"]][/name.lastName]").arg(QContactJsonDbStr::contactsJsonDbType())); - jsonDbQuery.clear(); -} - - -void tst_QcontactJsondbConverter::convertCompoundFilterTest() -{ - QContactJsonDbConverter converter; - - // prepare ContactId filter - QContactIdFilter idFilter; - QUuid filterUuid("123"); - QString expectedUuid = filterUuid.toString(); - QContactJsonDbId *engineId = new QContactJsonDbId(filterUuid, QContactAbstractRequest::UserDataStorage); - QContactId testId (engineId); - QList<QContactId> ids; - ids.append(testId); - idFilter.setIds(ids); - - //prepare detail filter - QContactDetailFilter detailFilter; - detailFilter.setDetailType(QContactName::Type, QContactName::FieldFirstName); - detailFilter.setValue("John"); - - //prepare Intersection of contactIdFilter and detailFilter - QContactIntersectionFilter isf; - isf.append(detailFilter); - isf.append(idFilter); - - // now convert the Intersection Filter to Jsondb query - QContactFilter filter(isf); - QString filterStr; - QVERIFY(converter.compoundFilterToJsondbQuery(filter,filterStr)); - QCOMPARE(filterStr, - QString("[?name.firstName=\"John\"][?_uuid in [\"" + expectedUuid + "\"]]")); - filterStr.clear(); -} - - -void tst_QcontactJsondbConverter::convertSortOrderTest() -{ - // Functionality still missing -} - -void tst_QcontactJsondbConverter::contactIdToUuidTest() -{ - QContactJsonDbConverter converter; - QUuid uuid("123"); - QContactJsonDbId *engineId = new QContactJsonDbId(uuid, QContactAbstractRequest::UserDataStorage); - QContactId qid(engineId); - QString jsonUuid; - jsonUuid = converter.contactIdToUuid(qid); - QCOMPARE(jsonUuid, uuid.toString()); -} - -void tst_QcontactJsondbConverter::testJsonDetailItems(const QJsonObject& values, const QString& extractField, - const QMap<QString, QString>& fields, bool testSize) -{ - // result should be type field and value field - QCOMPARE(values.size(), 2); - QCOMPARE(values.value(QContactJsonDbStr::type()).toString(), QContactJsonDbStr::contactsJsonDbType()); - // extract data values - QJsonObject jsonTmp; - - if (values.value(extractField).isArray()) { - QJsonArray array = values.value(extractField).toArray(); - jsonTmp = array[0].toObject(); - } else { - jsonTmp = values.value(extractField).toObject(); - } - // extract data should have as many fields as compared data - if(testSize) - QCOMPARE(jsonTmp.size(), fields.size()); - QMapIterator<QString, QString> i(fields); - while(i.hasNext()) { - i.next(); - QCOMPARE(jsonTmp.value(i.key()).toString(), i.value()); - } -} - -void tst_QcontactJsondbConverter::initializeJsonContact(QJsonObject& jsonContact, unsigned int numbering) -{ - jsonContact = QJsonObject(); - jsonContact.insert(QContactJsonDbStr::type(), QContactJsonDbStr::contactsJsonDbType()); - jsonContact.insert(QContactJsonDbStr::uuid(), QString("123")); - QJsonObject jsonData; - QString number(""); - if(numbering > 0) { - number = QString().setNum(numbering); - } - jsonData.insert("firstName", QString("John" + number)); - jsonData.insert("lastName", QString("Doe" + number)); - jsonData.insert("middleName", QString("Tom" + number)); - jsonContact.insert(QContactJsonDbStr::nameDefinitionName(), jsonData); -} - -QTEST_APPLESS_MAIN(tst_QcontactJsondbConverter); - -#include "tst_qcontactjsondbconverter.moc" diff --git a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/missingstoragelocations.pro b/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/missingstoragelocations.pro deleted file mode 100644 index affe810f1..000000000 --- a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/missingstoragelocations.pro +++ /dev/null @@ -1,4 +0,0 @@ -TEMPLATE = subdirs - -qtHaveModule(jsondb): SUBDIRS += nosystemstorage nouserdatastorage nostorages - diff --git a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nostorages/nostorages.pro b/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nostorages/nostorages.pro deleted file mode 100644 index 43daec150..000000000 --- a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nostorages/nostorages.pro +++ /dev/null @@ -1,23 +0,0 @@ -include(../../../../auto.pri) - -TARGET = tst_nostorages - -QT += contacts -qtHaveModule(jsondb): QT += jsondb - -SOURCES += tst_nostorages.cpp \ - ../tst_missingstorage.cpp \ - ../../../../../../src/plugins/contacts/jsondb/qcontactjsondbid.cpp - -HEADERS += ../tst_missingstorage.h \ - ../../../../jsondbprocess.h \ - ../../../../../../src/plugins/contacts/jsondb/qcontactjsondbid.h - -INCLUDEPATH += .. -INCLUDEPATH += ../../../.. -INCLUDEPATH += ../../../../../../src/plugins/contacts/jsondb - -OTHER_FILES += partitions.json - - -DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 diff --git a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nostorages/partitions.json b/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nostorages/partitions.json deleted file mode 100644 index 0d4f101c7..000000000 --- a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nostorages/partitions.json +++ /dev/null @@ -1,2 +0,0 @@ -[ -] diff --git a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nostorages/tst_nostorages.cpp b/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nostorages/tst_nostorages.cpp deleted file mode 100644 index e8588ebf0..000000000 --- a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nostorages/tst_nostorages.cpp +++ /dev/null @@ -1,163 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -// This module implements no storage locations related test data for a set of -// test cases shared with other similar modules for cases of no userdata -// storage and no system storage. - -#include "tst_missingstorage.h" - -Q_DECLARE_METATYPE(QContactAbstractRequest::StorageLocations) -Q_DECLARE_METATYPE(QContactManager::Error) - -tst_StoragesLocationsMissing::tst_StoragesLocationsMissing() -{ - QString partitions_json = QFINDTESTDATA("partitions.json"); - QVERIFY2(!partitions_json.isEmpty(), "partitions.json file is missing"); - QVERIFY2(m_jsondbProcess.start(partitions_json), "Failed to start JsonDb process"); -} - -tst_StoragesLocationsMissing::~tst_StoragesLocationsMissing() -{ - m_jsondbProcess.terminate(); -} - -void tst_StoragesLocationsMissing::init() -{ - // Nothing to init for tests in this module. -} - - -void tst_StoragesLocationsMissing::fetchData() -{ - QTest::addColumn<int>("storageLocations"); - QTest::addColumn<QContactManager::Error>("expectedError"); - - QTest::newRow("from user") << int(QContactAbstractRequest::UserDataStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from system") << int(QContactAbstractRequest::SystemStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from both") << int(QContactAbstractRequest::SystemStorage | QContactAbstractRequest::UserDataStorage) - << QContactManager::MissingPlatformRequirementsError; - - QTest::newRow("from invalid") << (0x8) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from invalid with user") << int(0x8 | QContactAbstractRequest::UserDataStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from invalid with system") << int(0x8 | QContactAbstractRequest::SystemStorage) - << QContactManager::InvalidStorageLocationError; -} - -void tst_StoragesLocationsMissing::idData() -{ - QTest::addColumn<QString>("jsonId"); - QTest::addColumn<int>("storageLocation"); - QTest::addColumn<QContactManager::Error>("expectedError"); - - QTest::newRow("from user") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << int(QContactAbstractRequest::UserDataStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from system") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << int(QContactAbstractRequest::SystemStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from invalid") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << (0x8) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("with empty id") << QString() - << (0x0) - << QContactManager::InvalidStorageLocationError; -} - -void tst_StoragesLocationsMissing::idsData() -{ - QTest::addColumn<QString>("jsonId"); - QTest::addColumn<int>("firstStorageLocation"); - QTest::addColumn<int>("secondStorageLocation"); - QTest::addColumn<QContactManager::Error>("expectedError"); - - QTest::newRow("from user") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << int(QContactAbstractRequest::UserDataStorage) - << int(QContactAbstractRequest::UserDataStorage) - << QContactManager::InvalidStorageLocationError; - - - QTest::newRow("from system") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << int(QContactAbstractRequest::SystemStorage) - << int(QContactAbstractRequest::SystemStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from both") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << int(QContactAbstractRequest::UserDataStorage) - << int(QContactAbstractRequest::SystemStorage) - << QContactManager::MissingPlatformRequirementsError; - - QTest::newRow("from invalid") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << (0x8) - << int(QContactAbstractRequest::SystemStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("with empty id") << QString() - << int(QContactAbstractRequest::UserDataStorage) - << int(QContactAbstractRequest::SystemStorage) - << QContactManager::MissingPlatformRequirementsError; -} - -void tst_StoragesLocationsMissing::saveData() -{ - QTest::addColumn<int>("storageLocation"); - QTest::addColumn<QContactManager::Error>("expectedError"); - - QTest::newRow("to user") << int(QContactAbstractRequest::UserDataStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("to system") << int(QContactAbstractRequest::SystemStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("to invalid") << (0x8) - << QContactManager::InvalidStorageLocationError; -} diff --git a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nosystemstorage/nosystemstorage.pro b/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nosystemstorage/nosystemstorage.pro deleted file mode 100644 index 915d54f9c..000000000 --- a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nosystemstorage/nosystemstorage.pro +++ /dev/null @@ -1,21 +0,0 @@ -include(../../../../auto.pri) - -TARGET = tst_nosystemstorage - -QT += contacts -qtHaveModule(jsondb): QT += jsondb - -SOURCES += tst_nosystemstorage.cpp \ - ../tst_missingstorage.cpp \ - ../../../../../../src/plugins/contacts/jsondb/qcontactjsondbid.cpp - -HEADERS += ../tst_missingstorage.h \ - ../../../../jsondbprocess.h \ - ../../../../../../src/plugins/contacts/jsondb/qcontactjsondbid.h - -INCLUDEPATH += .. -INCLUDEPATH += ../../../.. -INCLUDEPATH += ../../../../../../src/plugins/contacts/jsondb - -OTHER_FILES += partitions.json -DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 diff --git a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nosystemstorage/partitions.json b/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nosystemstorage/partitions.json deleted file mode 100644 index b886f8271..000000000 --- a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nosystemstorage/partitions.json +++ /dev/null @@ -1,3 +0,0 @@ -[ - { "name" : "com.nokia.mt.User" } -] diff --git a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nosystemstorage/tst_nosystemstorage.cpp b/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nosystemstorage/tst_nosystemstorage.cpp deleted file mode 100644 index 18d4f9da4..000000000 --- a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nosystemstorage/tst_nosystemstorage.cpp +++ /dev/null @@ -1,172 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -// This module implements no system storage location related test data for a -// set of tests shared with other similar modules for cases of no userdata -// storage and no storages at all. - -#include "tst_missingstorage.h" - -Q_DECLARE_METATYPE(QContactAbstractRequest::StorageLocations) -Q_DECLARE_METATYPE(QContactManager::Error) - -tst_StoragesLocationsMissing::tst_StoragesLocationsMissing() -{ - QString partitions_json = QFINDTESTDATA("partitions.json"); - QVERIFY2(!partitions_json.isEmpty(), "partitions.json file is missing"); - QVERIFY2(m_jsondbProcess.start(partitions_json), "Failed to start JsonDb process"); -} - -tst_StoragesLocationsMissing::~tst_StoragesLocationsMissing() -{ - m_jsondbProcess.terminate(); -} - -void tst_StoragesLocationsMissing::init() -{ - // Make sure all tests in this test case start with an empty userdata storage. - QContactIdFetchRequest idFetchRequest; - idFetchRequest.setManager(m_contactManager); - idFetchRequest.start(); - idFetchRequest.waitForFinished(); - if (!idFetchRequest.ids().isEmpty()) { - QContactRemoveRequest removeRequest; - removeRequest.setManager(m_contactManager); - removeRequest.setContactIds(idFetchRequest.ids()); - removeRequest.start(); - removeRequest.waitForFinished(); - } -} - -void tst_StoragesLocationsMissing::fetchData() -{ - QTest::addColumn<int>("storageLocations"); - QTest::addColumn<QContactManager::Error>("expectedError"); - - QTest::newRow("from user") << int(QContactAbstractRequest::UserDataStorage) - << QContactManager::DoesNotExistError; - - QTest::newRow("from system") << int(QContactAbstractRequest::SystemStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from both") << int(QContactAbstractRequest::SystemStorage | QContactAbstractRequest::UserDataStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from invalid") << (0x8) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from invalid with user") << int(0x8 | QContactAbstractRequest::UserDataStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from invalid with system") << int(0x8 | QContactAbstractRequest::SystemStorage) - << QContactManager::InvalidStorageLocationError; -} - -void tst_StoragesLocationsMissing::idData() -{ - QTest::addColumn<QString>("jsonId"); - QTest::addColumn<int>("storageLocation"); - QTest::addColumn<QContactManager::Error>("expectedError"); - - QTest::newRow("from user") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << int(QContactAbstractRequest::UserDataStorage) - << QContactManager::DoesNotExistError; - - QTest::newRow("from system") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << int(QContactAbstractRequest::SystemStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from invalid") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << (0x8) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("with empty id") << QString() - << (0x0) - << QContactManager::InvalidStorageLocationError; -} - -void tst_StoragesLocationsMissing::idsData() -{ - QTest::addColumn<QString>("jsonId"); - QTest::addColumn<int>("firstStorageLocation"); - QTest::addColumn<int>("secondStorageLocation"); - QTest::addColumn<QContactManager::Error>("expectedError"); - - QTest::newRow("from user") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << int(QContactAbstractRequest::UserDataStorage) - << int(QContactAbstractRequest::UserDataStorage) - << QContactManager::DoesNotExistError; - - QTest::newRow("from system") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << int(QContactAbstractRequest::SystemStorage) - << int(QContactAbstractRequest::SystemStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from both") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << int(QContactAbstractRequest::UserDataStorage) - << int(QContactAbstractRequest::SystemStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from invalid") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << (0x8) - << int(QContactAbstractRequest::SystemStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("with empty id") << QString() - << int(QContactAbstractRequest::UserDataStorage) - << int(QContactAbstractRequest::SystemStorage) - << QContactManager::InvalidStorageLocationError; -} - -void tst_StoragesLocationsMissing::saveData() -{ - QTest::addColumn<int>("storageLocation"); - QTest::addColumn<QContactManager::Error>("expectedError"); - - QTest::newRow("to user") << int(QContactAbstractRequest::UserDataStorage) - << QContactManager::NoError; - - QTest::newRow("to system") << int(QContactAbstractRequest::SystemStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("to invalid") << (0x8) - << QContactManager::InvalidStorageLocationError; -} diff --git a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nouserdatastorage/nouserdatastorage.pro b/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nouserdatastorage/nouserdatastorage.pro deleted file mode 100644 index e35717b7d..000000000 --- a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nouserdatastorage/nouserdatastorage.pro +++ /dev/null @@ -1,21 +0,0 @@ -include(../../../../auto.pri) - -TARGET = tst_nouserdatastorage - -QT += contacts -qtHaveModule(jsondb): QT += jsondb - -SOURCES += tst_nouserdatastorage.cpp \ - ../tst_missingstorage.cpp \ - ../../../../../../src/plugins/contacts/jsondb/qcontactjsondbid.cpp - -HEADERS += ../tst_missingstorage.h \ - ../../../../jsondbprocess.h \ - ../../../../../../src/plugins/contacts/jsondb/qcontactjsondbid.h - -INCLUDEPATH += .. -INCLUDEPATH += ../../../.. -INCLUDEPATH += ../../../../../../src/plugins/contacts/jsondb - -OTHER_FILES += partitions.json -DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 diff --git a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nouserdatastorage/partitions.json b/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nouserdatastorage/partitions.json deleted file mode 100644 index b05adf1c9..000000000 --- a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nouserdatastorage/partitions.json +++ /dev/null @@ -1,3 +0,0 @@ -[ - { "name" : "com.nokia.mt.System" } -] diff --git a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nouserdatastorage/tst_nouserdatastorage.cpp b/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nouserdatastorage/tst_nouserdatastorage.cpp deleted file mode 100644 index 6b21a5999..000000000 --- a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/nouserdatastorage/tst_nouserdatastorage.cpp +++ /dev/null @@ -1,181 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -// This module implements no userdata storage location related test data for -// a set of tests shared with other similar modules for cases of no system -// storage and no storages at all. - -#include "tst_missingstorage.h" - -Q_DECLARE_METATYPE(QContactAbstractRequest::StorageLocations) -Q_DECLARE_METATYPE(QContactManager::Error) - -tst_StoragesLocationsMissing::tst_StoragesLocationsMissing() -{ - QString partitions_json = QFINDTESTDATA("partitions.json"); - QVERIFY2(!partitions_json.isEmpty(), "partitions.json file is missing"); - QVERIFY2(m_jsondbProcess.start(partitions_json), "Failed to start JsonDb process"); -} - -tst_StoragesLocationsMissing::~tst_StoragesLocationsMissing() -{ - m_jsondbProcess.terminate(); -} - -void tst_StoragesLocationsMissing::init() -{ - // Make sure all tests in this test case start with an empty system storage. - QContactIdFetchRequest idFetchRequest; - idFetchRequest.setManager(m_contactManager); - idFetchRequest.setStorageLocations(QContactAbstractRequest::SystemStorage); - idFetchRequest.start(); - idFetchRequest.waitForFinished(); - if (!idFetchRequest.ids().isEmpty()) { - QContactRemoveRequest removeRequest; - removeRequest.setManager(m_contactManager); - removeRequest.setContactIds(idFetchRequest.ids()); - removeRequest.start(); - removeRequest.waitForFinished(); - } -} - -void tst_StoragesLocationsMissing::fetchData() -{ - QTest::addColumn<int>("storageLocations"); - QTest::addColumn<QContactManager::Error>("expectedError"); - - QTest::newRow("from user") << int(QContactAbstractRequest::UserDataStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from system") << int(QContactAbstractRequest::SystemStorage) - << QContactManager::DoesNotExistError; - - QTest::newRow("from both") << int(QContactAbstractRequest::SystemStorage | QContactAbstractRequest::UserDataStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from invalid") << (0x8) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from invalid with user") << int(0x8 | QContactAbstractRequest::UserDataStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from invalid with system") << int(0x8 | QContactAbstractRequest::SystemStorage) - << QContactManager::InvalidStorageLocationError; -} - -void tst_StoragesLocationsMissing::idData() -{ - QTest::addColumn<QString>("jsonId"); - QTest::addColumn<int>("storageLocation"); - QTest::addColumn<QContactManager::Error>("expectedError"); - - QTest::newRow("from user") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << int(QContactAbstractRequest::UserDataStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from system") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << int(QContactAbstractRequest::SystemStorage) - << QContactManager::DoesNotExistError; - - QTest::newRow("from invalid") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << (0x8) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("with empty id") << QString() - << (0x0) - << QContactManager::InvalidStorageLocationError; -} - -void tst_StoragesLocationsMissing::idsData() -{ - QTest::addColumn<QString>("jsonId"); - QTest::addColumn<int>("firstStorageLocation"); - QTest::addColumn<int>("secondStorageLocation"); - QTest::addColumn<QContactManager::Error>("expectedError"); - - QTest::newRow("from user") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << int(QContactAbstractRequest::UserDataStorage) - << int(QContactAbstractRequest::UserDataStorage) - << QContactManager::InvalidStorageLocationError; - - - QTest::newRow("from system") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << int(QContactAbstractRequest::SystemStorage) - << int(QContactAbstractRequest::SystemStorage) - << QContactManager::DoesNotExistError; - - QTest::newRow("from user and system") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << int(QContactAbstractRequest::UserDataStorage) - << int(QContactAbstractRequest::SystemStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from invalid with user") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << (0x8) - << int(QContactAbstractRequest::UserDataStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from invalid with system") << QString("a096c227-fc6f-46ad-89b8-1883fb490a38") - << (0x8) - << int(QContactAbstractRequest::SystemStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("from user and system with an empty id") << QString() - << int(QContactAbstractRequest::UserDataStorage) - << int(QContactAbstractRequest::SystemStorage) - << QContactManager::InvalidStorageLocationError; -} - -void tst_StoragesLocationsMissing::saveData() -{ - QTest::addColumn<int>("storageLocation"); - QTest::addColumn<QContactManager::Error>("expectedError"); - - QTest::newRow("to user") << int(QContactAbstractRequest::UserDataStorage) - << QContactManager::InvalidStorageLocationError; - - QTest::newRow("to system") << int(QContactAbstractRequest::SystemStorage) - << QContactManager::NoError; - - QTest::newRow("to invalid") << (0x8) - << QContactManager::InvalidStorageLocationError; -} - - diff --git a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/tst_missingstorage.cpp b/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/tst_missingstorage.cpp deleted file mode 100644 index f758abced..000000000 --- a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/tst_missingstorage.cpp +++ /dev/null @@ -1,202 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "tst_missingstorage.h" - -Q_DECLARE_METATYPE(QContactAbstractRequest::StorageLocations) -Q_DECLARE_METATYPE(QContactManager::Error) - -void tst_StoragesLocationsMissing::initTestCase() -{ - m_contactManager = new QContactManager("jsondb"); -} - -void tst_StoragesLocationsMissing::cleanupTestCase() -{ - if (m_contactManager) - delete m_contactManager; -} - -QContactManager::Error tst_StoragesLocationsMissing::errorFromManager(QContactAbstractRequest &request, QContactManager *cm) -{ - request.setManager(cm); - request.start(); - request.waitForFinished(); - request.isFinished(); - return request.error(); -} - -void tst_StoragesLocationsMissing::fetch() -{ - QFETCH(int, storageLocations); - QFETCH(QContactManager::Error, expectedError); - - QContactManager *cm = new QContactManager("jsondb"); - - QContactFetchRequest request; - request.setStorageLocations(QContactAbstractRequest::StorageLocations(storageLocations)); - QCOMPARE(errorFromManager(request, cm), expectedError); - - delete cm; -} - -void tst_StoragesLocationsMissing::idFetch() -{ - QFETCH(int, storageLocations); - QFETCH(QContactManager::Error, expectedError); - - QContactManager *cm = new QContactManager("jsondb"); - - QContactIdFetchRequest request; - request.setStorageLocations(QContactAbstractRequest::StorageLocations(storageLocations)); - QCOMPARE(errorFromManager(request, cm), expectedError); - - delete cm; -} - -void tst_StoragesLocationsMissing::fetchById() -{ - QFETCH(QString, jsonId); - QFETCH(int, storageLocation); - QFETCH(QContactManager::Error, expectedError); - - QContactManager *cm = new QContactManager("jsondb"); - - QList<QContactId> contactIds; - QContactEngineId *engineId = new QContactJsonDbId(jsonId , QContactAbstractRequest::StorageLocation(storageLocation)); - contactIds.append(QContactId(engineId)); // QContactId takes the ownership of the pointer. - QContactFetchByIdRequest request; - request.setIds(contactIds); - QCOMPARE(errorFromManager(request, cm), expectedError); - - delete cm; -} - -void tst_StoragesLocationsMissing::fetchByIds() -{ - QFETCH(QString, jsonId); - QFETCH(int, firstStorageLocation); - QFETCH(int, secondStorageLocation); - QFETCH(QContactManager::Error, expectedError); - - QContactManager *cm = new QContactManager("jsondb"); - - QContactEngineId *firstEngineId = new QContactJsonDbId(jsonId , QContactAbstractRequest::StorageLocation(firstStorageLocation)); - QContactEngineId *secondEngineId = new QContactJsonDbId(jsonId , QContactAbstractRequest::StorageLocation(secondStorageLocation)); - - QList<QContactId> contactIds; - contactIds.append(QContactId(firstEngineId)); // QContactId takes the ownership of the pointer. - contactIds.append(QContactId(secondEngineId)); - - QContactFetchByIdRequest request; - request.setIds(contactIds); - QCOMPARE(errorFromManager(request, cm), expectedError); - - delete cm; -} - -void tst_StoragesLocationsMissing::removeById() -{ - QFETCH(QString, jsonId); - QFETCH(int, storageLocation); - QFETCH(QContactManager::Error, expectedError); - - QContactManager *cm = new QContactManager("jsondb"); - - QContactEngineId *engineId = new QContactJsonDbId(jsonId , QContactAbstractRequest::StorageLocation(storageLocation)); - QList<QContactId> contactIds; - contactIds.append(QContactId(engineId)); // QContactId takes the ownership of the pointer. - - QContactRemoveRequest request; - request.setContactIds(contactIds); - QCOMPARE(errorFromManager(request, cm), expectedError); - - delete cm; -} - -void tst_StoragesLocationsMissing::removeByIds() -{ - QFETCH(QString, jsonId); - QFETCH(int, firstStorageLocation); - QFETCH(int, secondStorageLocation); - QFETCH(QContactManager::Error, expectedError); - - QContactManager *cm = new QContactManager("jsondb"); - - QContactEngineId *firstEngineId = new QContactJsonDbId(jsonId , QContactAbstractRequest::StorageLocation(firstStorageLocation)); - QContactEngineId *secondEngineId = new QContactJsonDbId(jsonId , QContactAbstractRequest::StorageLocation(secondStorageLocation)); - - QList<QContactId> contactIds; - contactIds.append(QContactId(firstEngineId)); // QContactId takes the ownership of the pointer. - contactIds.append(QContactId(secondEngineId)); - - QContactRemoveRequest request; - request.setContactIds(contactIds); - QCOMPARE(errorFromManager(request, cm), expectedError); - - delete cm; -} - -QList<QContact> tst_StoragesLocationsMissing::makeTestContactsForSave() -{ - QList<QContact> contacts; - contacts << QContact(); - return contacts; -} - -void tst_StoragesLocationsMissing::save() -{ - QFETCH(int, storageLocation); - QFETCH(QContactManager::Error, expectedError); - - QContactManager *cm = new QContactManager("jsondb"); - - QList<QContact> testContacts = makeTestContactsForSave(); - QContactSaveRequest request; - request.setContacts(testContacts); - request.setStorageLocation(QContactAbstractRequest::StorageLocation(storageLocation)); - QCOMPARE(errorFromManager(request, cm), expectedError); - - delete cm; -} - - -QTEST_MAIN(tst_StoragesLocationsMissing) diff --git a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/tst_missingstorage.h b/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/tst_missingstorage.h deleted file mode 100644 index 0f86cf6e7..000000000 --- a/tests/auto/contacts/qcontactjsondbstoragelocations/missingstoragelocations/tst_missingstorage.h +++ /dev/null @@ -1,111 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef TST_MISSINGSTORAGE_H -#define TST_MISSINGSTORAGE_H - -#include <QtTest/QtTest> -#include <QtGlobal> - -#include <QtContacts/QContact> -#include <QtContacts/QContactAbstractRequest> -#include <QtContacts/QContactFetchRequest> -#include <QtContacts/QContactFetchByIdRequest> -#include <QtContacts/QContactIdFetchRequest> -#include <QtContacts/QContactRemoveRequest> -#include <QtContacts/QContactSaveRequest> -#include <QtContacts/qcontactengineid.h> -#include "qcontactjsondbid.h" - -#include "jsondbprocess.h" - -QTCONTACTS_USE_NAMESPACE - -class tst_StoragesLocationsMissing : public QObject -{ - Q_OBJECT - -public: - tst_StoragesLocationsMissing(); - virtual ~tst_StoragesLocationsMissing(); - -public slots: - void initTestCase(); - void cleanupTestCase(); - void init(); - -private slots: - - void fetch(); - void fetch_data() {fetchData();} - - void idFetch(); - void idFetch_data() {fetchData();} - - void fetchById(); - void fetchById_data() {idData();} - - void fetchByIds(); - void fetchByIds_data() {idsData();} - - void removeById(); - void removeById_data() {idData();} - - void removeByIds(); - void removeByIds_data() {idsData();} - - void save(); - void save_data() {saveData();} - -private: - void fetchData(); - void idData(); - void idsData(); - void saveData(); - - QContactManager::Error errorFromManager(QContactAbstractRequest &request, QContactManager *cm); - QList<QContact> makeTestContactsForSave(); - QContactManager *m_contactManager; - - JsonDbProcess m_jsondbProcess; -}; - -#endif diff --git a/tests/auto/contacts/qcontactjsondbstoragelocations/qcontactjsondbstoragelocations.pro b/tests/auto/contacts/qcontactjsondbstoragelocations/qcontactjsondbstoragelocations.pro deleted file mode 100644 index e83338c73..000000000 --- a/tests/auto/contacts/qcontactjsondbstoragelocations/qcontactjsondbstoragelocations.pro +++ /dev/null @@ -1,3 +0,0 @@ -TEMPLATE = subdirs - -qtHaveModule(jsondb): SUBDIRS += missingstoragelocations diff --git a/tests/auto/contacts/qcontactmanager/qcontactmanager.pro b/tests/auto/contacts/qcontactmanager/qcontactmanager.pro index e02651516..86fd33a7e 100644 --- a/tests/auto/contacts/qcontactmanager/qcontactmanager.pro +++ b/tests/auto/contacts/qcontactmanager/qcontactmanager.pro @@ -1,14 +1,10 @@ include(../../auto.pri) QT += contacts versit contacts-private -qtHaveModule(jsondb) { - QT += jsondb -} SOURCES += tst_qcontactmanager.cpp HEADERS += ../qcontactmanagerdataholder.h -HEADERS += ../../jsondbprocess.h \ - ../qcontactidmock.h +HEADERS += ../qcontactidmock.h OTHER_FILES += lazy.json diff --git a/tests/auto/contacts/qcontactmanager/tst_qcontactmanager.cpp b/tests/auto/contacts/qcontactmanager/tst_qcontactmanager.cpp index 5684fe7ff..8ddd480fb 100644 --- a/tests/auto/contacts/qcontactmanager/tst_qcontactmanager.cpp +++ b/tests/auto/contacts/qcontactmanager/tst_qcontactmanager.cpp @@ -47,7 +47,6 @@ #include <QtContacts> #include "qcontactmanagerdataholder.h" -#include "jsondbprocess.h" #include "qcontactidmock.h" #if defined(USE_VERSIT_PLZ) @@ -120,8 +119,6 @@ private: QContact createContact(QString firstName, QString lastName, QString phoneNumber); void saveContactName(QContact *contact,QContactName *contactName, const QString &name) const; - JsonDbProcess m_jsondbProcess; - QScopedPointer<QContactManagerDataHolder> managerDataHolder; public slots: @@ -309,13 +306,6 @@ tst_QContactManager::~tst_QContactManager() void tst_QContactManager::initTestCase() { - // Start JsonDb daemon if needed - if (QContactManager::availableManagers().contains("jsondb")) { - QString partitions_json = QFINDTESTDATA("partitions.json"); - QVERIFY2(!partitions_json.isEmpty(), "partitions.json file is missing"); - QVERIFY2(m_jsondbProcess.start(partitions_json), "Failed to start JsonDb process"); - } - managerDataHolder.reset(new QContactManagerDataHolder()); /* Make sure these other test plugins are NOT loaded by default */ @@ -328,9 +318,6 @@ void tst_QContactManager::initTestCase() void tst_QContactManager::cleanupTestCase() { managerDataHolder.reset(0); - - if (QContactManager::availableManagers().contains("jsondb")) - m_jsondbProcess.terminate(); } void tst_QContactManager::dumpContactDifferences(const QContact& ca, const QContact& cb) @@ -752,15 +739,8 @@ void tst_QContactManager::ctors() QCOMPARE(em5->managerParameters(), tst_QContactManager_QStringMap()); QCOMPARE(em3.managerParameters(), em6->managerParameters()); // memory engine discards the given params, replaces with id. - // Finally test the platform specific engines are actually the defaults -#if defined(QT_JSONDB_ENABLED) - QCOMPARE(defaultStore, QString("jsondb")); -#elif !defined(QT_NO_JSONDB) - QCOMPARE(defaultStore, QString::fromLatin1("jsondb")); -#else QCOMPARE(defaultStore, QString("invalid")); -#endif } void tst_QContactManager::doDump() @@ -2134,11 +2114,6 @@ void tst_QContactManager::actionPreferences() QFETCH(QString, uri); QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri)); - // early out if the manager doesn't support action preference saving. - if (cm->managerName() == "jsondb") { - QSKIP("Manager does not support action preferences"); - } - // create a sample contact QContactAvatar a; a.setImageUrl(QUrl("test.png")); @@ -2281,9 +2256,6 @@ void tst_QContactManager::selfContactId() // early out if the manager doesn't support self contact id saving QContactId selfContact = cm->selfContactId(); - if (cm->managerName() == "jsondb") - QSKIP("JSONDB backend does not support selfContact at the moment, skipping..."); - // create a new "self" contact and retrieve its Id QVERIFY(cm->error() == QContactManager::NoError || cm->error() == QContactManager::DoesNotExistError); @@ -2342,7 +2314,7 @@ void tst_QContactManager::detailOrders() QFETCH(QString, uri); QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri)); - if (cm->managerName() == "jsondb" || cm->managerName() == "memory") + if (cm->managerName() == "memory") QSKIP("Skipping: This manager does not support detail ordering!"); QContact a; @@ -2475,10 +2447,6 @@ void tst_QContactManager::relationships() QFETCH(QString, uri); QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri)); - if (cm->managerName() == "jsondb") - QSKIP("Jsondb doesnt support relationships"); - - // save some contacts QContact source; QContact dest1, dest2, dest3, dest4; @@ -2501,7 +2469,7 @@ void tst_QContactManager::relationships() // check if manager supports relationships - if (cm->managerName() == "jsondb") { + if (!cm->isRelationshipTypeSupported(QContactRelationship::HasManager())) { // ensure that the operations all fail as required. QContactRelationship r1, r2, r3; r1.setFirst(source); diff --git a/tests/auto/contacts/qcontactmanagerdetails/qcontactmanagerdetails.pro b/tests/auto/contacts/qcontactmanagerdetails/qcontactmanagerdetails.pro index 304a360dd..854253329 100644 --- a/tests/auto/contacts/qcontactmanagerdetails/qcontactmanagerdetails.pro +++ b/tests/auto/contacts/qcontactmanagerdetails/qcontactmanagerdetails.pro @@ -1,9 +1,6 @@ include(../../auto.pri) QT += contacts contacts-private -qtHaveModule(jsondb) { - QT += jsondb -} HEADERS += ../qcontactmanagerdataholder.h diff --git a/tests/auto/contacts/qcontactmanagerdetails/tst_qcontactmanagerdetails.cpp b/tests/auto/contacts/qcontactmanagerdetails/tst_qcontactmanagerdetails.cpp index a024cc13d..4718db001 100644 --- a/tests/auto/contacts/qcontactmanagerdetails/tst_qcontactmanagerdetails.cpp +++ b/tests/auto/contacts/qcontactmanagerdetails/tst_qcontactmanagerdetails.cpp @@ -44,7 +44,6 @@ #include <QtContacts> #include "qcontactmanagerdataholder.h" -#include "jsondbprocess.h" QTCONTACTS_USE_NAMESPACE @@ -76,8 +75,6 @@ private: QScopedPointer<QContactManagerDataHolder> managerDataHolder; - JsonDbProcess m_jsondbProcess; - private slots: void initTestCase(); void cleanupTestCase(); @@ -149,22 +146,12 @@ void tst_QContactManagerDetails::addManagers() void tst_QContactManagerDetails::initTestCase() { - // Start JsonDb daemon if needed - if (QContactManager::availableManagers().contains("jsondb")) { - QString partitions_json = QFINDTESTDATA("partitions.json"); - QVERIFY2(!partitions_json.isEmpty(), "partitions.json file is missing"); - QVERIFY2(m_jsondbProcess.start(partitions_json), "Failed to start JsonDb process"); - } - managerDataHolder.reset(new QContactManagerDataHolder()); } void tst_QContactManagerDetails::cleanupTestCase() { managerDataHolder.reset(0); - - if (QContactManager::availableManagers().contains("jsondb")) - m_jsondbProcess.terminate(); } bool tst_QContactManagerDetails::saveAndLoadContact( QContactManager *cm, QContact &original, QContact &loaded ) @@ -275,17 +262,13 @@ void tst_QContactManagerDetails::testAddress() void tst_QContactManagerDetails::testAnniversary() { QFETCH(QString, uri); - if (uri == "qtcontacts:jsondb:") { - QSKIP("JsonDb backend does not support QContactAnniversary detail!"); - } else { - QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri)); - QContact c; - QContactAnniversary a; - - a.setOriginalDate( QDate(2009,9,9) ); - c.saveDetail( &a ); - saveAndVerifyContact( cm.data(), c ); - } + QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri)); + QContact c; + QContactAnniversary a; + + a.setOriginalDate( QDate(2009,9,9) ); + c.saveDetail( &a ); + saveAndVerifyContact( cm.data(), c ); } void tst_QContactManagerDetails::testAvatar() @@ -384,8 +367,6 @@ void tst_QContactManagerDetails::testNickName() QContact loadedContact; QVERIFY(saveAndLoadContact(cm.data(), originalContact, loadedContact)); - if (uri == "qtcontacts:jsondb:") - QEXPECT_FAIL("", "JsonDb backend does not support QContactNickname properly!", Abort); QCOMPARE(loadedContact.details().count(), originalContact.details().count()); QCOMPARE(loadedContact, originalContact); } @@ -408,18 +389,14 @@ void tst_QContactManagerDetails::testOrganisation() void tst_QContactManagerDetails::testOnlineAccount() { QFETCH(QString, uri); - if (uri == "qtcontacts:jsondb:") { - QSKIP("JsonDb backend does not support QContactOnlineAccount detail!"); - } else { - QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri)); - QContact c; - - QContactOnlineAccount o; - o.setAccountUri( "john@example.com" ); - o.setProtocol(QContactOnlineAccount::ProtocolJabber); - c.saveDetail( &o ); - saveAndVerifyContact( cm.data(), c ); - } + QScopedPointer<QContactManager> cm(QContactManager::fromUri(uri)); + QContact c; + + QContactOnlineAccount o; + o.setAccountUri( "john@example.com" ); + o.setProtocol(QContactOnlineAccount::ProtocolJabber); + c.saveDetail( &o ); + saveAndVerifyContact( cm.data(), c ); } void tst_QContactManagerDetails::testPhoneNumber() @@ -482,8 +459,6 @@ void tst_QContactManagerDetails::testUrl() QContact loadedContact; QVERIFY(saveAndLoadContact(cm.data(), originalContact, loadedContact)); QCOMPARE( loadedContact.details().count(), originalContact.details().count() ); - if (uri == "qtcontacts:jsondb:") - QEXPECT_FAIL("", "JsonDb backend does not support QContactUrl detail properly!", Abort); QCOMPARE( loadedContact, originalContact ); } @@ -512,11 +487,7 @@ void tst_QContactManagerDetails::testEmptyExtendedDetail() // Adding an empty extended detail QContactExtendedDetail emptyDetail; QVERIFY(c.saveDetail(&emptyDetail)); - if (uri == "qtcontacts:jsondb:") { - QSKIP("This manager does not store empty extended details, so skipping empty extended detail test!"); - } else { - saveAndVerifyContact(cm.data(), c); - } + saveAndVerifyContact(cm.data(), c); } void tst_QContactManagerDetails::testExtendedDetail() diff --git a/tests/auto/contacts/qmlcontacts/qmlcontacts.pro b/tests/auto/contacts/qmlcontacts/qmlcontacts.pro index 391bfb405..540543d76 100644 --- a/tests/auto/contacts/qmlcontacts/qmlcontacts.pro +++ b/tests/auto/contacts/qmlcontacts/qmlcontacts.pro @@ -9,15 +9,9 @@ CONFIG += qmltestcase console SOURCES += tst_qmlcontacts.cpp OTHER_FILES += \ - testcases/ContactsJsonDbPartition.qml \ - testcases/ContactsJsonDbPartitions.qml \ - testcases/ContactsJsonDbPartitionTestHelper.qml \ - testcases/ContactsJsonDbTestHelper.qml \ testcases/ContactsSavingTestCase.qml \ testcases/ContactsSignalingTestCase.qml \ testcases/ContactsTestHelper.qml \ - testcases/initialize_jsondb_for_tests.qml \ - testcases/SignalingJsonDb.qml \ testcases/tst_contact_add_detail.qml \ testcases/tst_contact_addresses.qml \ testcases/tst_contact_detail_access.qml \ @@ -41,8 +35,6 @@ OTHER_FILES += \ testcases/tst_contacts_filtering_e2e.qml \ testcases/tst_contact_signals.qml \ testcases/tst_contacts_intersection_filter_e2e.qml \ - testcases/tst_contacts_jsondb_partitions_e2e.qml \ - testcases/tst_contacts_jsondb_to_model_notification_e2e.qml \ testcases/tst_contacts_model_to_model_notification_e2e.qml \ testcases/tst_contacts_remove_contacts_e2e.qml \ testcases/tst_contacts_remove_detail_e2e.qml \ diff --git a/tests/auto/contacts/qmlcontacts/testcases/ContactsJsonDbPartition.qml b/tests/auto/contacts/qmlcontacts/testcases/ContactsJsonDbPartition.qml deleted file mode 100644 index 1393ff019..000000000 --- a/tests/auto/contacts/qmlcontacts/testcases/ContactsJsonDbPartition.qml +++ /dev/null @@ -1,49 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtPim module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -import QtQuick 2.0 -import QtContacts 5.0 - -Item { - property int storageLocation - property string name - property ContactsJsonDbTestHelper testHelper -} diff --git a/tests/auto/contacts/qmlcontacts/testcases/ContactsJsonDbPartitions.qml b/tests/auto/contacts/qmlcontacts/testcases/ContactsJsonDbPartitions.qml deleted file mode 100644 index ba4004456..000000000 --- a/tests/auto/contacts/qmlcontacts/testcases/ContactsJsonDbPartitions.qml +++ /dev/null @@ -1,61 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtPim module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -import QtQuick 2.0 -import QtTest 1.0 -import QtContacts 5.0 - -Item { - property alias userPartition: userPartition - property alias systemPartition: systemPartition - - ContactsJsonDbPartition { - id: userPartition - storageLocation: ContactModel.UserDataStorage - name: "com.nokia.mt.User" - } - - ContactsJsonDbPartition { - id: systemPartition - storageLocation: ContactModel.SystemStorage - name: "com.nokia.mt.System" - } -} diff --git a/tests/auto/contacts/qmlcontacts/testcases/ContactsJsonDbTestCase.qml b/tests/auto/contacts/qmlcontacts/testcases/ContactsJsonDbTestCase.qml deleted file mode 100644 index 02ca319a3..000000000 --- a/tests/auto/contacts/qmlcontacts/testcases/ContactsJsonDbTestCase.qml +++ /dev/null @@ -1,97 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtPim module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -import QtQuick 2.0 -import QtTest 1.0 -import QtContacts 5.0 - -ContactsSavingTestCase { - name: "ContactsJsonDbTestCase" - id: contactsJsonDbTestCase - - Loader { - id: jsonDbPartitions - } - property string jsonDbPartitionForDefaultStorageLocation: jsonDbPartitions.item ? jsonDbPartitions.item.userPartition.name : '' - - Loader { - id: jsonDbTestHelper - } - - property bool jsonDbLoaded: jsonDbPartitions.item != null && jsonDbTestHelper.item != null - - function verifyJsonDbLoaded() - { - if (!jsonDbLoaded) { - skip('Could not load jsondb components') - } - } - - Component.onCompleted: { - jsonDbPartitions.setSource("ContactsJsonDbPartitions.qml") - jsonDbTestHelper.setSource("ContactsJsonDbTestHelper.qml", { "partition": jsonDbPartitionForDefaultStorageLocation }) - } - - function initJsonDbAccess() { - if (jsonDbTestHelper.item) - jsonDbTestHelper.item.initTestHelper(); - } - - function createContactToJsonDb(contact) { - if (jsonDbTestHelper.item) - jsonDbTestHelper.item.createContactToJsonDb(contact); - } - - function removeContactFromJsonDb(contact) { - if (jsonDbTestHelper.item) - jsonDbTestHelper.item.removeContactFromJsonDb(contact); - } - - function updateContactInJsonDb(contact, update) { - if (jsonDbTestHelper.item) - jsonDbTestHelper.item.updateContactInJsonDb(contact, update); - } - - function queryContactsInJsonDb() { - if (jsonDbTestHelper.item) - return jsonDbTestHelper.item.queryContactsInJsonDb(); - } -} diff --git a/tests/auto/contacts/qmlcontacts/testcases/ContactsJsonDbTestHelper.qml b/tests/auto/contacts/qmlcontacts/testcases/ContactsJsonDbTestHelper.qml deleted file mode 100644 index b4d90bc03..000000000 --- a/tests/auto/contacts/qmlcontacts/testcases/ContactsJsonDbTestHelper.qml +++ /dev/null @@ -1,168 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtPim module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -import QtQuick 2.0 -import QtTest 1.0 -import QtContacts 5.0 -import QtJsonDb 1.0 as JsonDb - -// Top-level element should have a default property to allow declaring elements -// inline (jsonDb element below). Component does not, so Item is used here -// although this is not a visual element. -Item { - id: contactsJsonDbTestHelper - - property alias partition: jsonDb.partition - - function initTestHelper() { - logDebug("initTestHelper()"); - createSpyForJsonDb(); - } - - function createContactToJsonDb(contact) { - logDebug("createContactToJsonDb()"); - contact["_type"] = "com.nokia.mt.contacts.Contact"; - jsonDb.createAndSignal(contact); - jsonDbSpy.wait(); - } - - function removeContactFromJsonDb(contact) { - logDebug("removeContactFromJsonDb(): remove contact id " + contact.contactId); - var contactUuid = convertContactIdToJsonDbUuid(contact.contactId); - removeContactWithUuidFromJsonDb(contactUuid); - } - - function removeContactWithUuidFromJsonDb(contactUuid) { - logDebug("removeContactWithUuidFromJsonDb(): contact uuid " + contactUuid); - var query = '[?_type="com.nokia.mt.contacts.Contact"]' + - '[?_uuid="' + contactUuid + '"]'; - jsonDb.queryAndSignal(query); - jsonDbSpy.wait(); - var object = jsonDb.lastResult[0]; - verify(object, "fetched given contact from jsondb"); - jsonDb.removeAndSignal(object); - jsonDbSpy.wait(); - } - - // updates only the first name at the moment! - function updateContactInJsonDb(contact, update) { - var jsonUuid = convertContactIdToJsonDbUuid(contact.contactId); - updateContactWithUuidInJsonDb(jsonUuid, update); - } - - // updates only the first name at the moment! - function updateContactWithUuidInJsonDb(contactUuid, update) { - logDebug("updateContactWithUuidInJsonDb(): contact uuid " + contactUuid); - - var query = '[?_type="com.nokia.mt.contacts.Contact"]' + - '[?_uuid="' + contactUuid + '"]'; - jsonDb.queryAndSignal(query); - jsonDbSpy.wait(); - var object = jsonDb.lastResult[0]; - - object.name.firstName = update.name.firstName; - jsonDb.updateAndSignal(object); - jsonDbSpy.wait(); - } - - function queryContactsInJsonDb() { - logDebug("queryContactsInJsonDb()"); - - var query = '[?_type="com.nokia.mt.contacts.Contact"]'; - jsonDb.queryAndSignal(query); - jsonDbSpy.wait(); - return jsonDb.lastResult; - } - - function emptyContacts() { - logDebug("emptyContacts()"); - var query = '[?_type="com.nokia.mt.contacts.Contact"]'; - jsonDb.queryAndSignal(query); - jsonDbSpy.wait(); - - var contacts = jsonDb.lastResult; - for (var i = 0; i < contacts.length; i++) { - jsonDb.removeAndSignal(contacts[i]); - jsonDbSpy.wait(); - } - } - - function convertJsonDbUuidAndStorageLocationToContactId(contactUuid, storageLocation) { - return 'qtcontacts:jsondb::' + storageLocation + '/' + contactUuid; - } - - function convertContactIdToJsonDbUuid(contactId) { - var idParts = contactId.split(':'); - var engineId = lastItemInArray(idParts); - var engineIdParts = engineId.split('/'); - var jsonDbUuid = lastItemInArray(engineIdParts); - return jsonDbUuid; - } - - function lastItemInArray(array) { - return array[array.length - 1]; - } - - SignalingJsonDb { - id: jsonDb - } - - property SignalSpy jsonDbSpy - - function createSpyForJsonDb() { - logDebug("createSpyForJson()"); - jsonDbSpy = Qt.createQmlObject( - "import QtTest 1.0;" + - "SignalSpy {" + - "}", - contactsJsonDbTestHelper); - jsonDbSpy.target = jsonDb; - jsonDbSpy.signalName = "operationFinished" - } - - property bool debug: false - - function logDebug(message) { - if (debug) - console.log('ContactsJsonDbTestHelper.' + message); - } -} - diff --git a/tests/auto/contacts/qmlcontacts/testcases/ContactsTestConfiguration.qml b/tests/auto/contacts/qmlcontacts/testcases/ContactsTestConfiguration.qml index 5a4a7e6a6..d1325af99 100644 --- a/tests/auto/contacts/qmlcontacts/testcases/ContactsTestConfiguration.qml +++ b/tests/auto/contacts/qmlcontacts/testcases/ContactsTestConfiguration.qml @@ -45,7 +45,6 @@ Item { function getManagerUnderTest() { // Adjust this to run the tests against different manager backends // Supported values: - // "jsondb" // "memory" // "" (selects the default backend) return "memory"; diff --git a/tests/auto/contacts/qmlcontacts/testcases/SignalingJsonDb.qml b/tests/auto/contacts/qmlcontacts/testcases/SignalingJsonDb.qml deleted file mode 100644 index 68c0671d8..000000000 --- a/tests/auto/contacts/qmlcontacts/testcases/SignalingJsonDb.qml +++ /dev/null @@ -1,105 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtPim module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -import QtQuick 2.0 -import QtTest 1.0 -import QtContacts 5.0 -import QtJsonDb 1.0 - -Partition { - id: jsonDb - - property alias partition: jsonDb.name - - function createAndSignal(object) { - logDebug("createAndSignal()"); - create(object, resultCallback); - } - - function removeAndSignal(object) { - logDebug("removeAndSignal()"); - remove(object, resultCallback); - } - - function updateAndSignal(object) { - logDebug("updateAndSignal()"); - update(object, resultCallback); - } - - property variant queryObject - - function queryAndSignal(querystr) { - logDebug("queryAndSignal()"); - queryObject = createQuery(querystr, -1, {}, jsonDb); - queryObject.finished.connect(queryResultCallback); - queryObject.start(); - } - - signal operationFinished - - property variant lastResult: {} - - function resultCallback(error, result) { - if (error) { - console.log("resultCallback(): error: code " + error.code + ": message: " + error.message); - return; - } - - logDebug("resultCallback(): result received: " + JSON.stringify(result)); - lastResult = result.items; - operationFinished(); - } - - function queryResultCallback() { - var result = queryObject.takeResults(); - logDebug("queryResultCallback(): result received: " + JSON.stringify(result)); - lastResult = result; - operationFinished(); - } - - property bool debug: false - - function logDebug(message) { - if (debug) - console.log('SignalingJsonDb.' + message); - } -} - diff --git a/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_details_saving_e2e.qml b/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_details_saving_e2e.qml index 82cf1a3e0..5b8cf0600 100644 --- a/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_details_saving_e2e.qml +++ b/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_details_saving_e2e.qml @@ -93,20 +93,11 @@ ContactsSavingTestCase { contact.addDetail(addressSanitizable) saveAndRefreshContact() var detail = contact.detail(ContactDetail.Address) - if (model.manager == "jsondb") { - compare(detail.street, "Street") - compare(detail.locality, "Locality") - compare(detail.region, "Region") - compare(detail.postcode, "Postcode") - compare(detail.country, "Country") - } else { - // we do not expect other backends to sanitize the input by default - compare(detail.street, " Street") - compare(detail.locality, " Locality") - compare(detail.region, " Region ") - compare(detail.postcode, " Postcode ") - compare(detail.country, " Country ") - } + compare(detail.street, " Street") + compare(detail.locality, " Locality") + compare(detail.region, " Region ") + compare(detail.postcode, " Postcode ") + compare(detail.country, " Country ") } Address { @@ -121,20 +112,13 @@ ContactsSavingTestCase { addressNotSanitizable.postcode = " Postcode " addressNotSanitizable.country = " Country " contact.addDetail(addressNotSanitizable) - if (model.manager == "jsondb") { - // jsondb backend will remove blank spaces and other invalid characters - // resulting this case into an invalid contact object. The model - // should return here a BadArgument error. - saveContactWithError("BadArgument") - } else { - saveAndRefreshContact() - var detail = contact.detail(ContactDetail.Address) - compare(detail.street, " Street") - compare(detail.locality, "") - compare(detail.region, " Vvvvvvvvvveeeeeeeeeerrrrrrrrrryyyyyyyyyylongnameeeeeeeeee ") - compare(detail.postcode, " Postcode ") - compare(detail.country, " Country ") - } + saveAndRefreshContact() + var detail = contact.detail(ContactDetail.Address) + compare(detail.street, " Street") + compare(detail.locality, "") + compare(detail.region, " Vvvvvvvvvveeeeeeeeeerrrrrrrrrryyyyyyyyyylongnameeeeeeeeee ") + compare(detail.postcode, " Postcode ") + compare(detail.country, " Country ") } Address { @@ -220,11 +204,7 @@ ContactsSavingTestCase { contact.addDetail(emailaddressSanitizable) saveAndRefreshContact() var detail = contact.detail(ContactDetail.Email) - if (model.manager == "jsondb") { - compare(detail.emailAddress, "test@qt.nokia.com") - } else { // we do not expect other backends to sanitize the input by default - compare(detail.emailAddress, " test@qt.nokia.com ") - } + compare(detail.emailAddress, " test@qt.nokia.com ") } EmailAddress { @@ -240,13 +220,9 @@ ContactsSavingTestCase { emailaddressNotSanitizable.emailAddress = veryLongEmailAddress emailaddressNotSanitizable.contexts = [ContactDetail.ContextHome] contact.addDetail(emailaddressNotSanitizable) - if (model.manager == "jsondb") { - saveContactWithError("BadArgument") - } else { - saveAndRefreshContact() - var detail = contact.detail(ContactDetail.Email) - compare(detail.emailAddress, veryLongEmailAddress) - } + saveAndRefreshContact() + var detail = contact.detail(ContactDetail.Email) + compare(detail.emailAddress, veryLongEmailAddress) } EmailAddress { @@ -277,8 +253,6 @@ ContactsSavingTestCase { } function test_favorite() { - if (model.manager === "jsondb") - skip("jsondb does not save favorite correctly"); favorite.favorite = true; favorite.index = 1; contact.addDetail(favorite); @@ -331,8 +305,6 @@ ContactsSavingTestCase { compare(detail.middleName, "B.") compare(detail.lastName, "Doe") compare(detail.suffix, "Sr.") - if (model.manager == 'jsondb') - expectFail("", "contexts are not supported at the moment") compare(detail.contexts.length, 1, "contexts length") compare(detail.contexts[0], ContactDetail.ContextHome, "contexts") } @@ -350,19 +322,11 @@ ContactsSavingTestCase { contact.addDetail(nameSanitizable) saveAndRefreshContact() var detail = contact.detail(ContactDetail.Name) - if (model.manager == "jsondb") { - compare(detail.prefix, "Mr.") - compare(detail.firstName, "Matti-Tapio") - compare(detail.middleName, "C.") - compare(detail.lastName, "De Angelis") - compare(detail.suffix, "Sr.") - } else { - compare(detail.prefix, " Mr. ") - compare(detail.firstName, " Matti-Tapio ") - compare(detail.middleName, "C. ") - compare(detail.lastName, " De Angelis") - compare(detail.suffix, "Sr.") - } + compare(detail.prefix, " Mr. ") + compare(detail.firstName, " Matti-Tapio ") + compare(detail.middleName, "C. ") + compare(detail.lastName, " De Angelis") + compare(detail.suffix, "Sr.") } Name { @@ -377,17 +341,13 @@ ContactsSavingTestCase { nameNotSanitizable.lastName = "Vvvvvvvvvveeeeeeeeeerrrrrrrrrryyyyyyyyyylongnameeeeeeeeee" nameNotSanitizable.suffix = "Sr." contact.addDetail(nameNotSanitizable) - if (model.manager == "jsondb") { - saveContactWithError("BadArgument") - } else { - saveAndRefreshContact() - var detail = contact.detail(ContactDetail.Name) - compare(detail.prefix, "") - compare(detail.firstName, "Matti-Tapio") - compare(detail.middleName, "C. ") - compare(detail.lastName, "Vvvvvvvvvveeeeeeeeeerrrrrrrrrryyyyyyyyyylongnameeeeeeeeee") - compare(detail.suffix, "Sr.") - } + saveAndRefreshContact() + var detail = contact.detail(ContactDetail.Name) + compare(detail.prefix, "") + compare(detail.firstName, "Matti-Tapio") + compare(detail.middleName, "C. ") + compare(detail.lastName, "Vvvvvvvvvveeeeeeeeeerrrrrrrrrryyyyyyyyyylongnameeeeeeeeee") + compare(detail.suffix, "Sr.") } Nickname { @@ -411,11 +371,7 @@ ContactsSavingTestCase { contact.addDetail(nicknameSanitizable) saveAndRefreshContact() var detail = contact.detail(ContactDetail.NickName) - if (model.manager == "jsondb") { - compare(detail.nickname, "Dummy") - } else { - compare(detail.nickname, " Dummy ") - } + compare(detail.nickname, " Dummy ") } Nickname { @@ -426,13 +382,9 @@ ContactsSavingTestCase { // If nickname is longer than 50 chars it is invalid and won't be saved nicknameNotSanitizable.nickname = "Vvvvvvvvvveeeeeeeeeerrrrrrrrrryyyyyyyyyylongnameeeeeeeeee" contact.addDetail(nicknameNotSanitizable) - if (model.manager == "jsondb") { - saveContactWithError("BadArgument") - } else { - saveAndRefreshContact() - var detail = contact.detail(ContactDetail.NickName) - compare(detail.nickname, "Vvvvvvvvvveeeeeeeeeerrrrrrrrrryyyyyyyyyylongnameeeeeeeeee") - } + saveAndRefreshContact() + var detail = contact.detail(ContactDetail.NickName) + compare(detail.nickname, "Vvvvvvvvvveeeeeeeeeerrrrrrrrrryyyyyyyyyylongnameeeeeeeeee") } Note { @@ -456,11 +408,7 @@ ContactsSavingTestCase { contact.addDetail(noteSanitizable) saveAndRefreshContact() var detail = contact.detail(ContactDetail.Note) - if (model.manager == "jsondb") { - compare(detail.note, "Dummy") - } else { - compare(detail.note, " Dummy ") - } + compare(detail.note, " Dummy ") } Note { @@ -475,13 +423,9 @@ ContactsSavingTestCase { } noteNotSanitizable.note = veryLongNote contact.addDetail(noteNotSanitizable) - if (model.manager == "jsondb") { - saveContactWithError("BadArgument") - } else { - saveAndRefreshContact() - var detail = contact.detail(ContactDetail.Note) - compare(detail.note, veryLongNote) - } + saveAndRefreshContact() + var detail = contact.detail(ContactDetail.Note) + compare(detail.note, veryLongNote) } OnlineAccount { @@ -519,17 +463,11 @@ ContactsSavingTestCase { compare(detail.name, "Name") compare(detail.logoUrl, "http://qt.nokia.com") compare(detail.department[0], "Department") - if (model.manager == 'jsondb') - expectFail("", "TODO: location is not working as expected at the moment"); compare(detail.location, "Location") - if (model.manager == 'jsondb') - expectFail("", "TODO: role is not working as expected at the moment"); compare(detail.role, "Role") compare(detail.title, "Title") compare(detail.assistantName, "Assistant name") - if (model.manager == 'jsondb') - expectFail("", "TODO: contexts are not working as expected at the moment"); compare(detail.contexts.length, 1, "contexts length") compare(detail.contexts[0], ContactDetail.ContextHome, "contexts") } @@ -543,11 +481,7 @@ ContactsSavingTestCase { contact.addDetail(organizationSanitizable) saveAndRefreshContact() var detail = contact.detail(ContactDetail.Organization) - if (model.manager == "jsondb") { - compare(detail.name, "Company Name") - } else { - compare(detail.name, " Company Name ") - } + compare(detail.name, " Company Name ") } Organization { @@ -558,13 +492,9 @@ ContactsSavingTestCase { // If any of the organization fields is longer than 50 chars it is invalid, thus the contact won't be saved organizationNotSanitizable.name = "Vvvvvvvvvveeeeeeeeeerrrrrrrrrryyyyyyyyyylongnameeeeeeeeee" contact.addDetail(organizationNotSanitizable) - if (model.manager == "jsondb") { - saveContactWithError("BadArgument") - } else { - saveAndRefreshContact() - var detail = contact.detail(ContactDetail.Organization) - compare(detail.name, "Vvvvvvvvvveeeeeeeeeerrrrrrrrrryyyyyyyyyylongnameeeeeeeeee") - } + saveAndRefreshContact() + var detail = contact.detail(ContactDetail.Organization) + compare(detail.name, "Vvvvvvvvvveeeeeeeeeerrrrrrrrrryyyyyyyyyylongnameeeeeeeeee") } Organization { @@ -608,12 +538,7 @@ ContactsSavingTestCase { compare(detail.number, "1") compare(detail.contexts.length, 1, "contexts length") compare(detail.contexts[0], ContactDetail.ContextHome, "contexts") - if (model.manager == 'jsondb') { - compare(detail.subTypes.length, 1, "jsondb phone number subtypes length") - compare(detail.subTypes[0], phonenumber.subTypes[0]) - } else { - compare(detail.subTypes.length, phonenumber.subTypes.length) - } + compare(detail.subTypes.length, phonenumber.subTypes.length) } PhoneNumber { @@ -644,11 +569,7 @@ ContactsSavingTestCase { contact.addDetail(phonenumberSanitizable) saveAndRefreshContact() var detail = contact.detail(ContactDetail.PhoneNumber) - if (model.manager == "jsondb") - // jsondb backend will remove blank spaces and other invalid characters - compare(detail.number, "+1(234)-56789abcd*#") - else // we do not expect other backends to sanitize the input by default - compare(detail.number, "+1 +(234)-56789abcdef*# ") + compare(detail.number, "+1 +(234)-56789abcdef*# ") compare(detail.subTypes.length, phonenumberSanitizable.subTypes.length) } @@ -664,14 +585,10 @@ ContactsSavingTestCase { contact.addDetail(phonenumberNotSanitizable) var detail - if (model.manager == "jsondb") { - saveContactWithError("BadArgument") - } else { - saveAndRefreshContact() - detail = contact.detail(ContactDetail.PhoneNumber) - compare(detail.number, " efghijk []/>>>>>") - compare(detail.subTypes.length, phonenumberNotSanitizable.subTypes.length) - } + saveAndRefreshContact() + detail = contact.detail(ContactDetail.PhoneNumber) + compare(detail.number, " efghijk []/>>>>>") + compare(detail.subTypes.length, phonenumberNotSanitizable.subTypes.length) } PhoneNumber { @@ -768,10 +685,6 @@ ContactsSavingTestCase { saveAndRefreshContact() var detail = contact.detail(ContactDetail.Version) verify(detail.sequenceNumber != undefined) - if (model.manager == "jsondb") { - compare(detail.sequenceNumber, 1, "sequenceNumber is always 1 for jsondb") - compare(detail.extendedVersion.length, 10, "jsondb extended version field is 10 characters long") - } } // Init & teardown diff --git a/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_extended_detail_e2e.qml b/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_extended_detail_e2e.qml index 91323c6dc..d90641472 100644 --- a/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_extended_detail_e2e.qml +++ b/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_extended_detail_e2e.qml @@ -103,13 +103,7 @@ ContactsSavingTestCase { { var fetchedExtendedDetail = saveAndUpdate(contactForDate); compare(fetchedExtendedDetail.name, "date", "extendedDetail.name"); - if (model.manager == "jsondb") { - // Jsondb backend converts dates to strings in ISO 8601 format containing - // date and time in local time without timezone specified. - compare(fetchedExtendedDetail.data, "2001-08-14T00:00:00", "extendedDetail.data"); - } else { - compare(fetchedExtendedDetail.data, myDate, "extendedDetail.data"); - } + compare(fetchedExtendedDetail.data, myDate, "extendedDetail.data"); } diff --git a/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_intersection_filter_e2e.qml b/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_intersection_filter_e2e.qml index 3e7acb465..46c1080c1 100644 --- a/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_intersection_filter_e2e.qml +++ b/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_intersection_filter_e2e.qml @@ -195,12 +195,6 @@ ContactsSavingTestCase { intersection: [contact1B] }, { - tag: "Intersection filter with empty filter set (manager: jsondb)", - manager: "jsondb", - filters: [], - intersection: [contact1A, contact2A, contact3A, contact1B, contact2B, contact3B] - }, - { tag: "Intersection filter with empty filter set (manager: memory)", manager: "memory", filters: [], diff --git a/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_jsondb_details_saving_e2e.qml b/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_jsondb_details_saving_e2e.qml deleted file mode 100644 index 0d27f6027..000000000 --- a/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_jsondb_details_saving_e2e.qml +++ /dev/null @@ -1,107 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtPim module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -import QtQuick 2.0 -import QtTest 1.0 -import QtContacts 5.0 - -ContactsJsonDbTestCase { - name: "ContactsJsonDbDetailsSavingE2ETests" - id: contactsJsonDbDetailsSavingE2ETests - - ContactModel { - id: model - manager: "jsondb" - autoUpdate: true - } - - // Tests - - Contact { - id: contactWithBirthday - Birthday { - birthday: new Date(2012,0,2) - } - } - - function test_saveBirthday() - { - initTestForModel(model); - - model.saveContact(contactWithBirthday); - waitForContactsChanged(); - - var contacts = queryContactsInJsonDb(); - verify(contacts, "contacts is defined"); - compare(contacts.length, 1, "contact present"); - compare(contacts[0].details.birthday, "2012-01-02", "birthday matches"); - } - - // Init & teardown - - function initTestCase() { - waitForModelToBeReady(model); - cleanupContacts(); - initJsonDbAccess(); - } - - function init() { - verifyJsonDbLoaded(); - cleanupContacts(); - } - - function cleanup() { - cleanupContacts(); - } - - function cleanupTestCase() { - cleanupContacts(); - } - - function waitForModelToBeReady(model) { - initTestForModel(model); - waitUntilContactsChanged(); - } - - function cleanupContacts() { - emptyContacts(model); - } -} diff --git a/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_jsondb_partitions_e2e.qml b/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_jsondb_partitions_e2e.qml deleted file mode 100644 index 06e3cb225..000000000 --- a/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_jsondb_partitions_e2e.qml +++ /dev/null @@ -1,446 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtPim module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -import QtQuick 2.0 -import QtTest 1.0 -import QtContacts 5.0 - -ContactsSavingTestCase { - name: "ContactsJsonDbPartitionsE2ETests" - id: contactsJsonDbPartitionsE2ETests - - property ContactModel model - - function createModel() { - model = Qt.createQmlObject( - 'import QtContacts 5.0;' + - 'ContactModel {' + - 'manager: "jsondb";' + - 'autoUpdate: true;' + - '}', - contactsJsonDbPartitionsE2ETests); - } - - function destroyModel() { - if (model) { - model.autoUpdate = false; - model.destroy(); - } - } - - // Partitions under test - - Loader { - id: jsonDbPartitions - source: 'ContactsJsonDbPartitions.qml' - } - - property var defaultPartition: jsonDbPartitions.item ? jsonDbPartitions.item.userPartition : undefined - property var testPartition: jsonDbPartitions.item ? jsonDbPartitions.item.systemPartition : undefined - - // Tests - - Contact { - id: contactInTheDefaultPartition - Name { - firstName: "contactInTheDefaultPartition" - } - } - - function test_fetchContactWithoutSpecifyingPartition() - { - createAndInitModelForPartition(); // does not set partition - - createContactToPartition({name: {firstName: "contactFromDefaultPartition"}}, defaultPartition); - waitForContactsChanged(); - - compare(model.contacts.length, 1, "model has a contact"); - compare(model.contacts[0].name.firstName, "contactFromDefaultPartition", "detail values match"); - } - - function test_fetchContactFromTheDefaultPartitionWhenThereAreContactsInAnotherPartition() - { - createAndInitModelForPartition(defaultPartition); - - // create a contact to the other partition (does not change the model) - listenToContactsChanged(); - createContactToPartition({}, testPartition); - verifyNoContactsChangedReceived(); - - // create a contact to and fetch it from the default partition - createContactToPartition({name: {firstName: "contactFromDefaultPartition"}}, defaultPartition); - waitForContactsChanged(); - - compare(model.contacts.length, 1, "model has a contact"); - compare(model.contacts[0].name.firstName, "contactFromDefaultPartition", "detail values match"); - } - - function test_fetchContactsToModelFromGivenPartition() { - createAndInitModelForPartition(testPartition); - - createContactToPartition({name: {firstName: "contactFromGivenPartition"}}, testPartition); - waitForContactsChanged(); - - compare(model.contacts.length, 1, "model has a contact"); - compare(model.contacts[0].name.firstName, "contactFromGivenPartition", "detail values match"); - } - - function test_createNewContactAndSaveItToDefaultPartition() { - createAndInitModelForPartition(defaultPartition); - - model.saveContact(contactInTheDefaultPartition); - waitForContactsChanged(); - - var contacts = queryContactsInPartition(defaultPartition); - verify(contacts, "contacts is defined"); - compare(contacts.length, 1, "partition has a contact"); - compare(model.contacts[0].name.firstName, contactInTheDefaultPartition.name.firstName, "detail values match"); - } - - Contact { - id: contactInTheTargetPartition - Name { - firstName: "contactInTheTargetPartition" - } - } - - function test_createNewContactAndSaveItToGivenPartition() { - createAndInitModelForPartition(testPartition); - - model.saveContact(contactInTheTargetPartition, testPartition.storageLocation); - waitForContactsChanged(); - - var contacts = queryContactsInPartition(testPartition); - verify(contacts, "contacts is defined"); - compare(contacts.length, 1, "partition has a contact"); - compare(model.contacts[0].name.firstName, contactInTheTargetPartition.name.firstName, "detail values match"); - } - - function test_createNewContactAndSaveItToPartitionWhichIsNotInTheModel() { - createAndInitModelForPartition(defaultPartition); - - model.saveContact(contactInTheTargetPartition, testPartition.storageLocation); - // the completion of the save does not signal through the model since it does not change - wait(500); - - var contacts = queryContactsInPartition(testPartition); - verify(contacts, "contacts is defined"); - compare(contacts.length, 1, "partition has a contact"); - compare(contacts[0].name.firstName, contactInTheTargetPartition.name.firstName, "detail values match"); - } - - function test_removeContactFromGivenPartition() { - createAndInitModelForPartition(testPartition); - - createContactToPartition({name: {firstName: "contactToBeRemoved"}}, testPartition); - waitForContactsChanged(); - compare(model.contacts.length, 1, "guard: model has a contact"); - - model.removeContact(model.contacts[0].contactId); - waitForContactsChanged(); - - var contacts = queryContactsInPartition(testPartition); - verify(contacts, "contacts is is defined"); - compare(contacts.length, 0, "partition is empty"); - } - - function test_fetchContactFromGivenPartitionChangeItAndSaveBackToTheSamePartition() { - createAndInitModelForPartition(testPartition); - - createContactToPartition({name: {firstName: "contactToBeChanged"}}, testPartition); - waitForContactsChanged(); - compare(model.contacts.length, 1, "guard: model has a contact"); - - var contact = model.contacts[0]; - var newFirstName = "contactWithNewFirstName"; - contact.name.firstName = newFirstName; - model.saveContact(contact); - waitForContactsChanged(); - - var contacts = queryContactsInPartition(testPartition); - compare(contacts.length, 1, "partition has a contact"); - compare(model.contacts[0].name.firstName, newFirstName, "first name"); - } - - function test_updateContactInAnotherPartitionDoesNotChangeModel() { - createAndInitModelForPartition(defaultPartition); - - createContactToPartition({name: {firstName: "old"}}, testPartition); - compare(model.contacts.length, 0, "guard: model does not see the contact"); - - var contacts = queryContactsInPartition(testPartition); - compare(contacts.length, 1, "target partition has a contact"); - - listenToContactsChanged(); - updateContactWithUuidInTargetPartition(contacts[0]["_uuid"], {name: {firstName: "new"}}, testPartition); - verifyNoContactsChangedReceived(); - - compare(model.contacts.length, 0, "model has not changed"); - } - - function test_removeContactInAnotherPartitionDoesNotChangeModel() { - createAndInitModelForPartition(defaultPartition); - - createContactToPartition({}, testPartition); - - var contacts = queryContactsInPartition(testPartition); - compare(contacts.length, 1, "target partition has a contact"); - - listenToContactsChanged(); - removeContactWithUuidFromPartition(contacts[0]["_uuid"], testPartition); - verifyNoContactsChangedReceived(); - } - - function test_setStorageLocationToGivenPartitionShouldFetchContacts() { - createAndInitModelForPartition(defaultPartition); - - createContactToPartition({name: {firstName: "contactFromGivenPartition"}}, testPartition); - // the completion of the save does not signal through the model since it does not change - wait(500); - - model.storageLocations = testPartition.storageLocation; - waitForContactsChanged(); - - compare(model.contacts.length, 1, "model has a contact"); - compare(model.contacts[0].name.firstName, "contactFromGivenPartition", "detail values match"); - } - - function test_setIncorrectStorageLocationRaisesError() { - createAndInitModelForPartition(testPartition); - - model.storageLocations = 0; - - compare(model.error, "BadArgument", "error"); - } - - function test_setMultipleStorageLocationsRaisesError() { - createAndInitModelForPartition(testPartition); - - model.storageLocations = ContactModel.UserDataStorage | ContactModel.SystemStorage; - - compare(model.error, "NotSupported", "error"); - } - - function test_fetchContactsFromThePartitionInTheModel() - { - createAndInitModelForPartition(defaultPartition); - - initContactsFetchTestForModel(model); - - createContactToPartition({}, defaultPartition); - waitForContactsChanged(); - compare(model.contacts.length, 1, "guard: model has a contact"); - - var id = model.contacts[0].contactId; - model.fetchContacts([id]); - waitForContactsFetched(); - - compare(lastContactsFetched.length, 1, "contacts length"); - compare(lastContactsFetched[0].contactId, id, "contact id"); - } - - function test_fetchContactsFromPartitionNotInTheModel() - { - createAndInitModelForPartition(defaultPartition); - - initContactsFetchTestForModel(model); - - createContactToPartition({}, testPartition); - // the completion of the save does not signal through the model since it does not change - wait(500); - - var id = queryContactIdOfTheContactOnPartition(testPartition); - model.fetchContacts([id]); - waitForContactsFetched(); - - compare(lastContactsFetched.length, 1, "contacts length"); - compare(lastContactsFetched[0].contactId, id, "contact id"); - } - - function test_fetchContactsFromMultiplePartitions() - { - createAndInitModelForPartition(defaultPartition); - - initContactsFetchTestForModel(model); - - createContactToPartition({}, defaultPartition); - waitForContactsChanged(); - createContactToPartition({}, testPartition); - // the completion of the save does not signal through the model since it does not change - wait(500); - - var id1 = queryContactIdOfTheContactOnPartition(defaultPartition); - var id2 = queryContactIdOfTheContactOnPartition(testPartition); - model.fetchContacts([id1, id2]); - waitForContactsFetched(); - - compare(lastContactsFetched.length, 2, "contacts length"); - compare(lastContactsFetched[0].contactId, id1, "contact id 1"); - compare(lastContactsFetched[1].contactId, id2, "contact id 2"); - } - - property SignalSpy contactsFetchedSpy - property list<Contact> lastContactsFetched - - function onContactsFetched(requestId, fetchedContacts) { - logDebug("onContactsFetched" + ": fetchedContacts " + JSON.stringify(fetchedContacts)); - lastContactsFetched = fetchedContacts; - } - - function initContactsFetchTestForModel(model) { - contactsFetchedSpy = initTestForTargetListeningToSignal(model, "contactsFetched"); - lastContactsFetched = []; - model.contactsFetched.connect(onContactsFetched); - } - - function waitForContactsFetched() { - waitForTargetSignal(contactsFetchedSpy); - } - - // Init & teardown - - function initTestCase() { - initJsonDbAccess(); - } - - function init() { - if (jsonDbTestHelperForDefaultPartition.item == null || jsonDbTestHelperForTestPartition.item == null) - skip('Could not load jsondb components') - - cleanupContacts(); - } - - function cleanup() { - destroyModel(); - cleanupContacts(); - } - - function cleanupTestCase() { - if (jsonDbTestHelperForDefaultPartition.item != null && jsonDbTestHelperForTestPartition.item != null) - cleanupContacts(); - } - - function cleanupContacts() { - emptyContactsInPartition(defaultPartition); - emptyContactsInPartition(testPartition); - } - - // Helpers - - function createAndInitModelForPartition(partition) { - if (partition === defaultPartition) { - createModelForPartition(defaultPartition); - } else if (partition === testPartition) { - createModelForPartition(testPartition); - waitForModelToBeReady(model); // change to another partition - } else if (!partition) { - createModelForPartition(); // does not set partition - } else { - fail("Failed to initialize partition for the model under test.") - } - initTestForModel(model); - } - - function createModelForPartition(partition) { - createModel(); - waitForModelToBeReady(model); - if (partition) - model.storageLocations = partition.storageLocation; - } - - function waitForModelToBeReady(model) { - initTestForModel(model); - waitUntilContactsChanged(); - } - - function emptyContactsInPartition(partition) { - partition.testHelper.emptyContacts(); - } - - function createContactToPartition(contact, partition) { - partition.testHelper.createContactToJsonDb(contact); - } - - function queryContactsInPartition(partition) { - return partition.testHelper.queryContactsInJsonDb(); - } - - function updateContactWithUuidInTargetPartition(contactUuid, update, partition) { - partition.testHelper.updateContactWithUuidInJsonDb(contactUuid, update); - } - - function removeContactWithUuidFromPartition(contactUuid, partition) { - partition.testHelper.removeContactWithUuidFromJsonDb(contactUuid); - } - - function queryContactIdOfTheContactOnPartition(partition) { - var contacts = queryContactsInPartition(partition); - compare(contacts.length, 1, "guard: partition has one contact"); - var uuid = contacts[0]["_uuid"]; - return convertJsonDbUuidOnPartitionToContactId(uuid, partition); - } - - function convertJsonDbUuidOnPartitionToContactId(uuid, partition) { - return partition.testHelper.convertJsonDbUuidAndStorageLocationToContactId(uuid, partition.storageLocation); - } - - Loader { - id: jsonDbTestHelperForDefaultPartition - source: 'ContactsJsonDbTestHelper.qml' - } - - Loader { - id: jsonDbTestHelperForTestPartition - source: 'ContactsJsonDbTestHelper.qml' - } - - function initJsonDbAccess() { - if (jsonDbTestHelperForDefaultPartition.item != null && jsonDbTestHelperForTestPartition.item != null) { - jsonDbTestHelperForDefaultPartition.item.partition = defaultPartition.name; - jsonDbTestHelperForDefaultPartition.item.initTestHelper(); - defaultPartition.testHelper = jsonDbTestHelperForDefaultPartition.item; - - jsonDbTestHelperForTestPartition.item.partition = testPartition.name; - jsonDbTestHelperForTestPartition.item.initTestHelper(); - testPartition.testHelper = jsonDbTestHelperForTestPartition.item; - } - } -} diff --git a/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_jsondb_to_model_notification_e2e.qml b/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_jsondb_to_model_notification_e2e.qml deleted file mode 100644 index 77bbc0e4a..000000000 --- a/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_jsondb_to_model_notification_e2e.qml +++ /dev/null @@ -1,501 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtPim module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -import QtQuick 2.0 -import QtTest 1.0 -import QtContacts 5.0 - -ContactsJsonDbTestCase { - name: "ContactsJsonDbToModelNotificationE2ETests" - id: contactsJsonDbToModelNotificationE2ETests - - property ContactModel model - - function createModel() { - model = Qt.createQmlObject( - 'import QtContacts 5.0;' + - 'ContactModel {' + - 'manager: "jsondb";' + - 'autoUpdate: true;' + - '}', - contactsJsonDbToModelNotificationE2ETests); - } - - function destroyModel() { - model.autoUpdate = false; - model.destroy(); - } - - function test_createContactShouldUpdateModel() - { - initTestForModel(model); - - createContactToJsonDb({}); - - waitForContactsChanged(); - - compare(model.contacts.length, 1, "model has a contact"); - } - - function test_createContactPassesDetailsToModel() - { - initTestForModel(model); - - createContactToJsonDb({name: {firstName: "Test"} - }); - - waitForContactsChanged(); - - verify(model.contacts[0].name, "name exists"); - compare(model.contacts[0].name.firstName, "Test", "first name"); - } - - function test_createContactWhenAutoUpdateIsOff() - { - initTestForModel(model); - model.autoUpdate = false; - - listenToContactsChanged(); - createContactToJsonDb({}); - verifyNoContactsChangedReceived(); - - compare(model.contacts.length, 0, "model should be empty now"); - emptyContacts(model); - } - - Contact { - id: contactToBeRemoved - } - - function test_removeContactShouldUpdateModel() - { - initTestForModel(model); - - model.saveContact(contactToBeRemoved); - waitForContactsChanged(); - - var contact = model.contacts[0]; - verify(contact); - removeContactFromJsonDb(contact); - - waitForContactsChanged(); - - compare(model.contacts.length, 0, "model is empty"); - } - - Contact { - id: contactToBeRemovedWhenAutoUpdateIsOff - } - - function test_removeContactWhenAutoUpdateIsOff() - { - initTestForModel(model); - model.autoUpdate = false; - model.saveContact(contactToBeRemovedWhenAutoUpdateIsOff); - model.update(); - waitForContactsChanged(); - - var contact = model.contacts[0]; - listenToContactsChanged(); - removeContactFromJsonDb(contact); - verifyNoContactsChangedReceived(); - - compare(model.contacts.length, 1, "model has a contact"); - emptyContacts(model); - } - - Contact { - id: contactToBeUpdated - Name { - firstName: "old" - } - } - - function test_updateContactShouldUpdateModel() - { - initTestForModel(model); - - model.saveContact(contactToBeUpdated); - waitForContactsChanged(); - - var contact = model.contacts[0]; - updateContactInJsonDb(contact, {name: {firstName: "new"}}); - - waitForContactsChanged(); - - compare(model.contacts.length, 1, "model is not empty"); - compare(model.contacts[0].name.firstName, "new", "first name"); - } - - Contact { - id: contactToBeUpdatedWhenAutoUpdateIsOff - Name { - firstName: "old" - } - } - - function test_updateContactWhenAutoUpdateIsOff() - { - initTestForModel(model); - model.autoUpdate = false; - model.saveContact(contactToBeUpdatedWhenAutoUpdateIsOff); - model.update(); - waitForContactsChanged(); - - listenToContactsChanged(); - var contact = model.contacts[0]; - updateContactInJsonDb(contact, {name: {firstName: "new"}}); - verifyNoContactsChangedReceived(); - - //model is not updated so the firstName must be still the "old" - compare(model.contacts[0].name.firstName, "old", "first name"); - emptyContacts(model); - } - - SortOrder { - id: sortByFirstName - detail: ContactDetail.Name - field: Name.FirstName - direction: Qt.AscendingOrder - } - - Contact { - id: sorting_creating_secondContact - Name { - firstName: "B" - } - } - - function test_createContactSortsContactsInModel() - { - initTestForModel(model); - model.sortOrders = [sortByFirstName]; - waitForContactsChanged(); - - model.saveContact(sorting_creating_secondContact); - waitForContactsChanged(); - createContactToJsonDb({name: {firstName: "A"}}); - waitForContactsChanged(); - - compare(model.contacts.length, 2, "contacts length"); - compare(model.contacts[0].name.firstName, "A", "first contact"); - compare(model.contacts[1].name.firstName, "B", "second contact"); - } - - Contact { - id: sorting_updating_firstContact - Name { - firstName: "B" - } - } - - Contact { - id: sorting_updating_secondContact - Name { - firstName: "C" - } - } - - function test_updateContactDetailSortsContactsInModel() - { - initTestForModel(model); - model.sortOrders = [sortByFirstName]; - waitForContactsChanged(); - - model.saveContact(sorting_updating_firstContact); - waitForContactsChanged(); - model.saveContact(sorting_updating_secondContact); - waitForContactsChanged(); - - var contact = model.contacts[1]; - compare(contact.name.firstName, "C", "second contact first name"); - updateContactInJsonDb(contact, {name: {firstName: "A"}}); - - waitForContactsChanged(); - - compare(model.contacts.length, 2, "contacts length"); - compare(model.contacts[0].name.firstName, "A", "first contact"); - compare(model.contacts[1].name.firstName, "B", "second contact"); - } - - Contact { - id: sorting_removing_firstContact - Name { - firstName: "A" - } - } - - Contact { - id: sorting_removing_secondContact - Name { - firstName: "B" - } - } - - Contact { - id: sorting_removing_thirdContact - Name { - firstName: "C" - } - } - - function test_removeContactSortsContactsInModel() - { - initTestForModel(model); - model.sortOrders = [sortByFirstName]; - waitForContactsChanged(); - - model.saveContact(sorting_removing_thirdContact); - waitForContactsChanged(); - model.saveContact(sorting_removing_secondContact); - waitForContactsChanged(); - model.saveContact(sorting_removing_firstContact); - waitForContactsChanged(); - - var contact = model.contacts[1]; - removeContactFromJsonDb(contact); - - waitForContactsChanged(); - - compare(model.contacts.length, 2, "contacts length"); - compare(model.contacts[0].name.firstName, "A", "first contact"); - compare(model.contacts[1].name.firstName, "C", "second contact"); - } - - DetailFilter { - id: filterByFirstName - detail: ContactDetail.Name - field: Name.FirstName - matchFlags: Filter.MatchExactly - } - - function test_createContactMatchingTheFilter() - { - initTestForModel(model); - filterByFirstName.value = "A"; - model.filter = filterByFirstName; - waitForContactsChanged(); - - createContactToJsonDb({name: {firstName: "A"}}); - waitForContactsChanged(); - - compare(model.contacts.length, 1, "contacts length"); - compare(model.contacts[0].name.firstName, "A", "first name"); - } - - function test_createContactNotMatchingTheFilter() - { - initTestForModel(model); - filterByFirstName.value = "A"; - model.filter = filterByFirstName; - waitForContactsChanged(); - - createContactToJsonDb({name: {firstName: "B"}}); - - compare(model.contacts.length, 0, "contacts length"); - } - - Contact { - id: filtering_removing_matchingContact - Name { - firstName: "A" - } - } - - function test_removeContactMatchingTheFilter() - { - initTestForModel(model); - filterByFirstName.value = "A"; - model.filter = filterByFirstName; - waitForContactsChanged(); - - model.saveContact(filtering_removing_matchingContact); - waitForContactsChanged(); - - var contact = model.contacts[0]; - removeContactFromJsonDb(contact); - waitForContactsChanged(); - - compare(model.contacts.length, 0, "contacts length"); - } - - Contact { - id: filtering_removing_nonmatchingContact - Name { - firstName: "B" - } - } - - function test_removeContactNotMatchingTheFilter() - { - initTestForModel(model); - - model.saveContact(filtering_removing_nonmatchingContact); - waitForContactsChanged(); - var id = model.contacts[0].contactId; - - filterByFirstName.value = "A"; - model.filter = filterByFirstName; - waitForContactsChanged(); - - compare(model.contacts.length, 0, "contacts length"); - - var count = spy.count; - removeContactFromJsonDb({contactId: id}); - - wait(500); - compare(spy.count, count, "spy does not receive a signal"); - } - - Contact { - id: filtering_updating_nonmatchingContact - Name { - firstName: "B" - } - } - - function test_updateContactDetailToMatchTheFilter() - { - initTestForModel(model); - - model.saveContact(filtering_updating_nonmatchingContact); - waitForContactsChanged(); - var id = model.contacts[0].contactId; - - filterByFirstName.value = "A"; - model.filter = filterByFirstName; - waitForContactsChanged(); - - compare(model.contacts.length, 0, "model is empty"); - - updateContactInJsonDb({contactId: id}, {name: {firstName: "A"}}); - waitForContactsChanged(); - compare(model.contacts.length, 1, "model is not empty"); - compare(model.contacts[0].name.firstName, "A", "first name"); - } - - Contact { - id: filtering_updating_matchingContact - Name { - firstName: "A" - } - } - - function test_updateContactDetailToNotMatchTheFilter() - { - initTestForModel(model); - - model.saveContact(filtering_updating_matchingContact); - waitForContactsChanged(); - var id = model.contacts[0].contactId; - - filterByFirstName.value = "A"; - model.filter = filterByFirstName; - waitForContactsChanged(); - - compare(model.contacts.length, 1, "model is not empty"); - - updateContactInJsonDb({contactId: id}, {name: {firstName: "B"}}); - waitForContactsChanged(); - compare(model.contacts.length, 0, "model is empty"); - } - - function initTestCase() { - cleanupContacts(); - } - - function cleanupTestCase() { - cleanupContacts(); - } - - function init() { - verifyJsonDbLoaded(); - initJsonDbAccess(); - createModel(); - waitForModelToBeReady(model); - } - - function waitForModelToBeReady(model) { - initTestForModel(model); - waitForContactsChanged(); - } - - function cleanup() { - cleanupContacts(); - destroyModel(); - } - - function cleanupContacts() { - if (!jsonDbLoaded) - return - var modelForCleanup = Qt.createQmlObject( - 'import QtContacts 5.0;' + - 'ContactModel {' + - 'manager: "jsondb";' + - 'autoUpdate: true;' + - '}', - contactsJsonDbToModelNotificationE2ETests); - waitForModelToBeReady(modelForCleanup); - - emptyContacts(modelForCleanup); - - modelForCleanup.autoUpdate = false; - modelForCleanup.destroy(); - } - - function compareContactArrays(actual, expected) { - compare(actual.length, expected.length, "length"); - for (var i = 0; i < expected.length; i++) { - compareContacts(actual[i], expected[i]); - } - } - - function compareContacts(actual, expected) { - if (expected.name) { - compare(actual.name.firstName, expected.name.firstName, 'name.firstName'); - compare(actual.name.lastName, expected.name.lastName, 'name.lastName'); - } - if (expected.email) { - compare(actual.email.emailAddress, expected.email.emailAddress, - 'email.emailAddress'); - } - } -} diff --git a/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_save_contact_e2e.qml b/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_save_contact_e2e.qml index 489df6138..13c57f404 100644 --- a/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_save_contact_e2e.qml +++ b/tests/auto/contacts/qmlcontacts/testcases/tst_contacts_save_contact_e2e.qml @@ -131,11 +131,8 @@ ContactsSavingTestCase { model.saveContact(contactToSaveMultipleTimes); waitUntilContactsChanged(); - // Saving the same contact multiple times currently yields an insertion and then an update - // The tested behavior does not occur - was it specific to jsondb backend? - expectFail('', 'This test does not reflect the current behavior') - compare(model.contacts.length, 2, "contacts.length"); - verify(model.contacts[0].contactId !== model.contacts[1].contactId, "contact ids are different"); + // Saving the same contact multiple times yields an insertion and then an update + compare(model.contacts.length, 1, "contacts.length"); } function test_saveTheSameContactMultipleTimesWithoutWaitingForTheModel() { @@ -146,14 +143,9 @@ ContactsSavingTestCase { model.saveContact(contactToSaveMultipleTimes); waitForContactsChanged(); - if (model.contacts.length < 2) - waitForContactsChanged(); - // Saving the same contact multiple times currently yields an insertion and then an update - // The tested behavior does not occur - was it specific to jsondb backend? - expectFail('', 'This test does not reflect the current behavior') - compare(model.contacts.length, 2, "contacts.length"); - verify(model.contacts[0].contactId !== model.contacts[1].contactId, "contact ids are different"); + // Saving the same contact multiple times yields an insertion and then an update + compare(model.contacts.length, 1, "contacts.length"); } // Init & teardown diff --git a/tests/auto/jsondbprocess.h b/tests/auto/jsondbprocess.h deleted file mode 100644 index c2f76882a..000000000 --- a/tests/auto/jsondbprocess.h +++ /dev/null @@ -1,129 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JSONDBPROCESS_H -#define JSONDBPROCESS_H - -#include <QtTest/QtTest> -#include <QProcess> -#include <QTemporaryDir> -#include <QCoreApplication> -#include <QLibraryInfo> - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -class JsonDbProcess -{ -public: - JsonDbProcess() - { - } - - bool start(const QString &partitionsFilePath = QString(), bool killAllJsonDb = true) { - - if (killAllJsonDb) { - if (system("killall jsondb") != 0) { - qWarning() << Q_FUNC_INFO << "Unable to kill running jsondb instances."; - } - } - - QFileInfo partitionsFileInfo(partitionsFilePath); - // Start new process - QString jsondbPath = QLibraryInfo::location(QLibraryInfo::BinariesPath) + "/jsondb"; - if (!QFileInfo(jsondbPath).exists()) { - qWarning() << Q_FUNC_INFO << "Cannot find JsonDb binaries."; - return false; - } - - QStringList args; - if (!partitionsFilePath.isEmpty()) - args << "-config-path" << partitionsFileInfo.absolutePath(); - args << "-reject-stale-updates"; - m_process.start(jsondbPath, args); - - if (!m_process.waitForStarted()) { - qWarning() << Q_FUNC_INFO << m_process.errorString(); - return false; - } else { - // Wait is needed so we get to know if the process was immediately exited - QTest::qWait(100); - - // The process was immediately exited - if (m_process.state() == QProcess::NotRunning) { - // Maybe older JsonDb version is in use and -config-path argument is invalid? - // TODO: remove this and the above wait later when it's safe - m_process.start(jsondbPath, QStringList() << partitionsFileInfo.absolutePath()); - if (!m_process.waitForStarted()) { - qWarning() << Q_FUNC_INFO << m_process.errorString(); - return false; - } - } - } - - return true; - } - - void terminate() { - if (m_process.state() == QProcess::NotRunning) - return; - - m_process.terminate(); - if (m_process.state() != QProcess::NotRunning && !m_process.waitForFinished()) { - qWarning() << Q_FUNC_INFO << "JsonDb did not terminate cleanly. Killing."; - m_process.kill(); - } - } - -private: - QProcess m_process; - -}; - -#endif // JSONDBPROCESS_H diff --git a/tests/auto/organizer/qmlorganizer/testcases/CheckJsonDb.qml b/tests/auto/organizer/qmlorganizer/testcases/CheckJsonDb.qml deleted file mode 100644 index 258808b00..000000000 --- a/tests/auto/organizer/qmlorganizer/testcases/CheckJsonDb.qml +++ /dev/null @@ -1,106 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtPim module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//TESTED_COMPONENT=src/organizer - -import QtQuick 2.0 -import QtTest 1.0 -import QtJsonDb 1.0 - -Item { - name: "A First thing to run" - id: firstThingie - - // NOTE: Since Organizer jsondb-backend expects to have User- and System-partitions, - // we must ensure they are there before testing. - - signal partitionsCreated - property int creationRequestAmount: 0 - - Partition { - id: systemPartition - } - - JsonDbListModel { - id: partitionModel - query: "[?_type=\"Partition\"]" - roleNames: ["name", "_uuid"] - partition: systemPartition - } - - SignalSpy { - id: partitionsCreatedSpy - target: firstThingie - signalName: "partitionsCreated" - } - - function check_db() { - var neededPartitions = ["com.nokia.mt.System", "com.nokia.mt.User"]; - for (var n=0;n<neededPartitions.length;n++) { - var found = false; - for (var p=0;p<partitionModel.count;p++) { - if (partitionModel.get(p, "name") == neededPartitions[n]) { - found = true; - break; - } - } - if (!found) { - console.log("Partition "+neededPartitions[n]+" not found. Creating it.."); - systemPartition.create({_type :"Partition", name : neededPartitions[n]}, callback); - creationRequestAmount++; - } - } - if (creationRequestAmount) { - partitionsCreatedSpy.wait() - } - } - - function callback(error, meta, response) { - if (error) { - console.log(response.status+" "+response.message); - } else { - creationRequestAmount--; - if (!creationRequestAmount) - partitionsCreated(); - } - } -} - diff --git a/tests/auto/organizer/qmlorganizer/testcases/QOrganizerTestUtility.qml b/tests/auto/organizer/qmlorganizer/testcases/QOrganizerTestUtility.qml index 893ae5eb1..56e4f683d 100644 --- a/tests/auto/organizer/qmlorganizer/testcases/QOrganizerTestUtility.qml +++ b/tests/auto/organizer/qmlorganizer/testcases/QOrganizerTestUtility.qml @@ -148,7 +148,7 @@ TestCase { function getManagerList() { - var testManagers = ["memory", "jsondb"]; + var testManagers = ["memory"]; var model = Qt.createQmlObject( "import QtOrganizer 5.0; OrganizerModel {}" diff --git a/tests/auto/organizer/qmlorganizer/testcases/tst_afirstthingtorun.qml b/tests/auto/organizer/qmlorganizer/testcases/tst_afirstthingtorun.qml deleted file mode 100644 index 2196e2f73..000000000 --- a/tests/auto/organizer/qmlorganizer/testcases/tst_afirstthingtorun.qml +++ /dev/null @@ -1,62 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** This file is part of the QtPim module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, 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, Digia gives you certain additional -** rights. These rights are described in the Digia 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. -** -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -import QtQuick 2.0 -import QtTest 1.0 - -TestCase { - name: "A First thing to run" - id: firstThingie - - Loader { - id: checkJsonDb - source: "CheckJsonDb.qml" - property bool valid: item !== null - function check_db() { - if (valid) item.check_db() - } - } - - function initTestCase() { - checkJsonDb.check_db(); - } -} - diff --git a/tests/auto/organizer/qmlorganizer/testcases/tst_collection.qml b/tests/auto/organizer/qmlorganizer/testcases/tst_collection.qml index 645f22a78..a5f6da428 100644 --- a/tests/auto/organizer/qmlorganizer/testcases/tst_collection.qml +++ b/tests/auto/organizer/qmlorganizer/testcases/tst_collection.qml @@ -321,14 +321,7 @@ TestCase { errorsChangedSpy.signalName = "errorChanged"; organizerModel.saveItem(savedEvent); - if (data.managerToBeTested == "jsondb") { - // jsondb backend supports changing collection of an item, collection id changes - modelChangedSpy.wait(spyWaitDelay); - savedEvent = organizerModel.items[organizerModel.items.length - 1]; - compare(organizerModel.error, "NoError"); - compare(savedEvent.collectionId, savedCollection.collectionId); - } - else if (data.managerToBeTested == "memory") { + if (data.managerToBeTested == "memory") { // memory backend does not support changing collection of an item, collection id does not change errorsChangedSpy.wait(spyWaitDelay); savedEvent = organizerModel.items[organizerModel.items.length - 1]; @@ -447,21 +440,6 @@ TestCase { compare(savedEmptyCollection.description, coll3.description); compare(savedEmptyCollection.color.toString(), coll3.color.toString()); compare(savedEmptyCollection.image.toString(), coll3.image.toString()); - // verify we can see same collections on different OrganizerModel element - if (data.managerToBeTested == "jsondb") { - var organizerModel2 = create_testobject("import QtQuick 2.0\n" - + "import QtOrganizer 5.0\n" - + "OrganizerModel {\n" - + " manager: '" + data.managerToBeTested + "'\n" - + " startPeriod:'2009-01-01'\n" - + " endPeriod:'2012-12-31'\n" - + "}\n"); - var collectionsChangedSpy2 = create_testobject( "import QtTest 1.0 \nSignalSpy {}"); - collectionsChangedSpy2.target = organizerModel2; - collectionsChangedSpy2.signalName = "collectionsChanged" - collectionsChangedSpy2.wait(spyWaitDelay);//needed so that OrganizerModel is initialised properly (collections fetched) - compare(organizerModel.collections.length, organizerModel2.collections.length); - } // fetching existing and non-existing collection var existingCollection = organizerModel.collection(organizerModel.collections[organizerModel.collections.length - 1].collectionId); diff --git a/tests/auto/organizer/qmlorganizer/testcases/tst_detailfieldfilter.qml b/tests/auto/organizer/qmlorganizer/testcases/tst_detailfieldfilter.qml index 59b0fe3f1..6efff373a 100644 --- a/tests/auto/organizer/qmlorganizer/testcases/tst_detailfieldfilter.qml +++ b/tests/auto/organizer/qmlorganizer/testcases/tst_detailfieldfilter.qml @@ -384,13 +384,13 @@ TestCase { filterDetail: Detail.EventTime, filterField: EventTime.FieldStartDateTime, filterValue: new Date("2011-10-23T16:42:00")},//notice, date-object {tag: "exact filter - EventTime.EndDateTime", expectedItemsAmount: 1, filterDetail: Detail.EventTime, filterField: EventTime.FieldEndDateTime, filterValue: new Date("2011-10-23T21:00:00")}, - {tag: "exact filter - EventTime.AllDayEvent", expectedItemsAmount: 1, expectedItemsAmount_Jsondb: 2, + {tag: "exact filter - EventTime.AllDayEvent", expectedItemsAmount: 1, filterDetail: Detail.EventTime, filterField: EventTime.FieldAllDay, filterValue: true}, {tag: "exact filter - TodoTime.StartDateTime", expectedItemsAmount: 1, filterDetail: Detail.TodoTime, filterField: TodoTime.FieldStartDateTime, filterValue: new Date("2010-10-23T15:48:00")}, {tag: "exact filter - TodoTime.DueDateTime", expectedItemsAmount: 1, filterDetail: Detail.TodoTime, filterField: TodoTime.FieldDueDateTime, filterValue: new Date("2010-10-25T15:49:00")}, - {tag: "exact filter - TodoTime.AllDay", expectedItemsAmount: 1, expectedItemsAmount_Jsondb: 2, + {tag: "exact filter - TodoTime.AllDay", expectedItemsAmount: 1, filterDetail: Detail.TodoTime, filterField: TodoTime.FieldAllDay, filterValue: true}, {tag: "exact filter - TodoProgress.Status", expectedItemsAmount: 1, filterDetail: Detail.TodoProgress, filterField: TodoProgress.FieldStatus, filterValue: TodoProgress.InProgress}, @@ -517,12 +517,7 @@ TestCase { applyFilter(data); } - if (managerToBeTested == "jsondb" ) { - // in some cases the stored details are utilising the same field on the backend, which means the amount of matches to be different - compare(organizerModel.items.length, data.expectedItemsAmount_Jsondb ? data.expectedItemsAmount_Jsondb : data.expectedItemsAmount); - } else { - compare(organizerModel.items.length, data.expectedItemsAmount); - } + compare(organizerModel.items.length, data.expectedItemsAmount); organizerModel.destroy(); } @@ -594,7 +589,6 @@ TestCase { {tag: "Filter set, Comment - MatchStartsWith", expectedItemsAmount: 1, filterDetail: Detail.Comment, filterField: Comment.FieldComment, filterValue: "my", matchFlags: Filter.MatchStartsWith, - // jsondb, depends on detail created in previous data set // mem, needs to create again separateDetailCtrStrMemory: "import QtQuick 2.0\n" + "import QtOrganizer 5.0 \n" @@ -604,7 +598,6 @@ TestCase { {tag: "Filter set, Comment - MatchContains", expectedItemsAmount: 1, filterDetail: Detail.Comment, filterField: Comment.FieldComment, filterValue: "great", matchFlags: Filter.MatchContains, - // jsondb, depends on detail created in previous data set // mem, needs to create again separateDetailCtrStrMemory: "import QtQuick 2.0\n" + "import QtOrganizer 5.0 \n" @@ -614,7 +607,6 @@ TestCase { {tag: "Filter set, Comment - MatchEndsWith", expectedItemsAmount: 1, filterDetail: Detail.Comment, filterField: Comment.FieldComment, filterValue: "comment", matchFlags: Filter.MatchEndsWith, - // jsondb, depends on detail created in previous data set // mem, needs to create again separateDetailCtrStrMemory: "import QtQuick 2.0\n" + "import QtOrganizer 5.0 \n" @@ -760,17 +752,6 @@ TestCase { function test_errors(data) { console.log(); - //preparations - // error codes are backend specific, these are tested only for jsondb - if (utility.getManagerList().indexOf("jsondb") === -1) - skip("Cannot run tests for jsondb backend. No plugin available!"); - organizerModel = utility.createModel("jsondb") - - var errorChangedSpy = utility.create_spy(organizerModel, "errorChanged"); - applyFilter(data); - errorChangedSpy.wait(); - - compare(organizerModel.error, "BadArgument"); - organizerModel.destroy(); + // error codes are backend specific - currently untested } } diff --git a/tests/auto/organizer/qmlorganizer/testcases/tst_detailfilter.qml b/tests/auto/organizer/qmlorganizer/testcases/tst_detailfilter.qml index 50134478c..0f89c5591 100644 --- a/tests/auto/organizer/qmlorganizer/testcases/tst_detailfilter.qml +++ b/tests/auto/organizer/qmlorganizer/testcases/tst_detailfilter.qml @@ -389,12 +389,7 @@ TestCase { applyFilter(detailToMatch); } - if (managerToBeTested == "jsondb" ) { - // in some cases the stored details are utilising the same field on the backend, which means the amount of matches to be different - compare(organizerModel.items.length, data.expectedItemsAmount_Jsondb ? data.expectedItemsAmount_Jsondb : data.expectedItemsAmount); - } else { - compare(organizerModel.items.length, data.expectedItemsAmount); - } + compare(organizerModel.items.length, data.expectedItemsAmount); organizerModel.destroy(); } @@ -500,17 +495,6 @@ TestCase { function test_errors(data) { console.log(); - //preparations - // error codes are backend specific, these are tested only for jsondb - if (utility.getManagerList().indexOf("jsondb") === -1) - skip("Cannot run tests for jsondb backend. No plugin available!"); - organizerModel = utility.createModel("jsondb") - var detailToMatch = create_testobject(data.filterDetailCtrStr) - var errorChangedSpy = utility.create_spy(organizerModel, "errorChanged"); - applyFilter(detailToMatch); - errorChangedSpy.wait(); - - compare(organizerModel.error, "BadArgument"); - organizerModel.destroy(); + // error codes are backend specific - currently untested } } diff --git a/tests/auto/organizer/qmlorganizer/testcases/tst_organizeraudiblereminder.qml b/tests/auto/organizer/qmlorganizer/testcases/tst_organizeraudiblereminder.qml index f014e25ae..544c555dd 100644 --- a/tests/auto/organizer/qmlorganizer/testcases/tst_organizeraudiblereminder.qml +++ b/tests/auto/organizer/qmlorganizer/testcases/tst_organizeraudiblereminder.qml @@ -127,21 +127,6 @@ Rectangle { utility.debug("Create and save the detail test", debugFlag); audibleReminderDetail.dataUrl = "http://www.test0.com"; event.setDetail(audibleReminderDetail); - if (managerName == "jsondb") { - // custom fields allowed in JsonDb for audible reminder - // simple test here, since already fully tested in C++ - var extendedDetail = Qt.createQmlObject( - "import QtOrganizer 5.0;" - + "ExtendedDetail {" - + " name: \"reminder\";" - + " data: \{" - + " Qt: \"Everywhere\";" - + " Url: \"http://www.qt-project.org/\";" - + " }" - + "}" - , test); - event.setDetail(extendedDetail); - } model.saveItem(event); //Let's wait for the model to be up-to-date utility.waitModelChange(1); diff --git a/tests/auto/organizer/qmlorganizer/testcases/tst_organizeremailreminder.qml b/tests/auto/organizer/qmlorganizer/testcases/tst_organizeremailreminder.qml index 76bdb1bff..e1da588bb 100644 --- a/tests/auto/organizer/qmlorganizer/testcases/tst_organizeremailreminder.qml +++ b/tests/auto/organizer/qmlorganizer/testcases/tst_organizeremailreminder.qml @@ -104,8 +104,6 @@ Rectangle { //Test all manager backends for (var i = 0; i < list.length; i ++) { var managerName = list[i]; - if (managerName == "jsondb")//jsondb backend does not support email reminder - return; console.log("Email reminder test start! :" + managerName); var model = Qt.createQmlObject( "import QtOrganizer 5.0;" diff --git a/tests/auto/organizer/qmlorganizer/testcases/tst_organizermodel.qml b/tests/auto/organizer/qmlorganizer/testcases/tst_organizermodel.qml index 58eb10bea..009c04c98 100644 --- a/tests/auto/organizer/qmlorganizer/testcases/tst_organizermodel.qml +++ b/tests/auto/organizer/qmlorganizer/testcases/tst_organizermodel.qml @@ -1019,19 +1019,15 @@ TestCase { function test_updateMethodsStartWithAutoupdateFalse() { - if (utility.getManagerList().indexOf("jsondb") === -1) - skip("Cannot run tests for jsondb backend. No plugin available!"); - var organizerModel = Qt.createQmlObject( "import QtOrganizer 5.0;" + "OrganizerModel {" - + " manager: 'jsondb'\n" + + " manager:'memory'\n" + " startPeriod:'2009-01-01'\n" + " endPeriod:'2012-12-31'\n" + " autoUpdate: false\n" + "}" , modelTests); - console.log("## Testing only jsondb-plugin"); var modelChangedSpy = Qt.createQmlObject("import QtTest 1.0; SignalSpy{}", modelTests) modelChangedSpy.target = organizerModel @@ -1040,10 +1036,39 @@ TestCase { collectionsChangedSpy.target = organizerModel collectionsChangedSpy.signalName = "collectionsChanged" - // After test_updateMethods()-test there should be - // 2 items and 2 collections (+ default collection) - // on the jsondb. They're just not visible, since - // autoUpdate is false. + // Add data to this model + var event1 = utility.create_testobject( + "import QtOrganizer 5.0\n" + + "Event {\n" + + " startDateTime: new Date(2011, 12, 7, 11)\n" + + " endDateTime: new Date(2011, 12, 8, 0, 30)\n" + + "}\n", modelTests); + var event2 = utility.create_testobject( + "import QtOrganizer 5.0\n" + + "Event {\n" + + " startDateTime: new Date(2011, 13, 7, 11)\n" + + " endDateTime: new Date(2011, 13, 8, 0, 30)\n" + + "}\n", modelTests); + + var collection1 = utility.create_testobject("import QtQuick 2.0 \n" + + "import QtOrganizer 5.0\n" + + "Collection {\n" + + "id: coll1\n" + + "}\n", modelTests); + + var collection2 = utility.create_testobject("import QtQuick 2.0 \n" + + "import QtOrganizer 5.0\n" + + "Collection {\n" + + "id: coll1\n" + + "}\n", modelTests); + + organizerModel.saveItem(event1); + organizerModel.saveItem(event2); + organizerModel.saveCollection(collection1); + organizerModel.saveCollection(collection2); + + // Now there should be 2 items and 2 collections (+ default collection) + // in the model. They're just not visible, since autoUpdate is false. compare(organizerModel.items.length, 0); compare(organizerModel.collections.length, 0); diff --git a/tests/auto/organizer/qmlorganizer/testcases/tst_organizerrecurrence.qml b/tests/auto/organizer/qmlorganizer/testcases/tst_organizerrecurrence.qml index 73f266706..620691242 100644 --- a/tests/auto/organizer/qmlorganizer/testcases/tst_organizerrecurrence.qml +++ b/tests/auto/organizer/qmlorganizer/testcases/tst_organizerrecurrence.qml @@ -619,7 +619,7 @@ TestCase { return [ { tag: "Invalid recurrence, no matching dates for rule", - managers: ["jsondb", "memory"], + managers: ["memory"], definitions: { "start" : new Date('2012-01-01T14:00:00'), diff --git a/tests/auto/organizer/qmlorganizer/testcases/tst_organizervisualreminder.qml b/tests/auto/organizer/qmlorganizer/testcases/tst_organizervisualreminder.qml index 6eefafe6d..eda2b9678 100644 --- a/tests/auto/organizer/qmlorganizer/testcases/tst_organizervisualreminder.qml +++ b/tests/auto/organizer/qmlorganizer/testcases/tst_organizervisualreminder.qml @@ -107,8 +107,6 @@ Rectangle { //Test all manager backends for (var i = 0; i < list.length; i ++) { var managerName = list[i]; - if (managerName == "jsondb")//jsondb backend does not support visual reminder - return; console.log("VisualReminder test start! :" + managerName); var model = Qt.createQmlObject( "import QtOrganizer 5.0;" @@ -136,21 +134,6 @@ Rectangle { utility.debug("Create and save the detail test", debugFlag); visualReminderDetail.dataUrl = "http://www.test0.com"; visualReminderEvent.setDetail(visualReminderDetail); - if (managerName == "jsondb") { - // custom fields allowed in JsonDb for audible reminder - // simple test here, since already fully tested in C++ - var extendedDetail = Qt.createQmlObject( - "import QtOrganizer 5.0;" - + "ExtendedDetail {" - + " name: \"reminder\";" - + " data: \{" - + " Qt: \"Everywhere\";" - + " Url: \"http://www.qt-project.org/\";" - + " }" - + "}" - , test); - visualReminderEvent.addDetail(extendedDetail); - } model.saveItem(visualReminderEvent); //Let's wait for the model to be up-to-date utility.waitModelChange(1); diff --git a/tests/auto/organizer/qorganizere2e/qorganizere2e.pro b/tests/auto/organizer/qorganizere2e/qorganizere2e.pro index 5b6f1dcec..c17d32d3f 100644 --- a/tests/auto/organizer/qorganizere2e/qorganizere2e.pro +++ b/tests/auto/organizer/qorganizere2e/qorganizere2e.pro @@ -2,8 +2,5 @@ include(../../auto.pri) QT += organizer organizer-private -qtHaveModule(jsondb): QT += jsondb - SOURCES += tst_qorganizere2e.cpp -HEADERS += ../../jsondbprocess.h DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 diff --git a/tests/auto/organizer/qorganizere2e/tst_qorganizere2e.cpp b/tests/auto/organizer/qorganizere2e/tst_qorganizere2e.cpp index 63ab95e2c..ceaaee34e 100644 --- a/tests/auto/organizer/qorganizere2e/tst_qorganizere2e.cpp +++ b/tests/auto/organizer/qorganizere2e/tst_qorganizere2e.cpp @@ -44,7 +44,6 @@ #include <QtOrganizer/qorganizeritemdetails.h> #include <QtOrganizer/qorganizeritems.h> #include <QtOrganizer/qorganizermanager.h> -#include "../../jsondbprocess.h" QTORGANIZER_USE_NAMESPACE @@ -73,19 +72,10 @@ private: // <manager, items> pair for existing items QMap<QString, QList<QOrganizerItem> > existingItems; - - JsonDbProcess jsondbProcess; }; void tst_QOrganizerE2E::initTestCase() { - // Start JsonDb daemon if needed - if (QOrganizerManager::availableManagers().contains("jsondb")) { - QString partitions_json = QFINDTESTDATA("partitions.json"); - QVERIFY2(!partitions_json.isEmpty(), "partitions.json file is missing"); - QVERIFY2(jsondbProcess.start(partitions_json), "Failed to start JsonDb process"); - } - // back-up all existing items QStringList availableManagers(QOrganizerManager::availableManagers()); foreach (const QString &manager, availableManagers) { @@ -115,9 +105,6 @@ void tst_QOrganizerE2E::cleanupTestCase() organizerManager.saveItems(&(i.value())); ++i; } - - if (QOrganizerManager::availableManagers().contains("jsondb")) - jsondbProcess.terminate(); } void tst_QOrganizerE2E::testMegaItem() diff --git a/tests/auto/organizer/qorganizeritemasync/unittest/tst_qorganizeritemasync.cpp b/tests/auto/organizer/qorganizeritemasync/unittest/tst_qorganizeritemasync.cpp index 18ac6b436..c83387a52 100644 --- a/tests/auto/organizer/qorganizeritemasync/unittest/tst_qorganizeritemasync.cpp +++ b/tests/auto/organizer/qorganizeritemasync/unittest/tst_qorganizeritemasync.cpp @@ -46,7 +46,6 @@ #include <QtOrganizer/qorganizer.h> #include "../../qorganizermanagerdataholder.h" //QOrganizerManagerDataHolder -#include "../../../jsondbprocess.h" Q_DECLARE_METATYPE(QTORGANIZER_PREPEND_NAMESPACE(QOrganizerAbstractRequest::State)) @@ -203,10 +202,8 @@ private slots: void itemSave_data() { addManagers(); } void itemListSave(); void itemListSave_data() { addManagers(); } -#if defined(QT_NO_JSONDB) void itemPartialSave(); void itemPartialSave_data() { addManagers(); } -#endif void collectionFetch(); void collectionFetch_data() { addManagers(); } @@ -239,9 +236,6 @@ private: Qt::HANDLE m_mainThreadId; Qt::HANDLE m_resultsAvailableSlotThreadId; QScopedPointer<QOrganizerManagerDataHolder> managerDataHolder; - - JsonDbProcess jsondbProcess; - }; tst_QOrganizerItemAsync::tst_QOrganizerItemAsync() @@ -259,22 +253,12 @@ tst_QOrganizerItemAsync::~tst_QOrganizerItemAsync() void tst_QOrganizerItemAsync::initTestCase() { - // Start JsonDb daemon if needed - if (QOrganizerManager::availableManagers().contains("jsondb")) { - QString partitions_json = QFINDTESTDATA("partitions.json"); - QVERIFY2(!partitions_json.isEmpty(), "partitions.json file is missing"); - QVERIFY2(jsondbProcess.start(partitions_json), "Failed to start JsonDb process"); - } - managerDataHolder.reset(new QOrganizerManagerDataHolder()); } void tst_QOrganizerItemAsync::cleanupTestCase() { managerDataHolder.reset(0); - - if (QOrganizerManager::availableManagers().contains("jsondb")) - jsondbProcess.terminate(); } bool tst_QOrganizerItemAsync::compareItemLists(QList<QOrganizerItem> lista, QList<QOrganizerItem> listb) @@ -577,14 +561,12 @@ void tst_QOrganizerItemAsync::itemFetch() mitems = oim->items(QDateTime(), QDateTime(), dfil); items = ifr.items(); - QEXPECT_FAIL("mgr='jsondb'","Jsondb backend does not support filtering based only on the detail/field and not value.", Continue); QVERIFY(!mitems.isEmpty()); QCOMPARE(mitems.size(), items.size()); for (int i = 0; i < items.size(); i++) { QVERIFY(containsIgnoringDetailKeys(mitems, items.at(i))); } -#if defined(QT_NO_JSONDB) // sort order QOrganizerItemSortOrder sortOrder; sortOrder.setDetail(QOrganizerItemDetail::TypePriority, QOrganizerItemPriority::FieldPriority); @@ -743,7 +725,6 @@ void tst_QOrganizerItemAsync::itemFetch() QVERIFY(ifr.state() == QOrganizerAbstractRequest::CanceledState); break; } -#endif } void tst_QOrganizerItemAsync::itemFetchById() @@ -867,11 +848,9 @@ void tst_QOrganizerItemAsync::itemIdFetch() itemIds = oim->itemIds(QDateTime(), QDateTime(), dfil); result = ifr.itemIds(); - QEXPECT_FAIL("mgr='jsondb'","Jsondb backend does not support filtering based only on the detail/field and not value.", Continue); QVERIFY(!itemIds.isEmpty()); QCOMPARE(itemIds, result); -#if defined(QT_NO_JSONDB) // sort order QOrganizerItemSortOrder sortOrder; sortOrder.setDetail(QOrganizerItemDetail::TypePriority, QOrganizerItemPriority::FieldPriority); @@ -958,7 +937,6 @@ void tst_QOrganizerItemAsync::itemIdFetch() spy.clear(); break; } -#endif } void tst_QOrganizerItemAsync::itemOccurrenceFetch() @@ -1213,7 +1191,6 @@ void tst_QOrganizerItemAsync::itemFetchForExport() QVERIFY(items.contains(curr)); } -#if defined(QT_NO_JSONDB) // asynchronous detail field filtering QOrganizerItemDetailFieldFilter dfil; dfil.setDetail(QOrganizerItemDetail::TypeLocation, QOrganizerItemLocation::FieldLabel); @@ -1236,7 +1213,6 @@ void tst_QOrganizerItemAsync::itemFetchForExport() QOrganizerItem curr = itemsfe.at(i); QVERIFY(items.contains(curr)); } -#endif // sort order QOrganizerItemSortOrder sortOrder; @@ -1266,7 +1242,6 @@ void tst_QOrganizerItemAsync::itemFetchForExport() QVERIFY(items.contains(curr)); } -#if defined(QT_NO_JSONDB) // restrictions sorting.clear(); ifr.setFilter(fil); @@ -1394,7 +1369,6 @@ void tst_QOrganizerItemAsync::itemFetchForExport() QVERIFY(ifr.state() == QOrganizerAbstractRequest::CanceledState); break; } -#endif } void tst_QOrganizerItemAsync::itemRemove() @@ -1461,7 +1435,6 @@ void tst_QOrganizerItemAsync::itemRemove() QThreadSignalSpy spy(&irr, SIGNAL(stateChanged(QOrganizerAbstractRequest::State))); QVERIFY(!irr.cancel()); // not started - QEXPECT_FAIL("mgr='jsondb'","Jsondb backend does not support filtering based only on the detail/field and not value.", Continue); QVERIFY(!oim->items(QDateTime(), QDateTime(), dfil).isEmpty()); QVERIFY(irr.start()); @@ -1474,7 +1447,6 @@ void tst_QOrganizerItemAsync::itemRemove() QVERIFY(spy.count() >= 1); // active + finished progress signals spy.clear(); - QEXPECT_FAIL("mgr='jsondb'","Jsondb backend does not support filtering based only on the detail/field and not value.", Continue); QCOMPARE(oim->itemIds().size(), originalCount - 1); QVERIFY(oim->itemIds(QDateTime(), QDateTime(), dfil).isEmpty()); @@ -1640,7 +1612,6 @@ void tst_QOrganizerItemAsync::itemRemoveById() QThreadSignalSpy spy(&irr, SIGNAL(stateChanged(QOrganizerAbstractRequest::State))); QVERIFY(!irr.cancel()); // not started - QEXPECT_FAIL("mgr='jsondb'","Jsondb backend does not support filtering based only on the detail/field and not value.", Continue); QVERIFY(!oim->itemIds(QDateTime(), QDateTime(), dfil).isEmpty()); QVERIFY(irr.start()); @@ -1653,15 +1624,11 @@ void tst_QOrganizerItemAsync::itemRemoveById() QVERIFY(spy.count() >= 1); // active + finished progress signals spy.clear(); - QEXPECT_FAIL("mgr='jsondb'","Jsondb backend does not support filtering based only on the detail/field and not value.", Continue); QCOMPARE(oim->itemIds().size(), originalCount - 1); QVERIFY(oim->itemIds(QDateTime(), QDateTime(), dfil).isEmpty()); // remove all items //// dfil.setDetail(QOrganizerItemDetail::TypeDisplayLabel); // delete everything. -//#if !defined(QT_NO_JSONDB) -// qRegisterMetaType<QOrganizerItemRemoveRequest*>("QOrganizerItemRemoveRequest*"); -//#endif irr.setManager(oim.data()); irr.setItemIds(oim->itemIds()); @@ -1850,7 +1817,6 @@ void tst_QOrganizerItemAsync::itemSave() // XXX: really, we should use isSuperset() from tst_QOrganizerManager, but this will do for now: QVERIFY(result.first().detail(QOrganizerItemDetail::TypePriority).value(QOrganizerItemPriority::FieldPriority) == priority.priority()); QCOMPARE(oim->itemIds().size(), originalCount + 1); -#if defined(QT_NO_JSONDB) // cancelling QOrganizerItem temp = testTodo; temp.setDisplayLabel("should not get saved"); @@ -1941,7 +1907,6 @@ void tst_QOrganizerItemAsync::itemSave() QCOMPARE(oim->itemIds().size(), originalCount + 1); break; } -#endif } void tst_QOrganizerItemAsync::itemListSave() @@ -2049,7 +2014,6 @@ void tst_QOrganizerItemAsync::itemListSave() QVERIFY(expected[1].id().isNull()); } -#if defined(QT_NO_JSONDB) void tst_QOrganizerItemAsync::itemPartialSave() { // QFETCH(QString, uri); @@ -2190,7 +2154,6 @@ void tst_QOrganizerItemAsync::itemPartialSave() // // XXX TODO: partial save for organizer items as well as items!!! } -#endif void tst_QOrganizerItemAsync::collectionFetch() { @@ -2235,7 +2198,6 @@ void tst_QOrganizerItemAsync::collectionFetch() QVERIFY(syncCols.contains(curr)); } -#if defined(QT_NO_JSONDB) // cancelling int bailoutCount = MAX_OPTIMISTIC_SCHEDULING_LIMIT; // attempt to cancel 40 times. If it doesn't work due to threading, bail out. while (true) { @@ -2290,7 +2252,6 @@ void tst_QOrganizerItemAsync::collectionFetch() QVERIFY(cfr.state() == QOrganizerAbstractRequest::CanceledState); break; } -#endif } void tst_QOrganizerItemAsync::collectionRemove() @@ -2365,7 +2326,6 @@ void tst_QOrganizerItemAsync::collectionRemove() QVERIFY(crr1.isFinished()); QVERIFY(crr1.error() == QOrganizerManager::NoError); -#if defined(QT_NO_JSONDB) // cancelling QOrganizerCollection temp; temp.setMetaData(QOrganizerCollection::KeyDescription, "Should not be removed!"); @@ -2450,7 +2410,6 @@ void tst_QOrganizerItemAsync::collectionRemove() // now clean up our temp collection. oim->removeCollection(temp.id()); -#endif } void tst_QOrganizerItemAsync::collectionSave() @@ -2545,7 +2504,6 @@ void tst_QOrganizerItemAsync::collectionSave() QVERIFY(csr1.isFinished()); QVERIFY(csr1.error() == QOrganizerManager::NoError); -#if defined(QT_NO_JSONDB) // cancelling QOrganizerCollection temp; temp.setMetaData(testCollection.metaData()); @@ -2631,7 +2589,6 @@ void tst_QOrganizerItemAsync::collectionSave() QCOMPARE(oim->collections().size(), originalCount + 1); break; } -#endif } @@ -3183,11 +3140,9 @@ QOrganizerManager* tst_QOrganizerItemAsync::prepareModel(const QString& managerU // XXX TODO: ensure that this is the case: // there should be no items in the database. -#if defined(QT_NO_JSONDB) QList<QOrganizerItemId> toRemove = oim->itemIds(); foreach (const QOrganizerItemId& removeId, toRemove) oim->removeItem(removeId); -#endif QOrganizerEvent a, b, c; a.setDisplayLabel("event a"); diff --git a/tests/auto/organizer/qorganizeritemasync/unittest/unittest.pro b/tests/auto/organizer/qorganizeritemasync/unittest/unittest.pro index 3d659689b..c02e23c53 100644 --- a/tests/auto/organizer/qorganizeritemasync/unittest/unittest.pro +++ b/tests/auto/organizer/qorganizeritemasync/unittest/unittest.pro @@ -4,8 +4,6 @@ TARGET = tst_qorganizeritemasync QT += organizer -qtHaveModule(jsondb): QT += jsondb - SOURCES += tst_qorganizeritemasync.cpp -HEADERS += ../../qorganizermanagerdataholder.h ../../../jsondbprocess.h +HEADERS += ../../qorganizermanagerdataholder.h DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 diff --git a/tests/auto/organizer/qorganizermanager/qorganizermanager.pro b/tests/auto/organizer/qorganizermanager/qorganizermanager.pro index cf6a286aa..fc24be1fc 100644 --- a/tests/auto/organizer/qorganizermanager/qorganizermanager.pro +++ b/tests/auto/organizer/qorganizermanager/qorganizermanager.pro @@ -2,8 +2,6 @@ include(../../auto.pri) QT += organizer organizer-private -qtHaveModule(jsondb): QT += jsondb - SOURCES += tst_qorganizermanager.cpp -HEADERS += ../qorganizermanagerdataholder.h ../../jsondbprocess.h +HEADERS += ../qorganizermanagerdataholder.h DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 diff --git a/tests/auto/organizer/qorganizermanager/tst_qorganizermanager.cpp b/tests/auto/organizer/qorganizermanager/tst_qorganizermanager.cpp index 08d17d59c..d5538f1b3 100644 --- a/tests/auto/organizer/qorganizermanager/tst_qorganizermanager.cpp +++ b/tests/auto/organizer/qorganizermanager/tst_qorganizermanager.cpp @@ -47,7 +47,6 @@ #include <QtOrganizer/qorganizer.h> #include <QtOrganizer/qorganizeritemchangeset.h> #include "../qorganizermanagerdataholder.h" -#include "../../jsondbprocess.h" #include <QtOrganizer/qorganizernote.h> #include <QtOrganizer/qorganizerevent.h> @@ -88,8 +87,6 @@ private: QScopedPointer<QOrganizerManagerDataHolder> managerDataHolder; - JsonDbProcess jsondbProcess; - public slots: void initTestCase(); void cleanupTestCase(); @@ -288,13 +285,6 @@ tst_QOrganizerManager::~tst_QOrganizerManager() void tst_QOrganizerManager::initTestCase() { - // Start JsonDb daemon if needed - if (QOrganizerManager::availableManagers().contains("jsondb")) { - QString partitions_json = QFINDTESTDATA("partitions.json"); - QVERIFY2(!partitions_json.isEmpty(), "partitions.json file is missing"); - QVERIFY2(jsondbProcess.start(partitions_json), "Failed to start JsonDb process"); - } - managerDataHolder.reset(new QOrganizerManagerDataHolder()); /* Make sure these other test plugins are NOT loaded by default */ @@ -306,9 +296,6 @@ void tst_QOrganizerManager::initTestCase() void tst_QOrganizerManager::cleanupTestCase() { managerDataHolder.reset(0); - - if (QOrganizerManager::availableManagers().contains("jsondb")) - jsondbProcess.terminate(); } void tst_QOrganizerManager::dumpOrganizerItemDifferences(const QOrganizerItem& ca, const QOrganizerItem& cb) @@ -732,11 +719,7 @@ void tst_QOrganizerManager::ctors() // Finally test the platform specific engines are actually the defaults -#if !defined(QT_NO_JSONDB) - QCOMPARE(defaultStore, QString::fromLatin1("jsondb")); -#else QCOMPARE(defaultStore, QString("invalid")); -#endif } void tst_QOrganizerManager::doDump() @@ -796,9 +779,7 @@ void tst_QOrganizerManager::add() QVERIFY(cm->saveItem(&nonexistentItem)); // should work QVERIFY(cm->removeItem(nonexistentItem.id())); // now nonexistentItem has an id which does not exist - QEXPECT_FAIL("mgr='jsondb'", "Expect fail due to Jsondb change", Continue); QVERIFY(!cm->saveItem(&nonexistentItem)); // hence, should fail - QEXPECT_FAIL("mgr='jsondb'", "Expect fail due to Jsondb change", Continue); QCOMPARE(cm->error(), QOrganizerManager::DoesNotExistError); nonexistentItem.setId(QOrganizerItemId()); QVERIFY(cm->saveItem(&nonexistentItem)); // after setting id to zero, should save @@ -810,84 +791,84 @@ void tst_QOrganizerManager::add() // - save the item // - read it back // - ensure that it's the same. -#if defined(QT_NO_JSONDB) -// QOrganizerEvent megaevent; -// QMap<QString, QOrganizerItemDetailDefinition> defmap = cm->detailDefinitions(QOrganizerItemType::TypeEvent); -// QList<QOrganizerItemDetailDefinition> defs = defmap.values(); -// foreach (const QOrganizerItemDetailDefinition def, defs) { - -// // This is probably read-only -// if (def.name() == QOrganizerItemTimestamp::DefinitionName) -// continue; - -// // otherwise, create a new detail of the given type and save it to the item -// QOrganizerItemDetail det(def.name()); -// QMap<QString, QOrganizerItemDetailFieldDefinition> fieldmap = def.fields(); -// QStringList fieldKeys = fieldmap.keys(); -// foreach (const QString& fieldKey, fieldKeys) { -// // get the field, and check to see that it's not constrained. -// QOrganizerItemDetailFieldDefinition currentField = fieldmap.value(fieldKey); - -// // Attempt to create a worthy value -// if (!currentField.allowableValues().isEmpty()) { -// // we want to save a value that will be accepted. -// if (currentField.dataType() == QVariant::StringList) -// det.setValue(fieldKey, QStringList() << currentField.allowableValues().first().toString()); -// else if (currentField.dataType() == QVariant::List) -// det.setValue(fieldKey, QVariantList() << currentField.allowableValues().first()); -// else -// det.setValue(fieldKey, currentField.allowableValues().first()); -// } else { -// // any value of the correct type will be accepted -// bool savedSuccessfully = false; -// QVariant dummyValue = QVariant(fieldKey); // try to get some unique string data -// if (currentField.dataType() < static_cast<int>(QVariant::UserType)) { -// QVariant::Type type = static_cast<QVariant::Type>(currentField.dataType()); -// // It is not a user-defined type -// if (dummyValue.canConvert(type)) { -// savedSuccessfully = dummyValue.convert(type); -// if (savedSuccessfully) { -// // we have successfully created a (supposedly) valid field for this detail. -// det.setValue(fieldKey, dummyValue); -// continue; -// } -// } - -// // nope, couldn't save the string value (test); try a date. -// dummyValue = QVariant(QDate::currentDate()); -// if (dummyValue.canConvert(type)) { -// savedSuccessfully = dummyValue.convert(type); -// if (savedSuccessfully) { -// // we have successfully created a (supposedly) valid field for this detail. -// det.setValue(fieldKey, dummyValue); -// continue; -// } -// } - -// // nope, couldn't convert a string or a date - try the integer value (42) -// dummyValue = QVariant(42); -// if (dummyValue.canConvert(type)) { -// savedSuccessfully = dummyValue.convert(type); -// if (savedSuccessfully) { -// // we have successfully created a (supposedly) valid field for this detail. -// det.setValue(fieldKey, dummyValue); -// continue; -// } -// } -// } - -// // if we get here, we don't know what sort of value can be saved... -// } -// } -// if (!det.isEmpty()) -// megaevent.saveDetail(&det); -// } +#if 0 // This test is currently excluded; can it be reinstated? + QOrganizerEvent megaevent; + QMap<QString, QOrganizerItemDetailDefinition> defmap = cm->detailDefinitions(QOrganizerItemType::TypeEvent); + QList<QOrganizerItemDetailDefinition> defs = defmap.values(); + foreach (const QOrganizerItemDetailDefinition def, defs) { + + // This is probably read-only + if (def.name() == QOrganizerItemTimestamp::DefinitionName) + continue; + + // otherwise, create a new detail of the given type and save it to the item + QOrganizerItemDetail det(def.name()); + QMap<QString, QOrganizerItemDetailFieldDefinition> fieldmap = def.fields(); + QStringList fieldKeys = fieldmap.keys(); + foreach (const QString& fieldKey, fieldKeys) { + // get the field, and check to see that it's not constrained. + QOrganizerItemDetailFieldDefinition currentField = fieldmap.value(fieldKey); + + // Attempt to create a worthy value + if (!currentField.allowableValues().isEmpty()) { + // we want to save a value that will be accepted. + if (currentField.dataType() == QVariant::StringList) + det.setValue(fieldKey, QStringList() << currentField.allowableValues().first().toString()); + else if (currentField.dataType() == QVariant::List) + det.setValue(fieldKey, QVariantList() << currentField.allowableValues().first()); + else + det.setValue(fieldKey, currentField.allowableValues().first()); + } else { + // any value of the correct type will be accepted + bool savedSuccessfully = false; + QVariant dummyValue = QVariant(fieldKey); // try to get some unique string data + if (currentField.dataType() < static_cast<int>(QVariant::UserType)) { + QVariant::Type type = static_cast<QVariant::Type>(currentField.dataType()); + // It is not a user-defined type + if (dummyValue.canConvert(type)) { + savedSuccessfully = dummyValue.convert(type); + if (savedSuccessfully) { + // we have successfully created a (supposedly) valid field for this detail. + det.setValue(fieldKey, dummyValue); + continue; + } + } -// QVERIFY(cm->saveItem(&megaevent)); // must be able to save since built from definitions. -// QOrganizerItem retrievedMegaitem = cm->item(megaevent.id()); -// if (!isSuperset(retrievedMegaitem, megaevent)) { -// dumpOrganizerItemDifferences(megaevent, retrievedMegaitem); -// } + // nope, couldn't save the string value (test); try a date. + dummyValue = QVariant(QDate::currentDate()); + if (dummyValue.canConvert(type)) { + savedSuccessfully = dummyValue.convert(type); + if (savedSuccessfully) { + // we have successfully created a (supposedly) valid field for this detail. + det.setValue(fieldKey, dummyValue); + continue; + } + } + + // nope, couldn't convert a string or a date - try the integer value (42) + dummyValue = QVariant(42); + if (dummyValue.canConvert(type)) { + savedSuccessfully = dummyValue.convert(type); + if (savedSuccessfully) { + // we have successfully created a (supposedly) valid field for this detail. + det.setValue(fieldKey, dummyValue); + continue; + } + } + } + + // if we get here, we don't know what sort of value can be saved... + } + } + if (!det.isEmpty()) + megaevent.saveDetail(&det); + } + + QVERIFY(cm->saveItem(&megaevent)); // must be able to save since built from definitions. + QOrganizerItem retrievedMegaitem = cm->item(megaevent.id()); + if (!isSuperset(retrievedMegaitem, megaevent)) { + dumpOrganizerItemDifferences(megaevent, retrievedMegaitem); + } // now a item with many details of a particular definition // if the detail is not unique it should then support minumum of two of the same kind @@ -4023,9 +4004,6 @@ void tst_QOrganizerManager::partialSave() QFETCH(QString, uri); QScopedPointer<QOrganizerManager> cm(QOrganizerManager::fromUri(uri)); - if (cm->managerName() == QStringLiteral("jsondb")) - QSKIP("Partial save is not supported by JsonDb!"); - QList<QOrganizerItem> items; QOrganizerEvent event = QOrganizerEvent(); event.setDisplayLabel("One"); @@ -4521,8 +4499,6 @@ void tst_QOrganizerManager::testReminder() QVERIFY(item.detail(QOrganizerItemDetail::TypeAudibleReminder) == oi.detail(QOrganizerItemDetail::TypeAudibleReminder)); } - if ("qtorganizer:jsondb:" == uri)// jsondb backend does not support email reminder and visual reminder - return; /*Email reminder test*/ QOrganizerItemEmailReminder emailReminder; QOrganizerEvent emailEvent; @@ -5090,73 +5066,6 @@ void tst_QOrganizerManager::testExtendedDetail() } QVERIFY(mgr->removeItem(event.id())); - - // for JsonDb backend, we allow custom fields for reminder, rsvp, and location - if (mgr->managerName() == QString(QStringLiteral("jsondb"))) { - QOrganizerItemAudibleReminder audibleReminder; - audibleReminder.setSecondsBeforeStart(1989); - audibleReminder.setRepetition(6, 4); - audibleReminder.setDataUrl(QUrl(QString(QStringLiteral("http://www.qt-project.org/")))); - - QOrganizerItemExtendedDetail extendedDetailForReminder; - extendedDetailForReminder.setName(QString(QStringLiteral("reminder"))); - QVariantMap data; - data.insert(QString(QStringLiteral("Qt")), QString(QStringLiteral("Everywhere"))); - data.insert(QString(QStringLiteral("URL")), QUrl(QString(QStringLiteral("http://www.qt-project.org/")))); - extendedDetailForReminder.setData(data); - - QOrganizerEvent eventForReminder; - eventForReminder.setStartDateTime(QDateTime::fromString(QString(QStringLiteral("2012-02-01T00:11:22")), Qt::ISODate)); - eventForReminder.saveDetail(&audibleReminder); - eventForReminder.saveDetail(&extendedDetailForReminder); - QVERIFY(mgr->saveItem(&eventForReminder)); - - QOrganizerItem fetchedItem = mgr->items(QList<QOrganizerItemId>() << eventForReminder.id()).at(0); - QVERIFY(fetchedItem == eventForReminder); - - QOrganizerEventRsvp rsvp; - rsvp.setOrganizerName(QString(QStringLiteral("Qt"))); - - QOrganizerItemExtendedDetail extendedDetailForRsvp; - extendedDetailForRsvp.setName(QString(QStringLiteral("rsvp"))); - extendedDetailForRsvp.setData(data); - - QOrganizerEvent eventForRsvp; - eventForRsvp.saveDetail(&rsvp); - eventForRsvp.saveDetail(&extendedDetailForRsvp); - QVERIFY(mgr->saveItem(&eventForRsvp)); - - fetchedItem = mgr->items(QList<QOrganizerItemId>() << eventForRsvp.id()).at(0); - QVERIFY(fetchedItem == eventForRsvp); - - QOrganizerItemLocation location; - location.setLatitude(19.84); - - QOrganizerItemExtendedDetail extendedDetailForLocation; - extendedDetailForLocation.setName(QString(QStringLiteral("location"))); - extendedDetailForLocation.setData(data); - - QOrganizerEvent eventForLocation; - eventForLocation.saveDetail(&location); - eventForLocation.saveDetail(&extendedDetailForLocation); - QVERIFY(mgr->saveItem(&eventForLocation)); - - fetchedItem = mgr->items(QList<QOrganizerItemId>() << eventForLocation.id()).at(0); - QVERIFY(fetchedItem == eventForLocation); - - QOrganizerEvent eventForAll; - eventForAll.setStartDateTime(QDateTime::fromString(QString(QStringLiteral("2012-02-01T00:11:22")), Qt::ISODate)); - eventForAll.saveDetail(&audibleReminder); - eventForAll.saveDetail(&extendedDetailForReminder); - eventForAll.saveDetail(&rsvp); - eventForAll.saveDetail(&extendedDetailForRsvp); - eventForAll.saveDetail(&location); - eventForAll.saveDetail(&extendedDetailForLocation); - QVERIFY(mgr->saveItem(&eventForAll)); - - fetchedItem = mgr->items(QList<QOrganizerItemId>() << eventForAll.id()).at(0); - QVERIFY(fetchedItem == eventForAll); - } } void tst_QOrganizerManager::testAttendee() @@ -5270,7 +5179,6 @@ void tst_QOrganizerManager::testClassification() QVERIFY(mgr->saveItem(&event)); QOrganizerItemId id = event.id(); QOrganizerItem item = mgr->item(id); - QEXPECT_FAIL("mgr='jsondb'", "No support on jsondb backend yet", Abort); QCOMPARE(1, item.details(QOrganizerItemDetail::TypeClassification).count()); QVERIFY(item == event);//This will compare all details and their values @@ -5312,7 +5220,7 @@ void tst_QOrganizerManager::testVersion() QVERIFY((version2.version() > version.version()) || (version2.extendedVersion() != version.extendedVersion())); } -#if defined(QT_NO_JSONDB) +#if 0 // This test is currently excluded; can it be reinstated? class errorSemanticsTester : public QObject { Q_OBJECT; public: diff --git a/tests/auto/organizer/qorganizermanagerdetails/qorganizermanagerdetails.pro b/tests/auto/organizer/qorganizermanagerdetails/qorganizermanagerdetails.pro index ceb60ebd5..6fd89a524 100644 --- a/tests/auto/organizer/qorganizermanagerdetails/qorganizermanagerdetails.pro +++ b/tests/auto/organizer/qorganizermanagerdetails/qorganizermanagerdetails.pro @@ -2,8 +2,6 @@ include(../../auto.pri) QT += organizer -qtHaveModule(jsondb): QT += jsondb - SOURCES += tst_qorganizermanagerdetails.cpp -HEADERS += ../qorganizermanagerdataholder.h ../../jsondbprocess.h +HEADERS += ../qorganizermanagerdataholder.h DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 diff --git a/tests/auto/organizer/qorganizermanagerdetails/tst_qorganizermanagerdetails.cpp b/tests/auto/organizer/qorganizermanagerdetails/tst_qorganizermanagerdetails.cpp index 3c5af5e4d..60ff1fa9e 100644 --- a/tests/auto/organizer/qorganizermanagerdetails/tst_qorganizermanagerdetails.cpp +++ b/tests/auto/organizer/qorganizermanagerdetails/tst_qorganizermanagerdetails.cpp @@ -43,7 +43,6 @@ #include <QtCore/QDateTime> #include <QtOrganizer/qorganizer.h> #include "../qorganizermanagerdataholder.h" -#include "../../jsondbprocess.h" QTORGANIZER_USE_NAMESPACE @@ -59,8 +58,6 @@ private: QScopedPointer<QOrganizerManagerDataHolder> managerDataHolder; - JsonDbProcess jsondbProcess; - private slots: void initTestCase(); void cleanupTestCase(); @@ -91,22 +88,12 @@ void tst_QOrganizerManagerDetails::addManagers() void tst_QOrganizerManagerDetails::initTestCase() { - // Start JsonDb daemon if needed - if (QOrganizerManager::availableManagers().contains("jsondb")) { - QString partitions_json = QFINDTESTDATA("partitions.json"); - QVERIFY2(!partitions_json.isEmpty(), "partitions.json file is missing"); - QVERIFY2(jsondbProcess.start(partitions_json), "Failed to start JsonDb process"); - } - managerDataHolder.reset(new QOrganizerManagerDataHolder()); } void tst_QOrganizerManagerDetails::cleanupTestCase() { managerDataHolder.reset(0); - - if (QOrganizerManager::availableManagers().contains("jsondb")) - jsondbProcess.terminate(); } bool tst_QOrganizerManagerDetails::saveAndLoadItem(QOrganizerManager *manager, QOrganizerItem &original, QOrganizerItem &loaded) @@ -138,9 +125,7 @@ void tst_QOrganizerManagerDetails::saveAndVerifyItem(QOrganizerManager *manager, qDebug() << "expected: " << original; qDebug() << "loaded: " << loaded; QCOMPARE(loaded.details().count(), original.details().count()); -#if defined(QT_NO_JSONDB) QCOMPARE(loaded, original); -#endif } } diff --git a/tests/benchmark/contacts/tst_benchmark_create_and_savecontact.qml b/tests/benchmark/contacts/tst_benchmark_create_and_savecontact.qml index f688bb742..72c2b23ab 100644 --- a/tests/benchmark/contacts/tst_benchmark_create_and_savecontact.qml +++ b/tests/benchmark/contacts/tst_benchmark_create_and_savecontact.qml @@ -52,7 +52,7 @@ ContactsBenchmarkTestCase { ContactModel { id: model - manager:"jsondb"; + manager:"memory"; autoUpdate: true } diff --git a/tests/benchmark/contacts/tst_benchmark_removecontact.qml b/tests/benchmark/contacts/tst_benchmark_removecontact.qml index ac2a58fb1..8fd6c8ec5 100644 --- a/tests/benchmark/contacts/tst_benchmark_removecontact.qml +++ b/tests/benchmark/contacts/tst_benchmark_removecontact.qml @@ -52,7 +52,7 @@ ContactsBenchmarkTestCase { ContactModel { id: model - manager:"jsondb"; + manager:"memory"; autoUpdate: true } diff --git a/tests/benchmark/contacts/tst_benchmark_savecontact.qml b/tests/benchmark/contacts/tst_benchmark_savecontact.qml index 77c3fd638..d80800b7e 100644 --- a/tests/benchmark/contacts/tst_benchmark_savecontact.qml +++ b/tests/benchmark/contacts/tst_benchmark_savecontact.qml @@ -53,7 +53,7 @@ ContactsBenchmarkTestCase { ContactModel { id: model - manager:"jsondb"; + manager:"memory"; autoUpdate: true } diff --git a/tests/benchmark/contacts/tst_benchmark_updatecontact.qml b/tests/benchmark/contacts/tst_benchmark_updatecontact.qml index 0db196d75..803e55b86 100644 --- a/tests/benchmark/contacts/tst_benchmark_updatecontact.qml +++ b/tests/benchmark/contacts/tst_benchmark_updatecontact.qml @@ -52,7 +52,7 @@ ContactsBenchmarkTestCase { ContactModel { id: model - manager:"jsondb"; + manager:"memory"; autoUpdate: true } diff --git a/tests/system/qmlorganizer/organizer.qml b/tests/system/qmlorganizer/organizer.qml index f06e11aa0..706605d08 100644 --- a/tests/system/qmlorganizer/organizer.qml +++ b/tests/system/qmlorganizer/organizer.qml @@ -89,8 +89,7 @@ Rectangle { SystemPalette { id: activePalette } property OrganizerModel organizer:OrganizerModel{ id: organizer - manager:"qtorganizer:jsondb:id=qml" - //manager:"qtorganizer:memory:id=qml" + manager:"qtorganizer:memory:id=qml" startPeriod:'2009-01-01' endPeriod:'2012-12-31' autoUpdate:true |