Exemplo n.º 1
0
void MT_CntVersitMyCardPlugin::exportOwnContact()
{
    //create contact
    QContact phonecontact;
    QContactName contactName;
    contactName.setFirstName("Jo");
    contactName.setLastName("Black");
    phonecontact.saveDetail(&contactName);
    QContactPhoneNumber number;
    number.setContexts("Home");
    number.setSubTypes("Mobile");
    number.setNumber("+02644424429");
    phonecontact.saveDetail(&number);
    
    //set MyCard detail
    QContactDetail myCard(MYCARD_DEFINTION_NAME);
    phonecontact.saveDetail(&myCard);
    
    //export
    QList<QContact> list;
    list.append(phonecontact);
    QVersitContactExporter exporter;
    QVERIFY(exporter.exportContacts(list, QVersitDocument::VCard21Type));
    QList<QVersitDocument> documents = exporter.documents();
    
    //X-SELF property is exported if MyCard
    QVersitDocument document  = documents.first();
    QVersitProperty property;
    property.setName(QLatin1String("X-SELF"));
    property.setValue("0");
    bool propertyFound = document.properties().contains(property);
    QVERIFY(propertyFound);
}
Exemplo n.º 2
0
void SeasidePerson::setLastName(const QString &name)
{
    QContactName nameDetail = mContact.detail<QContactName>();
    nameDetail.setLastName(name);
    mContact.saveDetail(&nameDetail);
    emit lastNameChanged();
    recalculateDisplayLabel();
}
/*!
 * The leaving function that queries the SQL database
 * 
 * \a aSqlQuery An SQL query
 * \return the list of matched contact ids
 */
QList<QContact> CntSymbianSrvConnection::searchContactNamesL(const TDesC& aSqlQuery)
{
    readContactsToBufferL(aSqlQuery, CntSymbianSrvConnection::CntSearchResultList);

    RBufReadStream readStream;
    QList<QContact> contacts;
    TInt id;
    TBuf<256> firstName;
    TBuf<256> lastName;
    TBuf<256> company;

    readStream.Open(*m_buffer);
    while ((id = readStream.ReadInt32L()) != 0) {
        readStream >> firstName;
        readStream >> lastName;
        readStream >> company;

        QContact contact, tempContact;

        QContactName name;
        name.setFirstName(QString::fromUtf16(firstName.Ptr(), firstName.Length()));
        name.setLastName(QString::fromUtf16(lastName.Ptr(), lastName.Length()));
        tempContact.saveDetail(&name);

        QContactOrganization organization;
        organization.setName(QString::fromUtf16(company.Ptr(), company.Length()));
        tempContact.saveDetail(&organization);

        QContactManager::Error error(QContactManager::NoError);
        QString label = m_manager->synthesizedDisplayLabel(tempContact, &error);
        if (error != QContactManager::NoError) {
            continue;
        }
        tempContact.clearDetails();

        m_manager->setContactDisplayLabel(&contact, label);

        QContactId contactId;
        contactId.setLocalId(id);
        contactId.setManagerUri(m_manager->managerUri());
        contact.setId(contactId);

        contacts << contact;
    }

    return contacts;
}
Exemplo n.º 4
0
QContactDetail *CntTransformName::transformItemField(const CContactItemField& field, const QContact &contact)
{
    QContactName *name = new QContactName(contact.detail<QContactName>());

    CContactTextField* storage = field.TextStorage();
    QString nameValue = QString::fromUtf16(storage->Text().Ptr(), storage->Text().Length());

    for (int i = 0; i < field.ContentType().FieldTypeCount(); i++) {
        //Prefix
        if (field.ContentType().FieldType(i) == KUidContactFieldPrefixName) {
            name->setPrefix(nameValue);
        }
        //First name
        else if (field.ContentType().FieldType(i) == KUidContactFieldGivenName) {
            name->setFirstName(nameValue);
        }
        //Middle name
        else if (field.ContentType().FieldType(i) == KUidContactFieldAdditionalName) {
            name->setMiddleName(nameValue);
        }
        //Last name
        else if (field.ContentType().FieldType(i) == KUidContactFieldFamilyName) {
            name->setLastName(nameValue);
        }
        //Suffix
        else if (field.ContentType().FieldType(i) == KUidContactFieldSuffixName) {
            name->setSuffix(nameValue);
        }
        // custom label
        else if (field.ContentType().FieldType(i) == KUidContactFieldTemplateLabel) {
            name->setCustomLabel(nameValue);
        }
    }

    return name;
}
Exemplo n.º 5
0
QContact generateContact(const QString &syncTarget = QString(QLatin1String("local")), bool possiblyAggregate = false)
{
    static const QStringList firstNames(generateFirstNamesList());
    static const QStringList middleNames(generateMiddleNamesList());
    static const QStringList lastNames(generateLastNamesList());
    static const QStringList nonOverlappingFirstNames(generateNonOverlappingFirstNamesList());
    static const QStringList nonOverlappingLastNames(generateNonOverlappingLastNamesList());
    static const QStringList phoneNumbers(generatePhoneNumbersList());
    static const QStringList emailProviders(generateEmailProvidersList());
    static const QStringList avatars(generateAvatarsList());
    static const QStringList hobbies(generateHobbiesList());

    // we randomly determine whether to generate various details
    // to ensure that we have heterogeneous contacts in the db.
    QContact retn;
    int random = qrand();
    bool preventAggregate = (syncTarget != QLatin1String("local") && !possiblyAggregate);

    // We always have a sync target.
    QContactSyncTarget synctarget;
    synctarget.setSyncTarget(syncTarget);
    retn.saveDetail(&synctarget);

    // We always have a name.  Select an overlapping name if the sync target
    // is something other than "local" and possiblyAggregate is true.
    QContactName name;
    name.setFirstName(preventAggregate ?
            nonOverlappingFirstNames.at(random % nonOverlappingFirstNames.size()) :
            firstNames.at(random % firstNames.size()));
    name.setLastName(preventAggregate ?
            nonOverlappingLastNames.at(random % nonOverlappingLastNames.size()) :
            lastNames.at(random % lastNames.size()));
    if ((random % 6) == 0) name.setMiddleName(middleNames.at(random % middleNames.size()));
    if ((random % 17) == 0) name.setPrefix(QLatin1String("Dr."));
    retn.saveDetail(&name);

    // Favorite
    if ((random % 31) == 0) {
        QContactFavorite fav;
        fav.setFavorite(true);
        retn.saveDetail(&fav);
    }

    // Phone number
    if ((random % 3) == 0) {
        QContactPhoneNumber phn;
        QString randomPhn = phoneNumbers.at(random % phoneNumbers.size());
        phn.setNumber(preventAggregate ? QString(QString::number(random % 500000) + randomPhn) : randomPhn);
        if ((random % 9) == 0) phn.setContexts(QContactDetail::ContextWork);
        retn.saveDetail(&phn);
    }

    // Email
    if ((random % 2) == 0) {
        QContactEmailAddress em;
        em.setEmailAddress(QString(QLatin1String("%1%2%3%4"))
                .arg(preventAggregate ? QString(QString::number(random % 500000) + syncTarget) : QString())
                .arg(name.firstName()).arg(name.lastName())
                .arg(emailProviders.at(random % emailProviders.size())));
        if (random % 9) em.setContexts(QContactDetail::ContextWork);
        retn.saveDetail(&em);
    }

    // Avatar
    if ((random % 5) == 0) {
        QContactAvatar av;
        av.setImageUrl(name.firstName() + avatars.at(random % avatars.size()));
        retn.saveDetail(&av);
    }

    // Hobby
    if ((random % 21) == 0) {
        QContactHobby h1;
        h1.setHobby(hobbies.at(random % hobbies.size()));
        retn.saveDetail(&h1);

        int newRandom = qrand();
        if ((newRandom % 2) == 0) {
            QContactHobby h2;
            h2.setHobby(hobbies.at(newRandom % hobbies.size()));
            retn.saveDetail(&h2);
        }
    }

    return retn;
}
void SeasideCache::reset()
{
    for (int i = 0; i < FilterTypesCount; ++i) {
        m_contacts[i].clear();
        m_populated[i] = false;
        m_models[i] = 0;
    }

    m_cache.clear();
    m_cacheIndices.clear();

    for (uint i = 0; i < sizeof(contactsData) / sizeof(Contact); ++i) {
        QContact contact;

        // This is specific to the qtcontacts-sqlite backend:
        const QString idStr(QString::fromLatin1("qtcontacts:org.nemomobile.contacts.sqlite::sql-%1"));
        contact.setId(QContactId::fromString(idStr.arg(i + 1)));

        QContactName name;
        name.setFirstName(QString::fromLatin1(contactsData[i].firstName));
        name.setMiddleName(QString::fromUtf8(contactsData[i].middleName));
        name.setLastName(QString::fromLatin1(contactsData[i].lastName));
        contact.saveDetail(&name);

        if (contactsData[i].avatar) {
            QContactAvatar avatar;
            avatar.setImageUrl(QUrl(QLatin1String(contactsData[i].avatar)));
            contact.saveDetail(&avatar);
        }

        QContactStatusFlags statusFlags;

        if (contactsData[i].email) {
            QContactEmailAddress email;
            email.setEmailAddress(QLatin1String(contactsData[i].email));
            contact.saveDetail(&email);
            statusFlags.setFlag(QContactStatusFlags::HasEmailAddress, true);
        }

        if (contactsData[i].phoneNumber) {
            QContactPhoneNumber phoneNumber;
            phoneNumber.setNumber(QLatin1String(contactsData[i].phoneNumber));
            contact.saveDetail(&phoneNumber);
            statusFlags.setFlag(QContactStatusFlags::HasPhoneNumber, true);
        }

        contact.saveDetail(&statusFlags);

        m_cacheIndices.insert(internalId(contact), m_cache.count());
        m_cache.append(CacheItem(contact));

        QString fullName = name.firstName() + QChar::fromLatin1(' ') + name.lastName();

        CacheItem &cacheItem = m_cache.last();
        cacheItem.nameGroup = determineNameGroup(&cacheItem);
        cacheItem.displayLabel = fullName;
    }

    insert(FilterAll, 0, getContactsForFilterType(FilterAll));
    insert(FilterFavorites, 0, getContactsForFilterType(FilterFavorites));
    insert(FilterOnline, 0, getContactsForFilterType(FilterOnline));
}
Exemplo n.º 7
0
int addTestContact(const QString &name, const QString &remoteUid, const QString &localUid)
{
    QString contactUri = QString("<testcontact:%1>").arg(contactNumber++);

    QContact contact;

    QContactSyncTarget syncTarget;
    syncTarget.setSyncTarget(QLatin1String("commhistory-tests"));
    if (!contact.saveDetail(&syncTarget)) {
        qWarning() << "Unable to add sync target to contact:" << contactUri;
        return -1;
    }

    if (!localUid.isEmpty() && localUid.indexOf("/ring/tel/") == -1) {
        // Create a metadata detail to link the contact with the account
        QContactOriginMetadata metadata;
        metadata.setGroupId(localUid);
        metadata.setId(remoteUid);
        metadata.setEnabled(true);
        if (!contact.saveDetail(&metadata)) {
            qWarning() << "Unable to add metadata to contact:" << contactUri;
            return false;
        }
    }

    QString normal = CommHistory::normalizePhoneNumber(remoteUid);
    if (normal.isEmpty()) {
        QContactOnlineAccount qcoa;
        qcoa.setValue(QContactOnlineAccount__FieldAccountPath, localUid);
        qcoa.setAccountUri(remoteUid);
        if (!contact.saveDetail(&qcoa)) {
            qWarning() << "Unable to add online account to contact:" << contactUri;
            return -1;
        }
    } else {
        QContactPhoneNumber phoneNumberDetail;
        phoneNumberDetail.setNumber(remoteUid);
        if (!contact.saveDetail(&phoneNumberDetail)) {
            qWarning() << "Unable to add phone number to contact:" << contactUri;
            return -1;
        }
    }

    QContactName nameDetail;
    nameDetail.setLastName(name);
    if (!contact.saveDetail(&nameDetail)) {
        qWarning() << "Unable to add name to contact:" << contactUri;
        return -1;
    }

    if (!manager()->saveContact(&contact)) {
        qWarning() << "Unable to store contact:" << contactUri;
        return -1;
    }

    // We should return the aggregated instance of this contact
    QContactRelationshipFilter filter;
    filter.setRelatedContactRole(QContactRelationship::Second);

#ifdef USING_QTPIM
    filter.setRelatedContact(contact);
    filter.setRelationshipType(QContactRelationship::Aggregates());
#else
    filter.setRelatedContactId(contact.id());
    filter.setRelationshipType(QContactRelationship::Aggregates);
#endif

    foreach (const ContactListener::ApiContactIdType &id, manager()->contactIds(filter)) {
        qDebug() << "********** contact id" << id;
        addedContactIds.insert(id);
        return ContactListener::internalContactId(id);
    }
/**
 * Method to get the result for a network request.
 * @param aOperation The type of operation to be requested
 * @param aTransportResult The result of transport operation
 * @param aResponse The QByteArray instance containing the network response.
 * The plugins should delete this instance once they have read the 
 * data from it.
 * @param aResult [out] An output parameter to the plugin manager.If the 
 * return value is SmfSendRequestAgain, QVariant will be of type 
 * SmfPluginRequestData.
 * For SmfGalleryPlugin: If last operation was pictures(), aResult will 
 * be of type QList<SmfPicture>. If last operation was description(), 
 * aResult will be of type QString. If last operation was upload() or 
 * postComment(), aResult will be of type bool.
 * @param aRetType [out] SmfPluginRetType
 * @param aPageResult [out] The SmfResultPage structure variable
 */
SmfPluginError FlickrContactFetcherPlugin::responseAvailable( 
		const SmfRequestTypeID aOperation,
		const SmfTransportResult &aTransportResult, 
		QByteArray *aResponse, 
		QVariant* aResult, 
		SmfPluginRetType &aRetType,
		SmfResultPage &aPageResult )
	{
	Q_UNUSED(aPageResult)
	qDebug()<<"Inside FlickrContactFetcherPlugin::responseAvailable()";
	
	SmfPluginError error = SmfPluginErrNetworkError;
	
	if( !aResponse || (0 == aResponse->size()) )
		{
		qDebug()<<"Response is NULL or empty";
		aRetType = SmfRequestError;
		return error;
		}
	
	QByteArray response(*aResponse);
	delete aResponse;
	
	QFile respFile("c://data//SmfPluginFlickrContactResponse.txt");
	if(!respFile.open(QIODevice::WriteOnly))
		{
		qDebug()<<"File to write the response could not be opened, so writing to this file";
		qDebug()<<"Flickr response = "<<QString(response);
		}
	else
		{
		respFile.write(response);
		respFile.close();
		qDebug()<<"Writing FB response to a file named 'SmfPluginFlickrContactResponse.txt'";
		}
	qDebug()<<"FB response size = "<<response.size();
	
	if(SmfTransportOpNoError == aTransportResult)
		{
		qDebug()<<"No transport error";
		
#ifndef TESTINGTHISFUNCTION	
		if(SmfContactGetFriends == aOperation)
#else
		if(SmfContactGetFriends == aOperation ||aOperation == SmfContactGetFollowers||aOperation== SmfContactSearch ||aOperation ==SmfContactSearchNear||aOperation ==SmfContactSearchInGroup)
#endif
			{
			qDebug()<<"For getting friends response";
			
			QList<SmfContact> list;
			
#ifdef SMF_XMLPARSING // Xml parsing
			// For getting contacts from xml response
			QXmlStreamReader xml(response);
			while (!xml.atEnd())
				{
				xml.readNext();
				if (xml.tokenType() == QXmlStreamReader::StartElement)
					{
					// If the tag is contact
					if (xml.name() == "contact")
						{
						qDebug()<<"Contact tag found";
						SmfContact contact;
						QStringRef str;
						QContactName contactname;
						QString username = xml.attributes().value("username").toString();
						qDebug()<<"Username = "******"Name",namevar1);
						list.append(contact);
						}
					}
				}
#else
			// To remove the "jsonFlickrApi(" and also remove the last ")" from the response,
			// as these gives a Json parsing error
			response.remove(0, 14);
			response.chop(1);
			
			// For getting contacts from json response
			bool ok;
			SmfPluginUtil util;
			QVariantMap result = util.parse(response, &ok).toMap();
			if (!ok) {
				qDebug()<<"An error occurred during json parsing";
				aResult->setValue(list);
				aRetType = SmfRequestError;
				return SmfPluginErrParsingFailed;
			}
			
			QVariantMap map1 = result["contacts"].toMap();
			qDebug()<<"page = "<<map1["page"].toString();
			qDebug()<<"pages = "<<map1["pages"].toString();
			qDebug()<<"per_page = "<<map1["per_page"].toString();
			qDebug()<<"perpage = "<<map1["perpage"].toString();
			qDebug()<<"total = "<<map1["perpage"].toString();
			
			QList<QVariant> list1 = map1["contact"].toList();
			
			QListIterator<QVariant> i(list1);
			while(i.hasNext())
				{
				SmfContact contact;
				QVariantMap map2 = i.next().toMap();
				qDebug()<<"nsid = "<<map2["nsid"].toString();
				qDebug()<<"username = "******"username"].toString();
				qDebug()<<"iconserver = "<<map2["iconserver"].toString();
				qDebug()<<"iconfarm = "<<map2["iconfarm"].toString();
				qDebug()<<"ignored = "<<map2["ignored"].toString();
				qDebug()<<"realname = "<<map2["realname"].toString();
				qDebug()<<"friend = "<<map2["friend"].toString();
				qDebug()<<"family = "<<map2["family"].toString();
				qDebug()<<"path_alias = "<<map2["path_alias"].toString();
				qDebug()<<"location = "<<map2["location"].toString();
				
				// Contact Name
				QContactName contactname;
				QString username = map2["username"].toString();
				qDebug()<<"Username = "******"Name",nameVar);
				
				// Contact's Flickr Specific ID to QContactGuid
				QContactGuid guid;
				guid.setGuid(map2["nsid"].toString());
				QVariant guidVar = QVariant::fromValue(guid);
				contact.setValue("Guid",guidVar);
					
				// Contact's profile image url
				QUrl url;
				if((0 == map2["iconfarm"].toInt()) && (0 == map2["iconserver"].toInt()))
					url = QString("http://www.flickr.com/images/buddyicon.jpg");
				else
					{
					QString str("http://farm");
					str.append(map2["iconfarm"].toString());
					str.append(".static.flickr.com/");
					str.append(map2["iconserver"].toString());
					str.append("/buddyicons/");
					str.append(map2["nsid"].toString());
					str.append(".jpg");
					url = str;
					}
				QContactAvatar avatar;
				qDebug()<<"Profile image URL = "<<url.toString();
				avatar.setImageUrl(url);
				QVariant avatarVar = QVariant::fromValue(avatar);
				contact.setValue("Avatar",avatarVar);
				
				
				list.append(contact);
				}
#endif
			
			qDebug()<<"list count = "<<list.count();
			aResult->setValue(list);
			aRetType = SmfRequestComplete;
			error = SmfPluginErrNone;
			}
		else if(aOperation==SmfContactGetGroups)
			{
		        response.remove(0, 14);
				response.chop(1);
			
			    bool ok;
				qDebug()<<"Before Parser--";

				SmfPluginUtil util;
				QVariant result = util.parse(response, &ok);
				if (!ok) 
				{
				    qDebug()<<"An error occurred during json parsing";
					aRetType = SmfRequestError;
					return SmfPluginErrParsingFailed;
								 //return 0;
				}
							
				QVariantMap map1 = result.toMap();
		        QList<SmfGroup> list;
				QVariantMap map2 = map1["groups"].toMap();
				int page = map2["page"].toInt(&ok);
				qDebug()<<"PAGE = "<<map2["page"].toString();
				QList<QVariant> list1 = map2["group"].toList();
				QListIterator<QVariant> iter(list1);
						
				//Getting the group list from QJson Parser 
				 while(iter.hasNext())
				 {
					QVariantMap map2 = iter.next().toMap();
					qDebug()<<"name = "<<map2["name"].toString();
					qDebug()<<"id = "<<map2["id"].toString();
					SmfGroup group;
					QString id(map2["id"].toString());
					group.setId(id);
					QString grpname(map2["name"].toString());
					group.setName(grpname);
						   
					list.append(group);
						   
				 }//end While
				 qDebug()<<"list count = "<<QString::number(list.count(),10);
				aResult->setValue(list);
			}
		else
			{
			qDebug()<<"Service unsupported, currently only SmfContactGetFriends !!!";
			aRetType = SmfRequestError;
			error = SmfPluginErrServiceNotSupported;
			}
		}

	else if(SmfTransportOpOperationCanceledError == aTransportResult)
		{
		qDebug()<<"Operation Cancelled !!!";
		error = SmfPluginErrCancelComplete;
		aRetType = SmfRequestComplete;
		}

	else
		{
		qDebug()<<"Transport Error !!!";
		error = SmfPluginErrNetworkError;
		aRetType = SmfRequestError;
		}
	
	return error;
	}
Exemplo n.º 9
0
void SymbianPluginPerfomance::createComplexContacts()
{
    // Create N contacts
    QList<QContact> contactsList;
    for(int i=0; i<NO_OF_CONTACTS; i++) {
        QContact alice;

        // Contact details
        QString c = QString::number(i);
        QString first("Alice");
        QString last("Jones");

        QContactName aliceName;
        aliceName.setFirstName(first.append(c));
        aliceName.setLastName(last.append(c));
        alice.saveDetail(&aliceName);

        QContactPhoneNumber number;
        number.setContexts("Home");
        number.setSubTypes("Mobile");
        number.setNumber("12345678");
        alice.saveDetail(&number);
        alice.setPreferredDetail("DialAction", number);

        QContactPhoneNumber number2;
        number2.setContexts("Work");
        number2.setSubTypes("Landline");
        number2.setNumber("555-4444");
        alice.saveDetail(&number2);

        QContactAddress add;
        add.setStreet("Leeds West Yorkshire");
        add.setPostcode("10087");
        add.setRegion("New York");
        add.setCountry("United States");
        alice.saveDetail(&add);

        /* Commented out to ensure compatibility with pre-10.1 platforms
        QContactGender gender;
        gender.setGender("Female");
        alice.saveDetail(&gender);
        */

        QContactBirthday bday;
        bday.setDate(QDate(25,10,1978));
        alice.saveDetail(&bday);

        /* Commented out to ensure compatibility with pre-10.1 platforms
        QContactOnlineAccount acc;
        acc.setAccountUri("sips:[email protected]");
        acc.setSubTypes(QContactOnlineAccount::SubTypeSip);
        alice.saveDetail(&acc);
        */

        QContactEmailAddress email;
        email.setEmailAddress("mailto:[email protected]");
        alice.saveDetail(&email);

        QContactOrganization org;
        org.setDepartment(QStringList("Services"));
        org.setTitle("Assistant Manager");
        // Commented out to ensure compatibility with pre-10.1 platforms
        //org.setLocation("Nokia Cyber Park");
        alice.saveDetail(&org);

        contactsList.append(alice);
    }
    // Save the contacts
    mTime.restart();
    QMap<int, QContactManager::Error> errors;
    mCntMng->saveContacts(&contactsList, &errors);
    foreach(QContactManager::Error error, errors) {
        QCOMPARE(error, QContactManager::NoError);
    }
void TestCntPresenceInfoProvider::testRequestInfo()
{
    PrcPresenceWriter *writer = PrcPresenceWriter::createWriter();
    
    PrcPresenceBuddyInfoQt *buddy = PrcPresenceBuddyInfoQt::createInstance();
    buddy->setIdentity("sip:[email protected]");
    buddy->setAvailability(PrcPresenceBuddyInfoQt::PrcNotAvailable, "meh");
    writer->writePresence(*buddy);
    
    QContactManager manager("symbian");
    
    QContact c;
    QContactName name;
    name.setFirstName("firstname");
    name.setLastName("lastname");
    c.saveDetail(&name);
    QContactPhoneNumber number;
    number.setNumber("1234567");
    number.setContexts(QContactDetail::ContextHome);
    number.setSubTypes(QContactPhoneNumber::SubTypeMobile);
    c.saveDetail(&number);
    manager.saveContact(&c);
    
    ContactInfoFields fields;
    fields = ContactInfoTextField;
    
    QSignalSpy spy(mCntPresenceInfoProvider, SIGNAL(infoFieldReady(CntInfoProvider*, int, ContactInfoField, const QString&)));
    
    mCntPresenceInfoProvider->requestInfo(c, fields);
    QCOMPARE(spy.count(), 0);
    QVERIFY(mCntPresenceInfoProvider->mBuddyMap.isEmpty());
    
    fields = ContactInfoIcon2Field;
    
    mCntPresenceInfoProvider->requestInfo(c, fields);
    QCOMPARE(spy.count(), 0);
    QVERIFY(mCntPresenceInfoProvider->mBuddyMap.isEmpty());
    
    QContactOnlineAccount account;
    account.setSubTypes(QStringList() << QContactOnlineAccount::SubTypeSip);
    account.setServiceProvider("sip");
    account.setAccountUri("*****@*****.**");
    c.saveDetail(&account);
    QContactOnlineAccount account2;
    account2.setSubTypes(QStringList() << QContactOnlineAccount::SubTypeSipVoip);
    account.setServiceProvider("sip");
    account2.setAccountUri("*****@*****.**");
    c.saveDetail(&account2);
    QContactOnlineAccount account3;
    account3.setSubTypes(QStringList() << QContactOnlineAccount::SubTypeSip);
    account3.setAccountUri("malformatted");
    c.saveDetail(&account3);
    manager.saveContact(&c);
    
    mCntPresenceInfoProvider->requestInfo(c, fields);
    QCOMPARE(spy.count(), 0);
    QCOMPARE(mCntPresenceInfoProvider->mBuddyMap.count(), 1);
    
    delete mCntPresenceInfoProvider;
    mCntPresenceInfoProvider = NULL;
    
    buddy->setAvailability(PrcPresenceBuddyInfoQt::PrcAvailable, "meh");
    writer->writePresence(*buddy);
    
    mCntPresenceInfoProvider = new CntPresenceInfoProvider();
    
    QSignalSpy spy2(mCntPresenceInfoProvider, SIGNAL(infoFieldReady(CntInfoProvider*, int, ContactInfoField, const QString&)));
    mCntPresenceInfoProvider->requestInfo(c, fields);
    QCOMPARE(spy2.count(), 1);
    QCOMPARE(mCntPresenceInfoProvider->mBuddyMap.count(), 1);
    
    delete buddy;
    delete writer;
}
void AsyncRequestExample::performRequests()
{
//! [Creating a new contact in a manager]
    QContact exampleContact;

    QContactName nameDetail;
    nameDetail.setFirstName("Adam");
    nameDetail.setLastName("Unlikely");

    QContactPhoneNumber phoneNumberDetail;
    phoneNumberDetail.setNumber("+123 4567");

    exampleContact.saveDetail(&nameDetail);
    exampleContact.saveDetail(&phoneNumberDetail);

    // save the newly created contact in the manager
    connect(&m_contactSaveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(contactSaveRequestStateChanged(QContactAbstractRequest::State)));
    m_contactSaveRequest.setManager(m_manager);
    m_contactSaveRequest.setContacts(QList<QContact>() << exampleContact);
    m_contactSaveRequest.start();
//! [Creating a new contact in a manager]

    m_contactSaveRequest.waitForFinished();

//! [Creating a new contact in a manager waiting until finished]
    m_contactSaveRequest.setManager(m_manager);
    m_contactSaveRequest.setContacts(QList<QContact>() << exampleContact);
    m_contactSaveRequest.start();
    m_contactSaveRequest.waitForFinished();
    QList<QContact> savedContacts = m_contactSaveRequest.contacts();
//! [Creating a new contact in a manager waiting until finished]

//! [Filtering contacts from a manager]
    connect(&m_contactFetchRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(contactFetchRequestStateChanged(QContactAbstractRequest::State)));
    m_contactFetchRequest.setManager(m_manager);
    m_contactFetchRequest.setFilter(QContactPhoneNumber::match("+123 4567"));
    m_contactFetchRequest.start();
//! [Filtering contacts from a manager]

    m_contactFetchRequest.waitForFinished();

//! [Retrieving an existing contact from a manager]
    QContactLocalIdFilter idListFilter;
    idListFilter.setIds(QList<QContactLocalId>() << exampleContact.localId());
    m_contactFetchRequest.setManager(m_manager);
    m_contactFetchRequest.setFilter(idListFilter);
    m_contactFetchRequest.start();
//! [Retrieving an existing contact from a manager]

    m_contactFetchRequest.waitForFinished();

//! [Updating an existing contact in a manager]
    phoneNumberDetail.setNumber("+123 9876");
    exampleContact.saveDetail(&phoneNumberDetail);
    m_contactSaveRequest.setManager(m_manager);
    m_contactSaveRequest.setContacts(QList<QContact>() << exampleContact);
    m_contactSaveRequest.start();
//! [Updating an existing contact in a manager]

    m_contactFetchRequest.waitForFinished();

//! [Removing a contact from a manager]
    connect(&m_contactRemoveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(contactRemoveRequestStateChanged(QContactAbstractRequest::State)));
    m_contactRemoveRequest.setManager(m_manager);
    m_contactRemoveRequest.setContactIds(QList<QContactLocalId>() << exampleContact.localId());
    m_contactRemoveRequest.start();
//! [Removing a contact from a manager]

    m_contactFetchRequest.waitForFinished();

//! [Creating a new relationship between two contacts]
    // first, create the group and the group member
    QContact exampleGroup;
    exampleGroup.setType(QContactType::TypeGroup);
    QContactNickname groupName;
    groupName.setNickname("Example Group");
    exampleGroup.saveDetail(&groupName);
    
    QContact exampleGroupMember;
    QContactName groupMemberName;
    groupMemberName.setFirstName("Member");
    exampleGroupMember.saveDetail(&groupMemberName);

    // second, save those contacts in the manager
    QList<QContact> saveList;
    saveList << exampleGroup << exampleGroupMember;
    m_contactSaveRequest.setContacts(saveList);
    m_contactSaveRequest.start();
    m_contactSaveRequest.waitForFinished();

    // third, create the relationship between those contacts
    QContactRelationship groupRelationship;
    groupRelationship.setFirst(exampleGroup.id());
    groupRelationship.setRelationshipType(QContactRelationship::HasMember);
    groupRelationship.setSecond(exampleGroupMember.id());

    // finally, save the relationship in the manager
    connect(&m_relationshipSaveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(relationshipSaveRequestStateChanged(QContactAbstractRequest::State)));
    m_relationshipSaveRequest.setManager(m_manager);
    m_relationshipSaveRequest.setRelationships(QList<QContactRelationship>() << groupRelationship);
    m_relationshipSaveRequest.start();
//! [Creating a new relationship between two contacts]

    m_contactFetchRequest.waitForFinished();

//! [Retrieving relationships between contacts]
    connect(&m_relationshipFetchRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(relationshipFetchRequestStateChanged(QContactAbstractRequest::State)));
    m_relationshipFetchRequest.setManager(m_manager);
    // retrieve the list of relationships between the example group contact and the example member contact
    // where the group contact is the first contact in the relationship, and the member contact is the
    // second contact in the relationship.  In order to fetch all relationships between them, another
    // relationship fetch must be performed with their roles reversed, and the results added together.
    m_relationshipFetchRequest.setFirst(exampleGroup.id());
    m_relationshipFetchRequest.setSecond(exampleGroupMember.id());
    m_relationshipFetchRequest.start();
//! [Retrieving relationships between contacts]

    m_contactFetchRequest.waitForFinished();

//! [Providing a fetch hint]
    QContactFetchHint hasMemberRelationshipsOnly;
    hasMemberRelationshipsOnly.setRelationshipTypesHint(QStringList(QContactRelationship::HasMember));

    m_contactFetchRequest.setManager(m_manager);
    m_contactFetchRequest.setFilter(QContactFilter()); // all contacts
    m_contactFetchRequest.setFetchHint(hasMemberRelationshipsOnly);
    m_contactFetchRequest.start();
//! [Providing a fetch hint]

//! [Removing a relationship]
    connect(&m_relationshipRemoveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(relationshipRemoveRequestStateChanged(QContactAbstractRequest::State)));
    m_relationshipRemoveRequest.setManager(m_manager);
    m_relationshipRemoveRequest.setRelationships(QList<QContactRelationship>() << groupRelationship);
    m_relationshipRemoveRequest.start();
//! [Removing a relationship]

    connect(&m_definitionFetchRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(definitionFetchRequestStateChanged(QContactAbstractRequest::State)));
//! [Querying the schema supported by a manager]
    m_definitionFetchRequest.setManager(m_manager);
    m_definitionFetchRequest.setDefinitionNames(QStringList(QContactName::DefinitionName));
    m_definitionFetchRequest.start();
    m_definitionFetchRequest.waitForFinished();
    QMap<QString, QContactDetailDefinition> definitions = m_definitionFetchRequest.definitions();
    qDebug() << "This manager"
             << (definitions.value(QContactName::DefinitionName).fields().contains(QContactName::FieldCustomLabel) ? "supports" : "does not support")
             << "the custom label field of QContactName";
//! [Querying the schema supported by a manager]

    connect(&m_definitionSaveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(definitionSaveRequestStateChanged(QContactAbstractRequest::State)));
    connect(&m_definitionRemoveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(definitionRemoveRequestStateChanged(QContactAbstractRequest::State)));
//! [Modifying the schema supported by a manager]
    // modify the name definition, adding a patronym field
    QContactDetailDefinition nameDefinition = definitions.value(QContactName::DefinitionName);
    QContactDetailFieldDefinition fieldPatronym;
    fieldPatronym.setDataType(QVariant::String);
    nameDefinition.insertField("Patronym", fieldPatronym);

    // save the updated definition in the manager if supported...
    if (m_manager->hasFeature(QContactManager::MutableDefinitions)) {
        m_definitionSaveRequest.setManager(m_manager);
        m_definitionSaveRequest.setContactType(QContactType::TypeContact);
        m_definitionSaveRequest.setDefinitions(QList<QContactDetailDefinition>() << nameDefinition);
        m_definitionSaveRequest.start();
    }
//! [Modifying the schema supported by a manager]

    QCoreApplication::exit(0);
}